text
stringlengths
2
1.04M
meta
dict
package com.kubakhov.vaadin.ui.field.impl; import static com.kubakhov.collections.provider.factory.CollectionProviderFactory.getCollectionHelper; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.beanutils.PropertyUtils; import org.vaadin.viritin.LazyList; import org.vaadin.viritin.fields.CaptionGenerator; import org.vaadin.viritin.fields.LazyComboBox; import com.vaadin.data.Property; import com.vaadin.server.ErrorMessage; import com.vaadin.ui.ComboBox; public class LazyComboBoxExt<T> extends LazyComboBox<T> { private static final String INVALID_ERROR_MESSAGE = "Invalid property type"; private String itemCaptionPropertyId; @Override public void setPropertyDataSource(Property newDataSource) { if (!getCollectionHelper().canHandle(newDataSource.getType())) { setError(newDataSource.getType()); return; } List<T> list = getCollectionHelper().getList(newDataSource.getType()); initList(newDataSource.getType(), new FilterablePagingProviderImpl(list, LazyList.DEFAULT_PAGE_SIZE), new FilterableCountProviderImpl(list), LazyList.DEFAULT_PAGE_SIZE); super.setPropertyDataSource(newDataSource); super.setCaptionGenerator(new CaptionGeneratorImpl()); } @Override public void setRequired(boolean required) { setNullSelectionAllowed(!required); super.setRequired(required); } private void setError(Class propertyType) { setReadOnly(true); setComponentError(new ErrorMessage() { @Override public String getFormattedHtmlMessage() { return INVALID_ERROR_MESSAGE; } @Override public ErrorLevel getErrorLevel() { return ErrorLevel.ERROR; } }); Logger.getLogger(LazyComboBoxExt.class.getName()).log(Level.SEVERE, INVALID_ERROR_MESSAGE + " {0}", propertyType); } public ComboBox getComboBox() { return (ComboBox) getSelect(); } private class CaptionGeneratorImpl<T> implements CaptionGenerator<T> { @Override public String getCaption(T option) { if (itemCaptionPropertyId == null || itemCaptionPropertyId.isEmpty()) return option.toString(); String error = null; try { return String.valueOf(PropertyUtils.getNestedProperty(option, itemCaptionPropertyId)); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { Logger.getLogger(LazyComboBoxExt.class.getName()).log(Level.SEVERE, e.getMessage(), e); error = e.getMessage(); } return error; } } private class FilterablePagingProviderImpl<T> implements FilterablePagingProvider<T> { private final List<T> list; private final int pageSize; public FilterablePagingProviderImpl(List<T> list, int pageSize) { this.list = list; this.pageSize = pageSize; } @Override public List<T> findEntities(int firstRow, String filter) { return list.subList(firstRow, firstRow + pageSize > list.size() ? list.size() : firstRow + pageSize); } } private class FilterableCountProviderImpl implements FilterableCountProvider { private final List<T> list; public FilterableCountProviderImpl(List<T> list) { this.list = list; } @Override public int size(String filter) { return list.size(); } } public void setItemCaptionPropertyId(String itemCaptionPropertyId) { this.itemCaptionPropertyId = itemCaptionPropertyId; } public String getItemCaptionPropertyId() { return itemCaptionPropertyId; } }
{ "content_hash": "fdcf8bacaadf715833e8f7451873389d", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 104, "avg_line_length": 28.352459016393443, "alnum_prop": 0.7617808615206707, "repo_name": "DmitryKubahov/VESB", "id": "7491c4be44b3c14e0993c6a3b3408acd4799b14c", "size": "3459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vaadin/ui/xml-form-component-handlers/combobox-handler/src/main/java/com/kubakhov/vaadin/ui/field/impl/LazyComboBoxExt.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "3284" }, { "name": "Java", "bytes": "334230" } ], "symlink_target": "" }
<?php namespace Zimbra\Admin\Struct; use Zimbra\Struct\Base; /** * StatsSpec struct class * * @package Zimbra * @subpackage Admin * @category Struct * @author Nguyen Van Nguyen - nguyennv1981@gmail.com * @copyright Copyright © 2013 by Nguyen Van Nguyen. */ class StatsSpec extends Base { /** * Constructor method for StatsSpec * @param StatsValueWrapper $values * @param string $name * @param string $limit * @return self */ public function __construct(StatsValueWrapper $values, $name = null, $limit = null) { parent::__construct(); $this->setChild('values', $values); if(null !== $name) { $this->setProperty('name', trim($name)); } if(null !== $limit) { $this->setProperty('limit', trim($limit)); } } /** * Gets the values. * * @return StatsValueWrapper */ public function getValues() { return $this->getChild('values'); } /** * Sets the values. * * @param StatsValueWrapper $values * @return self */ public function setValues(StatsValueWrapper $values) { return $this->setChild('values', $values); } /** * Gets the name * * @return string */ public function getName() { return $this->getProperty('name'); } /** * Sets the name * * @param string $name * @return self */ public function setName($name) { return $this->setProperty('name', trim($name)); } /** * Gets the limit * * @return string */ public function getLimit() { return $this->getProperty('limit'); } /** * Sets the limit * * @param string $limit * @return self */ public function setLimit($limit) { return $this->setProperty('limit', trim($limit)); } /** * Returns the array representation of this class * * @param string $name * @return array */ public function toArray($name = 'stats') { return parent::toArray($name); } /** * Method returning the xml representative this class * * @param string $name * @return SimpleXML */ public function toXml($name = 'stats') { return parent::toXml($name); } }
{ "content_hash": "318e4c6141446b7afdd58d87afd3f2d7", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 87, "avg_line_length": 19.483870967741936, "alnum_prop": 0.5293874172185431, "repo_name": "malaleche/api-zimbra", "id": "d7e807a96e72bf04bb528ddeab99b32f09c03b32", "size": "2661", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Zimbra/Admin/Struct/StatsSpec.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "4095679" } ], "symlink_target": "" }
<?php namespace PLL\SocialBundle\Event; use PLL\PushBundle\Event\UserToUserEvent; class FriendshipRequestAcceptedEvent extends UserToUserEvent { } ?>
{ "content_hash": "4b075607022847a9ef9d3d647858a20e", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 60, "avg_line_length": 14.090909090909092, "alnum_prop": 0.8064516129032258, "repo_name": "Kishlin/Ehub", "id": "ce317b5817a36620fdf511aa9b831d98efb6c49a", "size": "155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PLL/SocialBundle/Event/FriendshipRequestAcceptedEvent.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "4714" }, { "name": "HTML", "bytes": "159442" }, { "name": "JavaScript", "bytes": "47809" }, { "name": "PHP", "bytes": "516750" } ], "symlink_target": "" }
The Library contains the Database classes for Redis based objects database client. ## License Apache 2.0 Copyright 2018-2022 bluefox <dogafox@gmail.com>
{ "content_hash": "82830bdaad48285732fe24b2ec368466", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 82, "avg_line_length": 31.2, "alnum_prop": 0.7948717948717948, "repo_name": "ioBroker/ioBroker.js-controller", "id": "4f2ef75cdbfdaebcc699fe367174dd3f75d1e93f", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/db-objects-redis/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "549" }, { "name": "JavaScript", "bytes": "1215448" }, { "name": "Lua", "bytes": "15416" }, { "name": "Shell", "bytes": "2186" }, { "name": "Smarty", "bytes": "1687" }, { "name": "TypeScript", "bytes": "1325892" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>V8 API Reference Guide for node.js v8.9.0: v8::SharedArrayBuffer::Contents 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="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="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v8.9.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <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&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</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> <li><a href="examples.html"><span>Examples</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&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- 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="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1SharedArrayBuffer.html">SharedArrayBuffer</a></li><li class="navelem"><a class="el" href="classv8_1_1SharedArrayBuffer_1_1Contents.html">Contents</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#friends">Friends</a> &#124; <a href="classv8_1_1SharedArrayBuffer_1_1Contents-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">v8::SharedArrayBuffer::Contents Class Reference</div> </div> </div><!--header--> <div class="contents"> <p><code>#include &lt;<a class="el" href="v8_8h_source.html">v8.h</a>&gt;</code></p> <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:a7e25a8f041d968fb7af4c4ae72dd2dc7"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a7e25a8f041d968fb7af4c4ae72dd2dc7"></a> void *&#160;</td><td class="memItemRight" valign="bottom"><b>Data</b> () const </td></tr> <tr class="separator:a7e25a8f041d968fb7af4c4ae72dd2dc7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a68fb3080f3304278ec47c2cfddfec0ae"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a68fb3080f3304278ec47c2cfddfec0ae"></a> size_t&#160;</td><td class="memItemRight" valign="bottom"><b>ByteLength</b> () const </td></tr> <tr class="separator:a68fb3080f3304278ec47c2cfddfec0ae"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a> Friends</h2></td></tr> <tr class="memitem:a35ac2a80dda42f728b7b1dfc4c3cc040"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a35ac2a80dda42f728b7b1dfc4c3cc040"></a> class&#160;</td><td class="memItemRight" valign="bottom"><b>SharedArrayBuffer</b></td></tr> <tr class="separator:a35ac2a80dda42f728b7b1dfc4c3cc040"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>The contents of an |SharedArrayBuffer|. Externalization of |SharedArrayBuffer| returns an instance of this class, populated, with a pointer to data and byte length.</p> <p>The <a class="el" href="classv8_1_1Data.html">Data</a> pointer of <a class="el" href="classv8_1_1SharedArrayBuffer_1_1Contents.html">SharedArrayBuffer::Contents</a> is always allocated with |ArrayBuffer::Allocator::Allocate| by the allocator specified in <a class="el" href="structv8_1_1Isolate_1_1CreateParams.html#a7c663f70b64290392eeaf164f57585f9">v8::Isolate::CreateParams::array_buffer_allocator</a>.</p> <p>This API is experimental and may change significantly. </p> </div><hr/>The documentation for this class was generated from the following file:<ul> <li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{ "content_hash": "e66d8057c6fc51ceafc0bf1f059f571a", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 412, "avg_line_length": 53.29323308270677, "alnum_prop": 0.6779063205417607, "repo_name": "v8-dox/v8-dox.github.io", "id": "2a5363d0806260f03601742f3d2a71840694c029", "size": "7088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bf2564d/html/classv8_1_1SharedArrayBuffer_1_1Contents.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
class Store { public: void StoreFront(Player*); }; #endif // STORE_H
{ "content_hash": "ac5800467a2689a59a3e30e8d062b219", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 33, "avg_line_length": 13.666666666666666, "alnum_prop": 0.573170731707317, "repo_name": "AlissaWe/Turn", "id": "f550381e6015d545d65eeaf76e724132781695a3", "size": "136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Turn/include/Store.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "361" }, { "name": "C++", "bytes": "69428" }, { "name": "CMake", "bytes": "574" } ], "symlink_target": "" }
from setuptools import setup setup( name='sql_query_dict', version='0.10', description='express sql queries as python dictionaries', url='http://github.com/PlotWatt/sql_query_dict', author='PlotWatt', author_email='zdwiel@plotwatt.com', license='Apache', py_modules=['sql_query_dict'], install_requires=['six'], )
{ "content_hash": "480f93283b96f092573c6c1f4b3c348a", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 61, "avg_line_length": 25.142857142857142, "alnum_prop": 0.6647727272727273, "repo_name": "PlotWatt/sql_query_dict", "id": "b13aba60192594e6bb4c62891487351503363798", "size": "352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "10911" } ], "symlink_target": "" }
<<<<<<< HEAD //=========================================================================== #include <stdarg.h> #include <cstdlib> #include <cstring> #include <string.h> #include <stdlib.h> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #endif #include <v8.h> // this and the above block must be around the v8.h header otherwise // v8 is not happy #ifdef __clang__ #pragma clang diagnostic pop #endif #include <node.h> #include <node_version.h> #include <node_buffer.h> #include <cmath> #include <iostream> #include <limits> #include <vector> #ifdef __sun #include <alloca.h> #endif #include "bson.h" using namespace v8; using namespace node; //=========================================================================== void DataStream::WriteObjectId(const Handle<Object>& object, const Handle<String>& key) { uint16_t buffer[12]; object->Get(key)->ToString()->Write(buffer, 0, 12); for(uint32_t i = 0; i < 12; ++i) { *p++ = (char) buffer[i]; } } void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) { va_list args; va_start(args, format); char* string = (char*) malloc(allocationSize); vsprintf(string, format, args); va_end(args); throw string; } void DataStream::CheckKey(const Local<String>& keyName) { size_t keyLength = keyName->Utf8Length(); if(keyLength == 0) return; // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it char* keyStringBuffer = (char*) alloca(keyLength + 1); // Write the key to the allocated buffer keyName->WriteUtf8(keyStringBuffer); // Check for the zero terminator char* terminator = strchr(keyStringBuffer, 0x00); // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere if(terminator != &keyStringBuffer[keyLength]) { ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); } if(keyStringBuffer[0] == '$') { ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); } if(strchr(keyStringBuffer, '.') != NULL) { ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); } } template<typename T> void BSONSerializer<T>::SerializeDocument(const Handle<Value>& value) { void* documentSize = this->BeginWriteSize(); Local<Object> object = bson->GetSerializeObject(value); // Get the object property names #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 Local<Array> propertyNames = object->GetPropertyNames(); #else Local<Array> propertyNames = object->GetOwnPropertyNames(); #endif // Length of the property int propertyLength = propertyNames->Length(); for(int i = 0; i < propertyLength; ++i) { const Local<String>& propertyName = propertyNames->Get(i)->ToString(); if(checkKeys) this->CheckKey(propertyName); const Local<Value>& propertyValue = object->Get(propertyName); if(serializeFunctions || !propertyValue->IsFunction()) { void* typeLocation = this->BeginWriteType(); this->WriteString(propertyName); SerializeValue(typeLocation, propertyValue); } } this->WriteByte(0); this->CommitSize(documentSize); } template<typename T> void BSONSerializer<T>::SerializeArray(const Handle<Value>& value) { void* documentSize = this->BeginWriteSize(); Local<Array> array = Local<Array>::Cast(value->ToObject()); uint32_t arrayLength = array->Length(); for(uint32_t i = 0; i < arrayLength; ++i) { void* typeLocation = this->BeginWriteType(); this->WriteUInt32String(i); SerializeValue(typeLocation, array->Get(i)); } this->WriteByte(0); this->CommitSize(documentSize); } // This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. // The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) // and ensures that there is always consistency between bytes counted and bytes written by design. template<typename T> void BSONSerializer<T>::SerializeValue(void* typeLocation, const Handle<Value>& value) { if(value->IsNumber()) { double doubleValue = value->NumberValue(); int intValue = (int) doubleValue; if(intValue == doubleValue) { this->CommitType(typeLocation, BSON_TYPE_INT); this->WriteInt32(intValue); } else { this->CommitType(typeLocation, BSON_TYPE_NUMBER); this->WriteDouble(doubleValue); } } else if(value->IsString()) { this->CommitType(typeLocation, BSON_TYPE_STRING); this->WriteLengthPrefixedString(value->ToString()); } else if(value->IsBoolean()) { this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); this->WriteBool(value); } else if(value->IsArray()) { this->CommitType(typeLocation, BSON_TYPE_ARRAY); SerializeArray(value); } else if(value->IsDate()) { this->CommitType(typeLocation, BSON_TYPE_DATE); this->WriteInt64(value); } else if(value->IsRegExp()) { this->CommitType(typeLocation, BSON_TYPE_REGEXP); const Handle<RegExp>& regExp = Handle<RegExp>::Cast(value); this->WriteString(regExp->GetSource()); int flags = regExp->GetFlags(); if(flags & RegExp::kGlobal) this->WriteByte('s'); if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); if(flags & RegExp::kMultiline) this->WriteByte('m'); this->WriteByte(0); } else if(value->IsFunction()) { this->CommitType(typeLocation, BSON_TYPE_CODE); this->WriteLengthPrefixedString(value->ToString()); } else if(value->IsObject()) { const Local<Object>& object = value->ToObject(); if(object->Has(bson->_bsontypeString)) { const Local<String>& constructorString = object->GetConstructorName(); if(bson->longString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_LONG); this->WriteInt32(object, bson->_longLowString); this->WriteInt32(object, bson->_longHighString); } else if(bson->timestampString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); this->WriteInt32(object, bson->_longLowString); this->WriteInt32(object, bson->_longHighString); } else if(bson->objectIDString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_OID); this->WriteObjectId(object, bson->_objectIDidString); } else if(bson->binaryString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_BINARY); uint32_t length = object->Get(bson->_binaryPositionString)->Uint32Value(); Local<Object> bufferObj = object->Get(bson->_binaryBufferString)->ToObject(); this->WriteInt32(length); this->WriteByte(object, bson->_binarySubTypeString); // write subtype // If type 0x02 write the array length aswell if(object->Get(bson->_binarySubTypeString)->Int32Value() == 0x02) { this->WriteInt32(length); } // Write the actual data this->WriteData(Buffer::Data(bufferObj), length); } else if(bson->doubleString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_NUMBER); this->WriteDouble(object, bson->_doubleValueString); } else if(bson->symbolString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_SYMBOL); this->WriteLengthPrefixedString(object->Get(bson->_symbolValueString)->ToString()); } else if(bson->codeString->StrictEquals(constructorString)) { const Local<String>& function = object->Get(bson->_codeCodeString)->ToString(); const Local<Object>& scope = object->Get(bson->_codeScopeString)->ToObject(); // For Node < 0.6.X use the GetPropertyNames #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); #else uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); #endif if(propertyNameLength > 0) { this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); void* codeWidthScopeSize = this->BeginWriteSize(); this->WriteLengthPrefixedString(function->ToString()); SerializeDocument(scope); this->CommitSize(codeWidthScopeSize); } else { this->CommitType(typeLocation, BSON_TYPE_CODE); this->WriteLengthPrefixedString(function->ToString()); } } else if(bson->dbrefString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_OBJECT); void* dbRefSize = this->BeginWriteSize(); void* refType = this->BeginWriteType(); this->WriteData("$ref", 5); SerializeValue(refType, object->Get(bson->_dbRefNamespaceString)); void* idType = this->BeginWriteType(); this->WriteData("$id", 4); SerializeValue(idType, object->Get(bson->_dbRefOidString)); const Local<Value>& refDbValue = object->Get(bson->_dbRefDbString); if(!refDbValue->IsUndefined()) { void* dbType = this->BeginWriteType(); this->WriteData("$db", 4); SerializeValue(dbType, refDbValue); } this->WriteByte(0); this->CommitSize(dbRefSize); } else if(bson->minKeyString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); } else if(bson->maxKeyString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); } } else if(Buffer::HasInstance(value)) { this->CommitType(typeLocation, BSON_TYPE_BINARY); #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 Buffer *buffer = ObjectWrap::Unwrap<Buffer>(value->ToObject()); uint32_t length = object->length(); #else uint32_t length = Buffer::Length(value->ToObject()); #endif this->WriteInt32(length); this->WriteByte(0); this->WriteData(Buffer::Data(value->ToObject()), length); } else { this->CommitType(typeLocation, BSON_TYPE_OBJECT); SerializeDocument(value); } } else if(value->IsNull() || value->IsUndefined()) { this->CommitType(typeLocation, BSON_TYPE_NULL); } } // Data points to start of element list, length is length of entire document including '\0' but excluding initial size BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) : bson(aBson), pStart(data), p(data), pEnd(data + length - 1) { if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); } BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) : bson(parentSerializer.bson), pStart(parentSerializer.p), p(parentSerializer.p), pEnd(parentSerializer.p + length - 1) { parentSerializer.p += length; if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); } Local<String> BSONDeserializer::ReadCString() { char* start = p; while(*p++) { } return String::New(start, (int32_t) (p-start-1) ); } int32_t BSONDeserializer::ReadRegexOptions() { int32_t options = 0; for(;;) { switch(*p++) { case '\0': return options; case 's': options |= RegExp::kGlobal; break; case 'i': options |= RegExp::kIgnoreCase; break; case 'm': options |= RegExp::kMultiline; break; } } } uint32_t BSONDeserializer::ReadIntegerString() { uint32_t value = 0; while(*p) { if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); value = value * 10 + *p++ - '0'; } ++p; return value; } Local<String> BSONDeserializer::ReadString() { uint32_t length = ReadUInt32(); char* start = p; p += length; return String::New(start, length-1); } Local<String> BSONDeserializer::ReadObjectId() { uint16_t objectId[12]; for(size_t i = 0; i < 12; ++i) { objectId[i] = *reinterpret_cast<unsigned char*>(p++); } return String::New(objectId, 12); } Handle<Value> BSONDeserializer::DeserializeDocument(bool promoteLongs) { uint32_t length = ReadUInt32(); if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); BSONDeserializer documentDeserializer(*this, length-4); return documentDeserializer.DeserializeDocumentInternal(promoteLongs); } Handle<Value> BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) { Local<Object> returnObject = Object::New(); while(HasMoreData()) { BsonType type = (BsonType) ReadByte(); const Local<String>& name = ReadCString(); const Handle<Value>& value = DeserializeValue(type, promoteLongs); returnObject->ForceSet(name, value); } if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); // From JavaScript: // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); if(returnObject->Has(bson->_dbRefIdRefString)) { Local<Value> argv[] = { returnObject->Get(bson->_dbRefRefString), returnObject->Get(bson->_dbRefIdRefString), returnObject->Get(bson->_dbRefDbRefString) }; return bson->dbrefConstructor->NewInstance(3, argv); } else { return returnObject; } } Handle<Value> BSONDeserializer::DeserializeArray(bool promoteLongs) { uint32_t length = ReadUInt32(); if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); BSONDeserializer documentDeserializer(*this, length-4); return documentDeserializer.DeserializeArrayInternal(promoteLongs); } Handle<Value> BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) { Local<Array> returnArray = Array::New(); while(HasMoreData()) { BsonType type = (BsonType) ReadByte(); uint32_t index = ReadIntegerString(); const Handle<Value>& value = DeserializeValue(type, promoteLongs); returnArray->Set(index, value); } if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); return returnArray; } Handle<Value> BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) { switch(type) { case BSON_TYPE_STRING: return ReadString(); case BSON_TYPE_INT: return Integer::New(ReadInt32()); case BSON_TYPE_NUMBER: return Number::New(ReadDouble()); case BSON_TYPE_NULL: return Null(); case BSON_TYPE_UNDEFINED: return Undefined(); case BSON_TYPE_TIMESTAMP: { int32_t lowBits = ReadInt32(); int32_t highBits = ReadInt32(); Local<Value> argv[] = { Int32::New(lowBits), Int32::New(highBits) }; return bson->timestampConstructor->NewInstance(2, argv); } case BSON_TYPE_BOOLEAN: return (ReadByte() != 0) ? True() : False(); case BSON_TYPE_REGEXP: { const Local<String>& regex = ReadCString(); int32_t options = ReadRegexOptions(); return RegExp::New(regex, (RegExp::Flags) options); } case BSON_TYPE_CODE: { const Local<Value>& code = ReadString(); const Local<Value>& scope = Object::New(); Local<Value> argv[] = { code, scope }; return bson->codeConstructor->NewInstance(2, argv); } case BSON_TYPE_CODE_W_SCOPE: { ReadUInt32(); const Local<Value>& code = ReadString(); const Handle<Value>& scope = DeserializeDocument(promoteLongs); Local<Value> argv[] = { code, scope->ToObject() }; return bson->codeConstructor->NewInstance(2, argv); } case BSON_TYPE_OID: { Local<Value> argv[] = { ReadObjectId() }; return bson->objectIDConstructor->NewInstance(1, argv); } case BSON_TYPE_BINARY: { uint32_t length = ReadUInt32(); uint32_t subType = ReadByte(); if(subType == 0x02) { length = ReadInt32(); } Buffer* buffer = Buffer::New(p, length); p += length; Handle<Value> argv[] = { buffer->handle_, Uint32::New(subType) }; return bson->binaryConstructor->NewInstance(2, argv); } case BSON_TYPE_LONG: { // Read 32 bit integers int32_t lowBits = (int32_t) ReadInt32(); int32_t highBits = (int32_t) ReadInt32(); // Promote long is enabled if(promoteLongs) { // If value is < 2^53 and >-2^53 if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { // Adjust the pointer and read as 64 bit value p -= 8; // Read the 64 bit value int64_t finalValue = (int64_t) ReadInt64(); return Number::New(finalValue); } } // Decode the Long value Local<Value> argv[] = { Int32::New(lowBits), Int32::New(highBits) }; return bson->longConstructor->NewInstance(2, argv); } case BSON_TYPE_DATE: return Date::New((double) ReadInt64()); case BSON_TYPE_ARRAY: return DeserializeArray(promoteLongs); case BSON_TYPE_OBJECT: return DeserializeDocument(promoteLongs); case BSON_TYPE_SYMBOL: { const Local<String>& string = ReadString(); Local<Value> argv[] = { string }; return bson->symbolConstructor->NewInstance(1, argv); } case BSON_TYPE_MIN_KEY: return bson->minKeyConstructor->NewInstance(); case BSON_TYPE_MAX_KEY: return bson->maxKeyConstructor->NewInstance(); default: ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); } return v8::Null(); } static Handle<Value> VException(const char *msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } Persistent<FunctionTemplate> BSON::constructor_template; BSON::BSON() : ObjectWrap() { // Setup pre-allocated comparision objects _bsontypeString = Persistent<String>::New(String::New("_bsontype")); _longLowString = Persistent<String>::New(String::New("low_")); _longHighString = Persistent<String>::New(String::New("high_")); _objectIDidString = Persistent<String>::New(String::New("id")); _binaryPositionString = Persistent<String>::New(String::New("position")); _binarySubTypeString = Persistent<String>::New(String::New("sub_type")); _binaryBufferString = Persistent<String>::New(String::New("buffer")); _doubleValueString = Persistent<String>::New(String::New("value")); _symbolValueString = Persistent<String>::New(String::New("value")); _dbRefRefString = Persistent<String>::New(String::New("$ref")); _dbRefIdRefString = Persistent<String>::New(String::New("$id")); _dbRefDbRefString = Persistent<String>::New(String::New("$db")); _dbRefNamespaceString = Persistent<String>::New(String::New("namespace")); _dbRefDbString = Persistent<String>::New(String::New("db")); _dbRefOidString = Persistent<String>::New(String::New("oid")); _codeCodeString = Persistent<String>::New(String::New("code")); _codeScopeString = Persistent<String>::New(String::New("scope")); _toBSONString = Persistent<String>::New(String::New("toBSON")); longString = Persistent<String>::New(String::New("Long")); objectIDString = Persistent<String>::New(String::New("ObjectID")); binaryString = Persistent<String>::New(String::New("Binary")); codeString = Persistent<String>::New(String::New("Code")); dbrefString = Persistent<String>::New(String::New("DBRef")); symbolString = Persistent<String>::New(String::New("Symbol")); doubleString = Persistent<String>::New(String::New("Double")); timestampString = Persistent<String>::New(String::New("Timestamp")); minKeyString = Persistent<String>::New(String::New("MinKey")); maxKeyString = Persistent<String>::New(String::New("MaxKey")); } void BSON::Initialize(v8::Handle<v8::Object> target) { // Grab the scope of the call from Node HandleScope scope; // Define a new function template Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("BSON")); // Instance methods NODE_SET_PROTOTYPE_METHOD(constructor_template, "calculateObjectSize", CalculateObjectSize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", BSONSerialize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserialize", BSONDeserialize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserializeStream", BSONDeserializeStream); target->ForceSet(String::NewSymbol("BSON"), constructor_template->GetFunction()); } // Create a new instance of BSON and passing it the existing context Handle<Value> BSON::New(const Arguments &args) { HandleScope scope; // Check that we have an array if(args.Length() == 1 && args[0]->IsArray()) { // Cast the array to a local reference Local<Array> array = Local<Array>::Cast(args[0]); if(array->Length() > 0) { // Create a bson object instance and return it BSON *bson = new BSON(); uint32_t foundClassesMask = 0; // Iterate over all entries to save the instantiate funtions for(uint32_t i = 0; i < array->Length(); i++) { // Let's get a reference to the function Local<Function> func = Local<Function>::Cast(array->Get(i)); Local<String> functionName = func->GetName()->ToString(); // Save the functions making them persistant handles (they don't get collected) if(functionName->StrictEquals(bson->longString)) { bson->longConstructor = Persistent<Function>::New(func); foundClassesMask |= 1; } else if(functionName->StrictEquals(bson->objectIDString)) { bson->objectIDConstructor = Persistent<Function>::New(func); foundClassesMask |= 2; } else if(functionName->StrictEquals(bson->binaryString)) { bson->binaryConstructor = Persistent<Function>::New(func); foundClassesMask |= 4; } else if(functionName->StrictEquals(bson->codeString)) { bson->codeConstructor = Persistent<Function>::New(func); foundClassesMask |= 8; } else if(functionName->StrictEquals(bson->dbrefString)) { bson->dbrefConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x10; } else if(functionName->StrictEquals(bson->symbolString)) { bson->symbolConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x20; } else if(functionName->StrictEquals(bson->doubleString)) { bson->doubleConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x40; } else if(functionName->StrictEquals(bson->timestampString)) { bson->timestampConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x80; } else if(functionName->StrictEquals(bson->minKeyString)) { bson->minKeyConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x100; } else if(functionName->StrictEquals(bson->maxKeyString)) { bson->maxKeyConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x200; } } // Check if we have the right number of constructors otherwise throw an error if(foundClassesMask != 0x3ff) { delete bson; return VException("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); } else { bson->Wrap(args.This()); return args.This(); } } else { return VException("No types passed in"); } } else { return VException("Argument passed in must be an array of types"); } } //------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------ Handle<Value> BSON::BSONDeserialize(const Arguments &args) { HandleScope scope; // Fail if the first argument is not a string or a buffer if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) return VException("First Argument must be a Buffer or String."); // Promote longs bool promoteLongs = true; // If we have an options object if(args.Length() == 2 && args[1]->IsObject()) { Local<Object> options = args[1]->ToObject(); if(options->Has(String::New("promoteLongs"))) { promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); } } // Define pointer to data Local<Object> obj = args[0]->ToObject(); // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); // If we passed in a buffer, let's unpack it, otherwise let's unpack the string if(Buffer::HasInstance(obj)) { #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 Buffer *buffer = ObjectWrap::Unwrap<Buffer>(obj); char* data = buffer->data(); size_t length = buffer->length(); #else char* data = Buffer::Data(obj); size_t length = Buffer::Length(obj); #endif // Validate that we have at least 5 bytes if(length < 5) return VException("corrupt bson message < 5 bytes long"); try { BSONDeserializer deserializer(bson, data, length); // deserializer.promoteLongs = promoteLongs; return deserializer.DeserializeDocument(promoteLongs); } catch(char* exception) { Handle<Value> error = VException(exception); free(exception); return error; } } else { // The length of the data for this encoding ssize_t len = DecodeBytes(args[0], BINARY); // Validate that we have at least 5 bytes if(len < 5) return VException("corrupt bson message < 5 bytes long"); // Let's define the buffer size char* data = (char *)malloc(len); DecodeWrite(data, len, args[0], BINARY); try { BSONDeserializer deserializer(bson, data, len); // deserializer.promoteLongs = promoteLongs; Handle<Value> result = deserializer.DeserializeDocument(promoteLongs); free(data); return result; } catch(char* exception) { Handle<Value> error = VException(exception); free(exception); free(data); return error; } } } Local<Object> BSON::GetSerializeObject(const Handle<Value>& argValue) { Local<Object> object = argValue->ToObject(); if(object->Has(_toBSONString)) { const Local<Value>& toBSON = object->Get(_toBSONString); if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); Local<Value> result = Local<Function>::Cast(toBSON)->Call(object, 0, NULL); if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); return result->ToObject(); } else { return object; } } Handle<Value> BSON::BSONSerialize(const Arguments &args) { HandleScope scope; if(args.Length() == 1 && !args[0]->IsObject()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); if(args.Length() > 4) return VException("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); // Check if we have an array as the object if(args[0]->IsArray()) return VException("Only javascript objects supported"); // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); // Calculate the total size of the document in binary form to ensure we only allocate memory once // With serialize function bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); char *serialized_object = NULL; size_t object_size; try { Local<Object> object = bson->GetSerializeObject(args[0]); BSONSerializer<CountStream> counter(bson, false, serializeFunctions); counter.SerializeDocument(object); object_size = counter.GetSerializeSize(); // Allocate the memory needed for the serialization serialized_object = (char *)malloc(object_size); // Check if we have a boolean value bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); BSONSerializer<DataStream> data(bson, checkKeys, serializeFunctions, serialized_object); data.SerializeDocument(object); } catch(char *err_msg) { free(serialized_object); Handle<Value> error = VException(err_msg); free(err_msg); return error; } // If we have 3 arguments if(args.Length() == 3 || args.Length() == 4) { Buffer *buffer = Buffer::New(serialized_object, object_size); free(serialized_object); return scope.Close(buffer->handle_); } else { Local<Value> bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); free(serialized_object); return bin_value; } } Handle<Value> BSON::CalculateObjectSize(const Arguments &args) { HandleScope scope; // Ensure we have a valid object if(args.Length() == 1 && !args[0]->IsObject()) return VException("One argument required - [object]"); if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("Two arguments required - [object, boolean]"); if(args.Length() > 3) return VException("One or two arguments required - [object] or [object, boolean]"); // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); BSONSerializer<CountStream> countSerializer(bson, false, serializeFunctions); countSerializer.SerializeDocument(args[0]); // Return the object size return scope.Close(Uint32::New((uint32_t) countSerializer.GetSerializeSize())); } Handle<Value> BSON::SerializeWithBufferAndIndex(const Arguments &args) { HandleScope scope; //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { // Ensure we have the correct values if(args.Length() > 5) return VException("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return VException("Four parameters required [object, boolean, Buffer, int]"); if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return VException("Four parameters required [object, boolean, Buffer, int, boolean]"); uint32_t index; size_t object_size; try { BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); Local<Object> obj = args[2]->ToObject(); char* data = Buffer::Data(obj); size_t length = Buffer::Length(obj); index = args[3]->Uint32Value(); bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); BSONSerializer<DataStream> dataSerializer(bson, checkKeys, serializeFunctions, data+index); dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); object_size = dataSerializer.GetSerializeSize(); if(object_size + index > length) return VException("Serious error - overflowed buffer!!"); } catch(char *exception) { Handle<Value> error = VException(exception); free(exception); return error; } return scope.Close(Uint32::New((uint32_t) (index + object_size - 1))); } Handle<Value> BSON::BSONDeserializeStream(const Arguments &args) { HandleScope scope; // At least 3 arguments required if(args.Length() < 5) return VException("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); // If the number of argumets equals 3 if(args.Length() >= 5) { if(!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer instance"); if(!args[1]->IsUint32()) return VException("Second argument must be a positive index number"); if(!args[2]->IsUint32()) return VException("Third argument must be a positive number of documents to deserialize"); if(!args[3]->IsArray()) return VException("Fourth argument must be an array the size of documents to deserialize"); if(!args[4]->IsUint32()) return VException("Sixth argument must be a positive index number"); } // If we have 4 arguments if(args.Length() == 6 && !args[5]->IsObject()) return VException("Fifth argument must be an object with options"); // Define pointer to data Local<Object> obj = args[0]->ToObject(); uint32_t numberOfDocuments = args[2]->Uint32Value(); uint32_t index = args[1]->Uint32Value(); uint32_t resultIndex = args[4]->Uint32Value(); bool promoteLongs = true; // Check for the value promoteLongs in the options object if(args.Length() == 6) { Local<Object> options = args[5]->ToObject(); // Check if we have the promoteLong variable if(options->Has(String::New("promoteLongs"))) { promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); } } // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); // Unpack the buffer variable #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 Buffer *buffer = ObjectWrap::Unwrap<Buffer>(obj); char* data = buffer->data(); size_t length = buffer->length(); #else char* data = Buffer::Data(obj); size_t length = Buffer::Length(obj); #endif // Fetch the documents Local<Object> documents = args[3]->ToObject(); BSONDeserializer deserializer(bson, data+index, length-index); for(uint32_t i = 0; i < numberOfDocuments; i++) { try { documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); } catch (char* exception) { Handle<Value> error = VException(exception); free(exception); return error; } } // Return new index of parsing return scope.Close(Uint32::New((uint32_t) (index + deserializer.GetSerializeSize()))); } // Exporting function extern "C" void init(Handle<Object> target) { HandleScope scope; BSON::Initialize(target); } NODE_MODULE(bson, BSON::Initialize); ======= //=========================================================================== #include <stdarg.h> #include <cstdlib> #include <cstring> #include <string.h> #include <stdlib.h> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #endif #include <v8.h> // this and the above block must be around the v8.h header otherwise // v8 is not happy #ifdef __clang__ #pragma clang diagnostic pop #endif #include <node.h> #include <node_version.h> #include <node_buffer.h> #include <cmath> #include <iostream> #include <limits> #include <vector> #ifdef __sun #include <alloca.h> #endif #include "bson.h" using namespace v8; using namespace node; //=========================================================================== void DataStream::WriteObjectId(const Handle<Object>& object, const Handle<String>& key) { uint16_t buffer[12]; object->Get(key)->ToString()->Write(buffer, 0, 12); for(uint32_t i = 0; i < 12; ++i) { *p++ = (char) buffer[i]; } } void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) { va_list args; va_start(args, format); char* string = (char*) malloc(allocationSize); vsprintf(string, format, args); va_end(args); throw string; } void DataStream::CheckKey(const Local<String>& keyName) { size_t keyLength = keyName->Utf8Length(); if(keyLength == 0) return; // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it char* keyStringBuffer = (char*) alloca(keyLength + 1); // Write the key to the allocated buffer keyName->WriteUtf8(keyStringBuffer); // Check for the zero terminator char* terminator = strchr(keyStringBuffer, 0x00); // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere if(terminator != &keyStringBuffer[keyLength]) { ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); } if(keyStringBuffer[0] == '$') { ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); } if(strchr(keyStringBuffer, '.') != NULL) { ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); } } template<typename T> void BSONSerializer<T>::SerializeDocument(const Handle<Value>& value) { void* documentSize = this->BeginWriteSize(); Local<Object> object = bson->GetSerializeObject(value); // Get the object property names #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 Local<Array> propertyNames = object->GetPropertyNames(); #else Local<Array> propertyNames = object->GetOwnPropertyNames(); #endif // Length of the property int propertyLength = propertyNames->Length(); for(int i = 0; i < propertyLength; ++i) { const Local<String>& propertyName = propertyNames->Get(i)->ToString(); if(checkKeys) this->CheckKey(propertyName); const Local<Value>& propertyValue = object->Get(propertyName); if(serializeFunctions || !propertyValue->IsFunction()) { void* typeLocation = this->BeginWriteType(); this->WriteString(propertyName); SerializeValue(typeLocation, propertyValue); } } this->WriteByte(0); this->CommitSize(documentSize); } template<typename T> void BSONSerializer<T>::SerializeArray(const Handle<Value>& value) { void* documentSize = this->BeginWriteSize(); Local<Array> array = Local<Array>::Cast(value->ToObject()); uint32_t arrayLength = array->Length(); for(uint32_t i = 0; i < arrayLength; ++i) { void* typeLocation = this->BeginWriteType(); this->WriteUInt32String(i); SerializeValue(typeLocation, array->Get(i)); } this->WriteByte(0); this->CommitSize(documentSize); } // This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. // The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) // and ensures that there is always consistency between bytes counted and bytes written by design. template<typename T> void BSONSerializer<T>::SerializeValue(void* typeLocation, const Handle<Value>& value) { if(value->IsNumber()) { double doubleValue = value->NumberValue(); int intValue = (int) doubleValue; if(intValue == doubleValue) { this->CommitType(typeLocation, BSON_TYPE_INT); this->WriteInt32(intValue); } else { this->CommitType(typeLocation, BSON_TYPE_NUMBER); this->WriteDouble(doubleValue); } } else if(value->IsString()) { this->CommitType(typeLocation, BSON_TYPE_STRING); this->WriteLengthPrefixedString(value->ToString()); } else if(value->IsBoolean()) { this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); this->WriteBool(value); } else if(value->IsArray()) { this->CommitType(typeLocation, BSON_TYPE_ARRAY); SerializeArray(value); } else if(value->IsDate()) { this->CommitType(typeLocation, BSON_TYPE_DATE); this->WriteInt64(value); } else if(value->IsRegExp()) { this->CommitType(typeLocation, BSON_TYPE_REGEXP); const Handle<RegExp>& regExp = Handle<RegExp>::Cast(value); this->WriteString(regExp->GetSource()); int flags = regExp->GetFlags(); if(flags & RegExp::kGlobal) this->WriteByte('s'); if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); if(flags & RegExp::kMultiline) this->WriteByte('m'); this->WriteByte(0); } else if(value->IsFunction()) { this->CommitType(typeLocation, BSON_TYPE_CODE); this->WriteLengthPrefixedString(value->ToString()); } else if(value->IsObject()) { const Local<Object>& object = value->ToObject(); if(object->Has(bson->_bsontypeString)) { const Local<String>& constructorString = object->GetConstructorName(); if(bson->longString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_LONG); this->WriteInt32(object, bson->_longLowString); this->WriteInt32(object, bson->_longHighString); } else if(bson->timestampString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); this->WriteInt32(object, bson->_longLowString); this->WriteInt32(object, bson->_longHighString); } else if(bson->objectIDString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_OID); this->WriteObjectId(object, bson->_objectIDidString); } else if(bson->binaryString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_BINARY); uint32_t length = object->Get(bson->_binaryPositionString)->Uint32Value(); Local<Object> bufferObj = object->Get(bson->_binaryBufferString)->ToObject(); this->WriteInt32(length); this->WriteByte(object, bson->_binarySubTypeString); // write subtype // If type 0x02 write the array length aswell if(object->Get(bson->_binarySubTypeString)->Int32Value() == 0x02) { this->WriteInt32(length); } // Write the actual data this->WriteData(Buffer::Data(bufferObj), length); } else if(bson->doubleString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_NUMBER); this->WriteDouble(object, bson->_doubleValueString); } else if(bson->symbolString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_SYMBOL); this->WriteLengthPrefixedString(object->Get(bson->_symbolValueString)->ToString()); } else if(bson->codeString->StrictEquals(constructorString)) { const Local<String>& function = object->Get(bson->_codeCodeString)->ToString(); const Local<Object>& scope = object->Get(bson->_codeScopeString)->ToObject(); // For Node < 0.6.X use the GetPropertyNames #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); #else uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); #endif if(propertyNameLength > 0) { this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); void* codeWidthScopeSize = this->BeginWriteSize(); this->WriteLengthPrefixedString(function->ToString()); SerializeDocument(scope); this->CommitSize(codeWidthScopeSize); } else { this->CommitType(typeLocation, BSON_TYPE_CODE); this->WriteLengthPrefixedString(function->ToString()); } } else if(bson->dbrefString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_OBJECT); void* dbRefSize = this->BeginWriteSize(); void* refType = this->BeginWriteType(); this->WriteData("$ref", 5); SerializeValue(refType, object->Get(bson->_dbRefNamespaceString)); void* idType = this->BeginWriteType(); this->WriteData("$id", 4); SerializeValue(idType, object->Get(bson->_dbRefOidString)); const Local<Value>& refDbValue = object->Get(bson->_dbRefDbString); if(!refDbValue->IsUndefined()) { void* dbType = this->BeginWriteType(); this->WriteData("$db", 4); SerializeValue(dbType, refDbValue); } this->WriteByte(0); this->CommitSize(dbRefSize); } else if(bson->minKeyString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); } else if(bson->maxKeyString->StrictEquals(constructorString)) { this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); } } else if(Buffer::HasInstance(value)) { this->CommitType(typeLocation, BSON_TYPE_BINARY); #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 Buffer *buffer = ObjectWrap::Unwrap<Buffer>(value->ToObject()); uint32_t length = object->length(); #else uint32_t length = Buffer::Length(value->ToObject()); #endif this->WriteInt32(length); this->WriteByte(0); this->WriteData(Buffer::Data(value->ToObject()), length); } else { this->CommitType(typeLocation, BSON_TYPE_OBJECT); SerializeDocument(value); } } else if(value->IsNull() || value->IsUndefined()) { this->CommitType(typeLocation, BSON_TYPE_NULL); } } // Data points to start of element list, length is length of entire document including '\0' but excluding initial size BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) : bson(aBson), pStart(data), p(data), pEnd(data + length - 1) { if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); } BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) : bson(parentSerializer.bson), pStart(parentSerializer.p), p(parentSerializer.p), pEnd(parentSerializer.p + length - 1) { parentSerializer.p += length; if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); } Local<String> BSONDeserializer::ReadCString() { char* start = p; while(*p++) { } return String::New(start, (int32_t) (p-start-1) ); } int32_t BSONDeserializer::ReadRegexOptions() { int32_t options = 0; for(;;) { switch(*p++) { case '\0': return options; case 's': options |= RegExp::kGlobal; break; case 'i': options |= RegExp::kIgnoreCase; break; case 'm': options |= RegExp::kMultiline; break; } } } uint32_t BSONDeserializer::ReadIntegerString() { uint32_t value = 0; while(*p) { if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); value = value * 10 + *p++ - '0'; } ++p; return value; } Local<String> BSONDeserializer::ReadString() { uint32_t length = ReadUInt32(); char* start = p; p += length; return String::New(start, length-1); } Local<String> BSONDeserializer::ReadObjectId() { uint16_t objectId[12]; for(size_t i = 0; i < 12; ++i) { objectId[i] = *reinterpret_cast<unsigned char*>(p++); } return String::New(objectId, 12); } Handle<Value> BSONDeserializer::DeserializeDocument(bool promoteLongs) { uint32_t length = ReadUInt32(); if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); BSONDeserializer documentDeserializer(*this, length-4); return documentDeserializer.DeserializeDocumentInternal(promoteLongs); } Handle<Value> BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) { Local<Object> returnObject = Object::New(); while(HasMoreData()) { BsonType type = (BsonType) ReadByte(); const Local<String>& name = ReadCString(); const Handle<Value>& value = DeserializeValue(type, promoteLongs); returnObject->ForceSet(name, value); } if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); // From JavaScript: // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); if(returnObject->Has(bson->_dbRefIdRefString)) { Local<Value> argv[] = { returnObject->Get(bson->_dbRefRefString), returnObject->Get(bson->_dbRefIdRefString), returnObject->Get(bson->_dbRefDbRefString) }; return bson->dbrefConstructor->NewInstance(3, argv); } else { return returnObject; } } Handle<Value> BSONDeserializer::DeserializeArray(bool promoteLongs) { uint32_t length = ReadUInt32(); if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); BSONDeserializer documentDeserializer(*this, length-4); return documentDeserializer.DeserializeArrayInternal(promoteLongs); } Handle<Value> BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) { Local<Array> returnArray = Array::New(); while(HasMoreData()) { BsonType type = (BsonType) ReadByte(); uint32_t index = ReadIntegerString(); const Handle<Value>& value = DeserializeValue(type, promoteLongs); returnArray->Set(index, value); } if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); return returnArray; } Handle<Value> BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) { switch(type) { case BSON_TYPE_STRING: return ReadString(); case BSON_TYPE_INT: return Integer::New(ReadInt32()); case BSON_TYPE_NUMBER: return Number::New(ReadDouble()); case BSON_TYPE_NULL: return Null(); case BSON_TYPE_UNDEFINED: return Undefined(); case BSON_TYPE_TIMESTAMP: { int32_t lowBits = ReadInt32(); int32_t highBits = ReadInt32(); Local<Value> argv[] = { Int32::New(lowBits), Int32::New(highBits) }; return bson->timestampConstructor->NewInstance(2, argv); } case BSON_TYPE_BOOLEAN: return (ReadByte() != 0) ? True() : False(); case BSON_TYPE_REGEXP: { const Local<String>& regex = ReadCString(); int32_t options = ReadRegexOptions(); return RegExp::New(regex, (RegExp::Flags) options); } case BSON_TYPE_CODE: { const Local<Value>& code = ReadString(); const Local<Value>& scope = Object::New(); Local<Value> argv[] = { code, scope }; return bson->codeConstructor->NewInstance(2, argv); } case BSON_TYPE_CODE_W_SCOPE: { ReadUInt32(); const Local<Value>& code = ReadString(); const Handle<Value>& scope = DeserializeDocument(promoteLongs); Local<Value> argv[] = { code, scope->ToObject() }; return bson->codeConstructor->NewInstance(2, argv); } case BSON_TYPE_OID: { Local<Value> argv[] = { ReadObjectId() }; return bson->objectIDConstructor->NewInstance(1, argv); } case BSON_TYPE_BINARY: { uint32_t length = ReadUInt32(); uint32_t subType = ReadByte(); if(subType == 0x02) { length = ReadInt32(); } Buffer* buffer = Buffer::New(p, length); p += length; Handle<Value> argv[] = { buffer->handle_, Uint32::New(subType) }; return bson->binaryConstructor->NewInstance(2, argv); } case BSON_TYPE_LONG: { // Read 32 bit integers int32_t lowBits = (int32_t) ReadInt32(); int32_t highBits = (int32_t) ReadInt32(); // Promote long is enabled if(promoteLongs) { // If value is < 2^53 and >-2^53 if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { // Adjust the pointer and read as 64 bit value p -= 8; // Read the 64 bit value int64_t finalValue = (int64_t) ReadInt64(); return Number::New(finalValue); } } // Decode the Long value Local<Value> argv[] = { Int32::New(lowBits), Int32::New(highBits) }; return bson->longConstructor->NewInstance(2, argv); } case BSON_TYPE_DATE: return Date::New((double) ReadInt64()); case BSON_TYPE_ARRAY: return DeserializeArray(promoteLongs); case BSON_TYPE_OBJECT: return DeserializeDocument(promoteLongs); case BSON_TYPE_SYMBOL: { const Local<String>& string = ReadString(); Local<Value> argv[] = { string }; return bson->symbolConstructor->NewInstance(1, argv); } case BSON_TYPE_MIN_KEY: return bson->minKeyConstructor->NewInstance(); case BSON_TYPE_MAX_KEY: return bson->maxKeyConstructor->NewInstance(); default: ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); } return v8::Null(); } static Handle<Value> VException(const char *msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } Persistent<FunctionTemplate> BSON::constructor_template; BSON::BSON() : ObjectWrap() { // Setup pre-allocated comparision objects _bsontypeString = Persistent<String>::New(String::New("_bsontype")); _longLowString = Persistent<String>::New(String::New("low_")); _longHighString = Persistent<String>::New(String::New("high_")); _objectIDidString = Persistent<String>::New(String::New("id")); _binaryPositionString = Persistent<String>::New(String::New("position")); _binarySubTypeString = Persistent<String>::New(String::New("sub_type")); _binaryBufferString = Persistent<String>::New(String::New("buffer")); _doubleValueString = Persistent<String>::New(String::New("value")); _symbolValueString = Persistent<String>::New(String::New("value")); _dbRefRefString = Persistent<String>::New(String::New("$ref")); _dbRefIdRefString = Persistent<String>::New(String::New("$id")); _dbRefDbRefString = Persistent<String>::New(String::New("$db")); _dbRefNamespaceString = Persistent<String>::New(String::New("namespace")); _dbRefDbString = Persistent<String>::New(String::New("db")); _dbRefOidString = Persistent<String>::New(String::New("oid")); _codeCodeString = Persistent<String>::New(String::New("code")); _codeScopeString = Persistent<String>::New(String::New("scope")); _toBSONString = Persistent<String>::New(String::New("toBSON")); longString = Persistent<String>::New(String::New("Long")); objectIDString = Persistent<String>::New(String::New("ObjectID")); binaryString = Persistent<String>::New(String::New("Binary")); codeString = Persistent<String>::New(String::New("Code")); dbrefString = Persistent<String>::New(String::New("DBRef")); symbolString = Persistent<String>::New(String::New("Symbol")); doubleString = Persistent<String>::New(String::New("Double")); timestampString = Persistent<String>::New(String::New("Timestamp")); minKeyString = Persistent<String>::New(String::New("MinKey")); maxKeyString = Persistent<String>::New(String::New("MaxKey")); } void BSON::Initialize(v8::Handle<v8::Object> target) { // Grab the scope of the call from Node HandleScope scope; // Define a new function template Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("BSON")); // Instance methods NODE_SET_PROTOTYPE_METHOD(constructor_template, "calculateObjectSize", CalculateObjectSize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", BSONSerialize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserialize", BSONDeserialize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserializeStream", BSONDeserializeStream); target->ForceSet(String::NewSymbol("BSON"), constructor_template->GetFunction()); } // Create a new instance of BSON and passing it the existing context Handle<Value> BSON::New(const Arguments &args) { HandleScope scope; // Check that we have an array if(args.Length() == 1 && args[0]->IsArray()) { // Cast the array to a local reference Local<Array> array = Local<Array>::Cast(args[0]); if(array->Length() > 0) { // Create a bson object instance and return it BSON *bson = new BSON(); uint32_t foundClassesMask = 0; // Iterate over all entries to save the instantiate funtions for(uint32_t i = 0; i < array->Length(); i++) { // Let's get a reference to the function Local<Function> func = Local<Function>::Cast(array->Get(i)); Local<String> functionName = func->GetName()->ToString(); // Save the functions making them persistant handles (they don't get collected) if(functionName->StrictEquals(bson->longString)) { bson->longConstructor = Persistent<Function>::New(func); foundClassesMask |= 1; } else if(functionName->StrictEquals(bson->objectIDString)) { bson->objectIDConstructor = Persistent<Function>::New(func); foundClassesMask |= 2; } else if(functionName->StrictEquals(bson->binaryString)) { bson->binaryConstructor = Persistent<Function>::New(func); foundClassesMask |= 4; } else if(functionName->StrictEquals(bson->codeString)) { bson->codeConstructor = Persistent<Function>::New(func); foundClassesMask |= 8; } else if(functionName->StrictEquals(bson->dbrefString)) { bson->dbrefConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x10; } else if(functionName->StrictEquals(bson->symbolString)) { bson->symbolConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x20; } else if(functionName->StrictEquals(bson->doubleString)) { bson->doubleConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x40; } else if(functionName->StrictEquals(bson->timestampString)) { bson->timestampConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x80; } else if(functionName->StrictEquals(bson->minKeyString)) { bson->minKeyConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x100; } else if(functionName->StrictEquals(bson->maxKeyString)) { bson->maxKeyConstructor = Persistent<Function>::New(func); foundClassesMask |= 0x200; } } // Check if we have the right number of constructors otherwise throw an error if(foundClassesMask != 0x3ff) { delete bson; return VException("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); } else { bson->Wrap(args.This()); return args.This(); } } else { return VException("No types passed in"); } } else { return VException("Argument passed in must be an array of types"); } } //------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------ Handle<Value> BSON::BSONDeserialize(const Arguments &args) { HandleScope scope; // Fail if the first argument is not a string or a buffer if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) return VException("First Argument must be a Buffer or String."); // Promote longs bool promoteLongs = true; // If we have an options object if(args.Length() == 2 && args[1]->IsObject()) { Local<Object> options = args[1]->ToObject(); if(options->Has(String::New("promoteLongs"))) { promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); } } // Define pointer to data Local<Object> obj = args[0]->ToObject(); // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); // If we passed in a buffer, let's unpack it, otherwise let's unpack the string if(Buffer::HasInstance(obj)) { #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 Buffer *buffer = ObjectWrap::Unwrap<Buffer>(obj); char* data = buffer->data(); size_t length = buffer->length(); #else char* data = Buffer::Data(obj); size_t length = Buffer::Length(obj); #endif // Validate that we have at least 5 bytes if(length < 5) return VException("corrupt bson message < 5 bytes long"); try { BSONDeserializer deserializer(bson, data, length); // deserializer.promoteLongs = promoteLongs; return deserializer.DeserializeDocument(promoteLongs); } catch(char* exception) { Handle<Value> error = VException(exception); free(exception); return error; } } else { // The length of the data for this encoding ssize_t len = DecodeBytes(args[0], BINARY); // Validate that we have at least 5 bytes if(len < 5) return VException("corrupt bson message < 5 bytes long"); // Let's define the buffer size char* data = (char *)malloc(len); DecodeWrite(data, len, args[0], BINARY); try { BSONDeserializer deserializer(bson, data, len); // deserializer.promoteLongs = promoteLongs; Handle<Value> result = deserializer.DeserializeDocument(promoteLongs); free(data); return result; } catch(char* exception) { Handle<Value> error = VException(exception); free(exception); free(data); return error; } } } Local<Object> BSON::GetSerializeObject(const Handle<Value>& argValue) { Local<Object> object = argValue->ToObject(); if(object->Has(_toBSONString)) { const Local<Value>& toBSON = object->Get(_toBSONString); if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); Local<Value> result = Local<Function>::Cast(toBSON)->Call(object, 0, NULL); if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); return result->ToObject(); } else { return object; } } Handle<Value> BSON::BSONSerialize(const Arguments &args) { HandleScope scope; if(args.Length() == 1 && !args[0]->IsObject()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); if(args.Length() > 4) return VException("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); // Check if we have an array as the object if(args[0]->IsArray()) return VException("Only javascript objects supported"); // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); // Calculate the total size of the document in binary form to ensure we only allocate memory once // With serialize function bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); char *serialized_object = NULL; size_t object_size; try { Local<Object> object = bson->GetSerializeObject(args[0]); BSONSerializer<CountStream> counter(bson, false, serializeFunctions); counter.SerializeDocument(object); object_size = counter.GetSerializeSize(); // Allocate the memory needed for the serialization serialized_object = (char *)malloc(object_size); // Check if we have a boolean value bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); BSONSerializer<DataStream> data(bson, checkKeys, serializeFunctions, serialized_object); data.SerializeDocument(object); } catch(char *err_msg) { free(serialized_object); Handle<Value> error = VException(err_msg); free(err_msg); return error; } // If we have 3 arguments if(args.Length() == 3 || args.Length() == 4) { Buffer *buffer = Buffer::New(serialized_object, object_size); free(serialized_object); return scope.Close(buffer->handle_); } else { Local<Value> bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); free(serialized_object); return bin_value; } } Handle<Value> BSON::CalculateObjectSize(const Arguments &args) { HandleScope scope; // Ensure we have a valid object if(args.Length() == 1 && !args[0]->IsObject()) return VException("One argument required - [object]"); if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("Two arguments required - [object, boolean]"); if(args.Length() > 3) return VException("One or two arguments required - [object] or [object, boolean]"); // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); BSONSerializer<CountStream> countSerializer(bson, false, serializeFunctions); countSerializer.SerializeDocument(args[0]); // Return the object size return scope.Close(Uint32::New((uint32_t) countSerializer.GetSerializeSize())); } Handle<Value> BSON::SerializeWithBufferAndIndex(const Arguments &args) { HandleScope scope; //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { // Ensure we have the correct values if(args.Length() > 5) return VException("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return VException("Four parameters required [object, boolean, Buffer, int]"); if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return VException("Four parameters required [object, boolean, Buffer, int, boolean]"); uint32_t index; size_t object_size; try { BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); Local<Object> obj = args[2]->ToObject(); char* data = Buffer::Data(obj); size_t length = Buffer::Length(obj); index = args[3]->Uint32Value(); bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); BSONSerializer<DataStream> dataSerializer(bson, checkKeys, serializeFunctions, data+index); dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); object_size = dataSerializer.GetSerializeSize(); if(object_size + index > length) return VException("Serious error - overflowed buffer!!"); } catch(char *exception) { Handle<Value> error = VException(exception); free(exception); return error; } return scope.Close(Uint32::New((uint32_t) (index + object_size - 1))); } Handle<Value> BSON::BSONDeserializeStream(const Arguments &args) { HandleScope scope; // At least 3 arguments required if(args.Length() < 5) return VException("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); // If the number of argumets equals 3 if(args.Length() >= 5) { if(!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer instance"); if(!args[1]->IsUint32()) return VException("Second argument must be a positive index number"); if(!args[2]->IsUint32()) return VException("Third argument must be a positive number of documents to deserialize"); if(!args[3]->IsArray()) return VException("Fourth argument must be an array the size of documents to deserialize"); if(!args[4]->IsUint32()) return VException("Sixth argument must be a positive index number"); } // If we have 4 arguments if(args.Length() == 6 && !args[5]->IsObject()) return VException("Fifth argument must be an object with options"); // Define pointer to data Local<Object> obj = args[0]->ToObject(); uint32_t numberOfDocuments = args[2]->Uint32Value(); uint32_t index = args[1]->Uint32Value(); uint32_t resultIndex = args[4]->Uint32Value(); bool promoteLongs = true; // Check for the value promoteLongs in the options object if(args.Length() == 6) { Local<Object> options = args[5]->ToObject(); // Check if we have the promoteLong variable if(options->Has(String::New("promoteLongs"))) { promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); } } // Unpack the BSON parser instance BSON *bson = ObjectWrap::Unwrap<BSON>(args.This()); // Unpack the buffer variable #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 Buffer *buffer = ObjectWrap::Unwrap<Buffer>(obj); char* data = buffer->data(); size_t length = buffer->length(); #else char* data = Buffer::Data(obj); size_t length = Buffer::Length(obj); #endif // Fetch the documents Local<Object> documents = args[3]->ToObject(); BSONDeserializer deserializer(bson, data+index, length-index); for(uint32_t i = 0; i < numberOfDocuments; i++) { try { documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); } catch (char* exception) { Handle<Value> error = VException(exception); free(exception); return error; } } // Return new index of parsing return scope.Close(Uint32::New((uint32_t) (index + deserializer.GetSerializeSize()))); } // Exporting function extern "C" void init(Handle<Object> target) { HandleScope scope; BSON::Initialize(target); } NODE_MODULE(bson, BSON::Initialize); >>>>>>> restructure
{ "content_hash": "737369ffd9666aecb167eefdd418f102", "timestamp": "", "source": "github", "line_count": 2093, "max_line_length": 281, "avg_line_length": 33.221213569039655, "alnum_prop": 0.6773428061899557, "repo_name": "ryanjhill/cogs121-project", "id": "420da9ec7a932d07726f2895f733a0632e58ebc1", "size": "69532", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/bson.cc", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "347" }, { "name": "HTML", "bytes": "7018" }, { "name": "JavaScript", "bytes": "17349" } ], "symlink_target": "" }
(function () { "use strict"; var Statement, Database, ItemDataSource, GroupDataSource; // Alternative typeof implementation yielding more meaningful results, // see http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/ function type(obj) { var typeString; typeString = Object.prototype.toString.call(obj); return typeString.substring(8, typeString.length - 1).toLowerCase(); } function throwSQLiteError(message, comException) { var error = new Error(message); error.resultCode = comException.number & 0xffff; throw error; } Statement = WinJS.Class.define(function (db, sql, args) { try { this.statement = db.connection.prepare(sql); } catch (comException) { throwSQLiteError('Error preparing an SQLite statement.', comException); } if (args) { this.bind(args); } }, { bind: function (args) { var index, resultCode; args.forEach(function (arg, i) { index = i + 1; switch (type(arg)) { case 'number': if (arg % 1 === 0) { resultCode = this.statement.bindInt64(index, arg); } else { resultCode = this.statement.bindDouble(index, arg); } break; case 'string': resultCode = this.statement.bindText(index, arg); break; case 'null': resultCode = this.statement.bindNull(index); break; default: throw new Error("Unsupported argument type: " + type(arg)); } if (resultCode !== SQLite3.ResultCode.ok) { throw new Error("Error " + resultCode + " when binding argument to SQL query."); } }, this); }, run: function () { this.statement.step(); }, one: function () { this.statement.step(); return this._getRow(); }, all: function () { var result = []; this.each(function (row) { result.push(row); }); return result; }, each: function (callback) { while (this.statement.step() === SQLite3.ResultCode.row) { callback(this._getRow()); } }, map: function (callback) { var result = []; this.each(function (row) { result.push(callback(row)); }); return result; }, close: function () { this.statement.close(); }, _getRow: function () { var i, len, name, row = {}; for (i = 0, len = this.statement.columnCount() ; i < len; i += 1) { name = this.statement.columnName(i); row[name] = this._getColumn(i); } return row; }, _getColumn: function (index) { switch (this.statement.columnType(index)) { case SQLite3.Datatype.integer: return this.statement.columnInt64(index); case SQLite3.Datatype.float: return this.statement.columnDouble(index); case SQLite3.Datatype.text: return this.statement.columnText(index); case SQLite3.Datatype["null"]: return null; default: throw new Error('Unsupported column type in column ' + index); } } }); Database = WinJS.Class.define(function (dbPath) { try { this.connection = SQLite3.Database(dbPath); } catch (comException) { throwSQLiteError('Error creating an SQLite database connection.', comException); } }, { run: function (sql, args) { var statement = this.prepare(sql, args); statement.run(); statement.close(); }, one: function (sql, args) { var row, statement = this.prepare(sql, args); row = statement.one(); statement.close(); return row; }, all: function (sql, args) { var rows, statement = this.prepare(sql, args); rows = statement.all(); statement.close(); return rows; }, each: function (sql, args, callback) { if (!callback && type(args) === 'function') { callback = args; args = null; } var statement = this.prepare(sql, args); statement.each(callback); statement.close(); }, map: function (sql, args, callback) { if (!callback && type(args) === 'function') { callback = args; args = null; } var rows, statement = this.prepare(sql, args); rows = statement.map(callback); statement.close(); return rows; }, prepare: function (sql, args) { return new Statement(this, sql, args); }, itemDataSource: function (sql, args, keyColumnName, groupKeyColumnName) { if (type(args) === 'string') { groupKeyColumnName = keyColumnName; keyColumnName = args; args = undefined; } return new ItemDataSource(this, sql, args, keyColumnName, groupKeyColumnName); }, groupDataSource: function (sql, args, keyColumnName, sizeColumnName) { if (type(args) === 'string') { sizeColumnName = keyColumnName; keyColumnName = args; args = undefined; } return new GroupDataSource(this, sql, args, keyColumnName, sizeColumnName); }, close: function () { return this.connection.close(); }, close_v2: function () { return this.connection.close_v2(); }, lastInsertRowid: function () { return this.connection.lastInsertRowid(); }, totalChanges: function () { return this.connection.totalChanges(); } }); ItemDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (db, sql, args, keyColumnName, groupKeyColumnName) { var dataAdapter = { getCount: function () { var row = db.one('SELECT COUNT(*) AS cnt FROM (' + sql + ')', args); return WinJS.Promise.wrap(row.cnt); }, itemsFromIndex: function (requestIndex, countBefore, countAfter) { var items, limit = countBefore + 1 + countAfter, offset = requestIndex - countBefore; items = db.map( 'SELECT * FROM (' + sql + ') LIMIT ' + limit + ' OFFSET ' + offset, function (row) { var item = { key: row[keyColumnName].toString(), data: row }; if (groupKeyColumnName) { item.groupKey = row[groupKeyColumnName].toString(); } return item; }); return WinJS.Promise.wrap({ items: items, offset: countBefore, atEnd: items.length < limit }); } }; this._baseDataSourceConstructor(dataAdapter); } ); GroupDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (db, sql, args, keyColumnName, sizeColumnName) { var groups, dataAdapter, keyIndexMap = {}, groupIndex = 0, firstItemIndex = 0; groups = db.map(sql, args, function (row) { var item = { key: row[keyColumnName].toString(), groupSize: row[sizeColumnName], firstItemIndexHint: firstItemIndex, data: row }; keyIndexMap[item.key] = groupIndex; groupIndex += 1; firstItemIndex += item.groupSize; return item; }); dataAdapter = { getCount: function () { return WinJS.Promise.wrap(groups.length); }, itemsFromIndex: function (requestIndex, countBefore, countAfter) { return WinJS.Promise.wrap({ items: groups.slice(), offset: requestIndex, absoluteIndex: requestIndex, atStart: true, atEnd: true }); }, itemsFromKey: function (key, countBefore, countAfter) { return this.itemsFromIndex(keyIndexMap[key], countBefore, countAfter); } }; this._baseDataSourceConstructor(dataAdapter); } ); WinJS.Namespace.define('SQLite3JS', { Database: Database }); }());
{ "content_hash": "87e4b296f62913d1a75cc90910976936", "timestamp": "", "source": "github", "line_count": 287, "max_line_length": 96, "avg_line_length": 28.069686411149824, "alnum_prop": 0.5615690168818273, "repo_name": "prostudy/calculadatos", "id": "d5042c460962b1233486fdb740457d778f950a71", "size": "8056", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/cordova-sqlite-storage/src/windows/SQLite3-WinRT/SQLite3JS/js/SQLite3.js", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "16341" }, { "name": "C", "bytes": "11099752" }, { "name": "C#", "bytes": "4559338" }, { "name": "C++", "bytes": "764152" }, { "name": "CSS", "bytes": "1613947" }, { "name": "CoffeeScript", "bytes": "18954" }, { "name": "HTML", "bytes": "77091" }, { "name": "Java", "bytes": "416898" }, { "name": "JavaScript", "bytes": "8658124" }, { "name": "Objective-C", "bytes": "338421" }, { "name": "PowerShell", "bytes": "1435" }, { "name": "Shell", "bytes": "3279" } ], "symlink_target": "" }
const errors = require("../errors"); const utils = require("../utils"); class AgentService { constructor(consul) { this.consul = consul; } /** * Returns the services local agent is managing */ async list(opts) { opts = utils.normalizeKeys(opts); opts = utils.defaults(opts, this.consul._defaults); const req = { name: "agent.service.list", path: "/agent/services", }; utils.options(req, opts); return await this.consul._get(req, utils.body); } /** * Registers a new local service */ async register(opts) { if (typeof opts === "string") { opts = { name: opts }; } opts = utils.normalizeKeys(opts); opts = utils.defaults(opts, this.consul._defaults); const req = { name: "agent.service.register", path: "/agent/service/register", type: "json", body: {}, }; if (!opts.name) { throw this.consul._err(errors.Validation("name required"), req); } try { req.body = utils.createService(opts); } catch (err) { throw this.consul._err(errors.Validation(err.message), req); } utils.options(req, opts); return await this.consul._put(req, utils.empty); } /** * Deregister a local service */ async deregister(opts) { if (typeof opts === "string") { opts = { id: opts }; } opts = utils.normalizeKeys(opts); opts = utils.defaults(opts, this.consul._defaults); const req = { name: "agent.service.deregister", path: "/agent/service/deregister/{id}", params: { id: opts.id }, }; if (!opts.id) { throw this.consul._err(errors.Validation("id required"), req); } utils.options(req, opts); return await this.consul._put(req, utils.empty); } /** * Manages node maintenance mode */ async maintenance(opts) { opts = utils.normalizeKeys(opts); opts = utils.defaults(opts, this.consul._defaults); const req = { name: "agent.service.maintenance", path: "/agent/service/maintenance/{id}", params: { id: opts.id }, query: { enable: opts.enable }, }; if (!opts.id) { throw this.consul._err(errors.Validation("id required"), req); } if (typeof opts.enable !== "boolean") { throw this.consul._err(errors.Validation("enable required"), req); } if (opts.reason) req.query.reason = opts.reason; utils.options(req, opts); return await this.consul._put(req, utils.empty); } } exports.AgentService = AgentService;
{ "content_hash": "006b57e42cc4b80f06d6b202a4af05a3", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 72, "avg_line_length": 22.460176991150444, "alnum_prop": 0.5929866036249015, "repo_name": "silas/node-consul", "id": "31b0a4c6391a4dac8b1c23d195886967c8d9869e", "size": "2538", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "lib/agent/service.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "188252" } ], "symlink_target": "" }
"""The zip path specification resolver helper implementation.""" # This is necessary to prevent a circular import. import dfvfs.file_io.zip_file_io import dfvfs.vfs.zip_file_system from dfvfs.lib import definitions from dfvfs.resolver import resolver from dfvfs.resolver import resolver_helper class ZipResolverHelper(resolver_helper.ResolverHelper): """Class that implements the zip resolver helper.""" TYPE_INDICATOR = definitions.TYPE_INDICATOR_ZIP def NewFileObject(self, resolver_context): """Creates a new file-like object. Args: resolver_context: the resolver context (instance of resolver.Context). Returns: The file-like object (instance of file_io.FileIO). """ return dfvfs.file_io.zip_file_io.ZipFile(resolver_context) def NewFileSystem(self, resolver_context): """Creates a new file system object. Args: resolver_context: the resolver context (instance of resolver.Context). Returns: The file system object (instance of vfs.FileSystem). """ return dfvfs.vfs.zip_file_system.ZipFileSystem(resolver_context) # Register the resolver helpers with the resolver. resolver.Resolver.RegisterHelper(ZipResolverHelper())
{ "content_hash": "92fdac20d69098bc09b7b7ea66c80f24", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 76, "avg_line_length": 29.463414634146343, "alnum_prop": 0.7458609271523179, "repo_name": "manashmndl/dfvfs", "id": "ea7a0bfa7e13b985308e375a9e533921bb943084", "size": "1232", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dfvfs/resolver/zip_resolver_helper.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1151" }, { "name": "Protocol Buffer", "bytes": "1883" }, { "name": "Python", "bytes": "896241" }, { "name": "Shell", "bytes": "33508" } ], "symlink_target": "" }
package me.vilsol.nmswrapper.wraps.unparsed; import me.vilsol.nmswrapper.reflections.ReflectiveClass; // TODO Implement @ReflectiveClass(name = "IBlockFragilePlantElement") public interface NMSIBlockFragilePlantElement { }
{ "content_hash": "946ae785621d9d79498b46a1a7d9da87", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 28.125, "alnum_prop": 0.8355555555555556, "repo_name": "Vilsol/NMSWrapper", "id": "0313a371ddc4ec01351cf04648929537b2d38f22", "size": "225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSIBlockFragilePlantElement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2502393" } ], "symlink_target": "" }
from PyQt5.QtGui import QTextCursor from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QCompleter, QPlainTextEdit, QApplication from .util import ButtonsTextEdit class CompletionTextEdit(ButtonsTextEdit): def __init__(self): ButtonsTextEdit.__init__(self) self.completer = None self.moveCursor(QTextCursor.End) self.disable_suggestions() def set_completer(self, completer): self.completer = completer self.initialize_completer() def initialize_completer(self): self.completer.setWidget(self) self.completer.setCompletionMode(QCompleter.PopupCompletion) self.completer.activated.connect(self.insert_completion) self.enable_suggestions() def insert_completion(self, completion): if self.completer.widget() != self: return text_cursor = self.textCursor() extra = len(completion) - len(self.completer.completionPrefix()) text_cursor.movePosition(QTextCursor.Left) text_cursor.movePosition(QTextCursor.EndOfWord) if extra == 0: text_cursor.insertText(" ") else: text_cursor.insertText(completion[-extra:] + " ") self.setTextCursor(text_cursor) def text_under_cursor(self): tc = self.textCursor() tc.select(QTextCursor.WordUnderCursor) return tc.selectedText() def enable_suggestions(self): self.suggestions_enabled = True def disable_suggestions(self): self.suggestions_enabled = False def keyPressEvent(self, e): if self.isReadOnly(): return if self.is_special_key(e): e.ignore() return QPlainTextEdit.keyPressEvent(self, e) ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier) if self.completer is None or (ctrlOrShift and not e.text()): return if not self.suggestions_enabled: return eow = "~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=" hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift completionPrefix = self.text_under_cursor() if hasModifier or not e.text() or len(completionPrefix) < 1 or eow.find(e.text()[-1]) >= 0: self.completer.popup().hide() return if completionPrefix != self.completer.completionPrefix(): self.completer.setCompletionPrefix(completionPrefix) self.completer.popup().setCurrentIndex(self.completer.completionModel().index(0, 0)) cr = self.cursorRect() cr.setWidth(self.completer.popup().sizeHintForColumn(0) + self.completer.popup().verticalScrollBar().sizeHint().width()) self.completer.complete(cr) def is_special_key(self, e): if self.completer and self.completer.popup().isVisible(): if e.key() in (Qt.Key_Enter, Qt.Key_Return): return True if e.key() == Qt.Key_Tab: return True return False if __name__ == "__main__": app = QApplication([]) completer = QCompleter(["alabama", "arkansas", "avocado", "breakfast", "sausage"]) te = CompletionTextEdit() te.set_completer(completer) te.show() app.exec_()
{ "content_hash": "2d4721d281ecd0a019da39c1fad48cf0", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 128, "avg_line_length": 33.4639175257732, "alnum_prop": 0.6272335181762169, "repo_name": "wakiyamap/electrum-mona", "id": "b34d976c6f1eb0a718f061fba0610b68b37c387c", "size": "4417", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "electrum_mona/gui/qt/completion_text_edit.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "13043" }, { "name": "GLSL", "bytes": "289" }, { "name": "Java", "bytes": "2929" }, { "name": "Makefile", "bytes": "2162" }, { "name": "NSIS", "bytes": "7779" }, { "name": "Python", "bytes": "4381566" }, { "name": "Ruby", "bytes": "16375" }, { "name": "Shell", "bytes": "100799" }, { "name": "kvlang", "bytes": "67448" } ], "symlink_target": "" }
import angular from 'angular'; import './ngbBrowser.scss'; // Import internal modules import controller from './ngbBrowser.controller'; import component from './ngbBrowser.component'; import service from './ngbBrowser.service'; export default angular.module('ngbBrowser',[]) .controller(controller.UID, controller) .component('ngbBrowser', component) .service('ngbBrowserService', service) .name;
{ "content_hash": "2aaf45b1299db90ce774785593420ace", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 49, "avg_line_length": 34.5, "alnum_prop": 0.7463768115942029, "repo_name": "epam/NGB", "id": "dd6d486d7000e1446438e6e932a7a85efcee7c9a", "size": "414", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "client/client/app/components/ngbBrowser/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2130" }, { "name": "Dockerfile", "bytes": "2839" }, { "name": "EJS", "bytes": "344" }, { "name": "HTML", "bytes": "455953" }, { "name": "Java", "bytes": "6041257" }, { "name": "JavaScript", "bytes": "3315081" }, { "name": "PLSQL", "bytes": "1182" }, { "name": "SCSS", "bytes": "167986" }, { "name": "Shell", "bytes": "11389" }, { "name": "Smarty", "bytes": "1410" } ], "symlink_target": "" }
import validateInput from '../utils/validate_input.js'; function onApplyDefinition(Class, parsedDefinition, className) { _.each(parsedDefinition.inputs, function(inputDefinition, inputName) { const input = validateInput(inputDefinition, [ { 'class': className }, { 'property': 'fields' }, { 'field': inputName }, { 'property': 'input' }, { 'property': 'type' } ]); Class.schema.inputs[inputName] = input; }); } export default onApplyDefinition;
{ "content_hash": "614280de09842a659332e5a1bf96a1a4", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 72, "avg_line_length": 24.5, "alnum_prop": 0.5974025974025974, "repo_name": "Zetoff/meteor-astroforms", "id": "52704f8eed2d16d9b18fdbfdb6115b9fc5d8f901", "size": "539", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/module/hooks/apply_definition.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "12570" } ], "symlink_target": "" }
module.exports = function(grunt){ return { /** * generate-chrome-extension Task * ============================== */ /** * ZIP-Archiv für die Chrome Extension erstellen */ "generate-chrome-extension-compress-zip": { options: { archive: grunt.pkg.paths.distextensions + grunt.pkg.filenames.chromezip, mode: 'zip' }, files: [{ flatten: true, expand: true, src: [grunt.pkg.paths.chrometemp + '*'], dest: '' }] }, /** * generate-chrome-extension Task * ============================== */ /** * ZIP-Archiv für die Firefox Extension erstellen */ "generate-firefox-extension-compress-zip": { options: { archive: grunt.pkg.paths.distextensions + grunt.pkg.filenames.firefoxzip, mode: 'zip' }, files: [{ expand: true, cwd: grunt.pkg.paths.firefoxtemp, src: ['**'] }] } }; };
{ "content_hash": "d8e690fd8c081a68e043128cc14eb95f", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 92, "avg_line_length": 27.22222222222222, "alnum_prop": 0.39510204081632655, "repo_name": "thextor/readmore-userscript", "id": "a686e585a977bc0b3148893b4d808e7475d443b0", "size": "1227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/tasks/options/compress.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10976" }, { "name": "HTML", "bytes": "41230" }, { "name": "JavaScript", "bytes": "119434" } ], "symlink_target": "" }
This is a test commit!
{ "content_hash": "bd2544310f39e7877da9f0ba9841bca3", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 22, "avg_line_length": 23, "alnum_prop": 0.7391304347826086, "repo_name": "20988902/lixl", "id": "ed8531b51356fb323dc451fcc3a23c0a689aa8fb", "size": "30", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * @license Highcharts Gantt JS v9.0.1 (2021-02-16) * * Pathfinder * * (c) 2016-2021 Øystein Moseng * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/pathfinder', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'Extensions/ArrowSymbols.js', [_modules['Core/Renderer/SVG/SVGRenderer.js']], function (SVGRenderer) { /* * * * (c) 2017 Highsoft AS * Authors: Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ /** * Creates an arrow symbol. Like a triangle, except not filled. * ``` * o * o * o * o * o * o * o * ``` * * @private * @function * * @param {number} x * x position of the arrow * * @param {number} y * y position of the arrow * * @param {number} w * width of the arrow * * @param {number} h * height of the arrow * * @return {Highcharts.SVGPathArray} * Path array */ SVGRenderer.prototype.symbols.arrow = function (x, y, w, h) { return [ ['M', x, y + h / 2], ['L', x + w, y], ['L', x, y + h / 2], ['L', x + w, y + h] ]; }; /** * Creates a half-width arrow symbol. Like a triangle, except not filled. * ``` * o * o * o * o * o * ``` * * @private * @function * * @param {number} x * x position of the arrow * * @param {number} y * y position of the arrow * * @param {number} w * width of the arrow * * @param {number} h * height of the arrow * * @return {Highcharts.SVGPathArray} * Path array */ SVGRenderer.prototype.symbols['arrow-half'] = function (x, y, w, h) { return SVGRenderer.prototype.symbols.arrow(x, y, w / 2, h); }; /** * Creates a left-oriented triangle. * ``` * o * ooooooo * ooooooooooooo * ooooooo * o * ``` * * @private * @function * * @param {number} x * x position of the triangle * * @param {number} y * y position of the triangle * * @param {number} w * width of the triangle * * @param {number} h * height of the triangle * * @return {Highcharts.SVGPathArray} * Path array */ SVGRenderer.prototype.symbols['triangle-left'] = function (x, y, w, h) { return [ ['M', x + w, y], ['L', x, y + h / 2], ['L', x + w, y + h], ['Z'] ]; }; /** * Alias function for triangle-left. * * @private * @function * * @param {number} x * x position of the arrow * * @param {number} y * y position of the arrow * * @param {number} w * width of the arrow * * @param {number} h * height of the arrow * * @return {Highcharts.SVGPathArray} * Path array */ SVGRenderer.prototype.symbols['arrow-filled'] = SVGRenderer.prototype.symbols['triangle-left']; /** * Creates a half-width, left-oriented triangle. * ``` * o * oooo * ooooooo * oooo * o * ``` * * @private * @function * * @param {number} x * x position of the triangle * * @param {number} y * y position of the triangle * * @param {number} w * width of the triangle * * @param {number} h * height of the triangle * * @return {Highcharts.SVGPathArray} * Path array */ SVGRenderer.prototype.symbols['triangle-left-half'] = function (x, y, w, h) { return SVGRenderer.prototype.symbols['triangle-left'](x, y, w / 2, h); }; /** * Alias function for triangle-left-half. * * @private * @function * * @param {number} x * x position of the arrow * * @param {number} y * y position of the arrow * * @param {number} w * width of the arrow * * @param {number} h * height of the arrow * * @return {Highcharts.SVGPathArray} * Path array */ SVGRenderer.prototype.symbols['arrow-filled-half'] = SVGRenderer.prototype.symbols['triangle-left-half']; }); _registerModule(_modules, 'Gantt/Connection.js', [_modules['Core/Globals.js'], _modules['Core/Options.js'], _modules['Core/Series/Point.js'], _modules['Core/Utilities.js']], function (H, O, Point, U) { /* * * * (c) 2016 Highsoft AS * Authors: Øystein Moseng, Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ /** * The default pathfinder algorithm to use for a chart. It is possible to define * your own algorithms by adding them to the * `Highcharts.Pathfinder.prototype.algorithms` * object before the chart has been created. * * The default algorithms are as follows: * * `straight`: Draws a straight line between the connecting * points. Does not avoid other points when drawing. * * `simpleConnect`: Finds a path between the points using right angles * only. Takes only starting/ending points into * account, and will not avoid other points. * * `fastAvoid`: Finds a path between the points using right angles * only. Will attempt to avoid other points, but its * focus is performance over accuracy. Works well with * less dense datasets. * * @typedef {"fastAvoid"|"simpleConnect"|"straight"|string} Highcharts.PathfinderTypeValue */ ''; // detach doclets above var defaultOptions = O.defaultOptions; var addEvent = U.addEvent, defined = U.defined, error = U.error, extend = U.extend, merge = U.merge, objectEach = U.objectEach, pick = U.pick, splat = U.splat; var deg2rad = H.deg2rad, max = Math.max, min = Math.min; /* @todo: - Document how to write your own algorithms - Consider adding a Point.pathTo method that wraps creating a connection and rendering it */ // Set default Pathfinder options extend(defaultOptions, { /** * The Pathfinder module allows you to define connections between any two * points, represented as lines - optionally with markers for the start * and/or end points. Multiple algorithms are available for calculating how * the connecting lines are drawn. * * Connector functionality requires Highcharts Gantt to be loaded. In Gantt * charts, the connectors are used to draw dependencies between tasks. * * @see [dependency](series.gantt.data.dependency) * * @sample gantt/pathfinder/demo * Pathfinder connections * * @declare Highcharts.ConnectorsOptions * @product gantt * @optionparent connectors */ connectors: { /** * Enable connectors for this chart. Requires Highcharts Gantt. * * @type {boolean} * @default true * @since 6.2.0 * @apioption connectors.enabled */ /** * Set the default dash style for this chart's connecting lines. * * @type {string} * @default solid * @since 6.2.0 * @apioption connectors.dashStyle */ /** * Set the default color for this chart's Pathfinder connecting lines. * Defaults to the color of the point being connected. * * @type {Highcharts.ColorString} * @since 6.2.0 * @apioption connectors.lineColor */ /** * Set the default pathfinder margin to use, in pixels. Some Pathfinder * algorithms attempt to avoid obstacles, such as other points in the * chart. These algorithms use this margin to determine how close lines * can be to an obstacle. The default is to compute this automatically * from the size of the obstacles in the chart. * * To draw connecting lines close to existing points, set this to a low * number. For more space around existing points, set this number * higher. * * @sample gantt/pathfinder/algorithm-margin * Small algorithmMargin * * @type {number} * @since 6.2.0 * @apioption connectors.algorithmMargin */ /** * Set the default pathfinder algorithm to use for this chart. It is * possible to define your own algorithms by adding them to the * Highcharts.Pathfinder.prototype.algorithms object before the chart * has been created. * * The default algorithms are as follows: * * `straight`: Draws a straight line between the connecting * points. Does not avoid other points when drawing. * * `simpleConnect`: Finds a path between the points using right angles * only. Takes only starting/ending points into * account, and will not avoid other points. * * `fastAvoid`: Finds a path between the points using right angles * only. Will attempt to avoid other points, but its * focus is performance over accuracy. Works well with * less dense datasets. * * Default value: `straight` is used as default for most series types, * while `simpleConnect` is used as default for Gantt series, to show * dependencies between points. * * @sample gantt/pathfinder/demo * Different types used * * @type {Highcharts.PathfinderTypeValue} * @default undefined * @since 6.2.0 */ type: 'straight', /** * Set the default pixel width for this chart's Pathfinder connecting * lines. * * @since 6.2.0 */ lineWidth: 1, /** * Marker options for this chart's Pathfinder connectors. Note that * this option is overridden by the `startMarker` and `endMarker` * options. * * @declare Highcharts.ConnectorsMarkerOptions * @since 6.2.0 */ marker: { /** * Set the radius of the connector markers. The default is * automatically computed based on the algorithmMargin setting. * * Setting marker.width and marker.height will override this * setting. * * @type {number} * @since 6.2.0 * @apioption connectors.marker.radius */ /** * Set the width of the connector markers. If not supplied, this * is inferred from the marker radius. * * @type {number} * @since 6.2.0 * @apioption connectors.marker.width */ /** * Set the height of the connector markers. If not supplied, this * is inferred from the marker radius. * * @type {number} * @since 6.2.0 * @apioption connectors.marker.height */ /** * Set the color of the connector markers. By default this is the * same as the connector color. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @since 6.2.0 * @apioption connectors.marker.color */ /** * Set the line/border color of the connector markers. By default * this is the same as the marker color. * * @type {Highcharts.ColorString} * @since 6.2.0 * @apioption connectors.marker.lineColor */ /** * Enable markers for the connectors. */ enabled: false, /** * Horizontal alignment of the markers relative to the points. * * @type {Highcharts.AlignValue} */ align: 'center', /** * Vertical alignment of the markers relative to the points. * * @type {Highcharts.VerticalAlignValue} */ verticalAlign: 'middle', /** * Whether or not to draw the markers inside the points. */ inside: false, /** * Set the line/border width of the pathfinder markers. */ lineWidth: 1 }, /** * Marker options specific to the start markers for this chart's * Pathfinder connectors. Overrides the generic marker options. * * @declare Highcharts.ConnectorsStartMarkerOptions * @extends connectors.marker * @since 6.2.0 */ startMarker: { /** * Set the symbol of the connector start markers. */ symbol: 'diamond' }, /** * Marker options specific to the end markers for this chart's * Pathfinder connectors. Overrides the generic marker options. * * @declare Highcharts.ConnectorsEndMarkerOptions * @extends connectors.marker * @since 6.2.0 */ endMarker: { /** * Set the symbol of the connector end markers. */ symbol: 'arrow-filled' } } }); /** * Override Pathfinder connector options for a series. Requires Highcharts Gantt * to be loaded. * * @declare Highcharts.SeriesConnectorsOptionsObject * @extends connectors * @since 6.2.0 * @excluding enabled, algorithmMargin * @product gantt * @apioption plotOptions.series.connectors */ /** * Connect to a point. This option can be either a string, referring to the ID * of another point, or an object, or an array of either. If the option is an * array, each element defines a connection. * * @sample gantt/pathfinder/demo * Different connection types * * @declare Highcharts.XrangePointConnectorsOptionsObject * @type {string|Array<string|*>|*} * @extends plotOptions.series.connectors * @since 6.2.0 * @excluding enabled * @product gantt * @requires highcharts-gantt * @apioption series.xrange.data.connect */ /** * The ID of the point to connect to. * * @type {string} * @since 6.2.0 * @product gantt * @apioption series.xrange.data.connect.to */ /** * Get point bounding box using plotX/plotY and shapeArgs. If using * graphic.getBBox() directly, the bbox will be affected by animation. * * @private * @function * * @param {Highcharts.Point} point * The point to get BB of. * * @return {Highcharts.Dictionary<number>|null} * Result xMax, xMin, yMax, yMin. */ function getPointBB(point) { var shapeArgs = point.shapeArgs, bb; // Prefer using shapeArgs (columns) if (shapeArgs) { return { xMin: shapeArgs.x, xMax: shapeArgs.x + shapeArgs.width, yMin: shapeArgs.y, yMax: shapeArgs.y + shapeArgs.height }; } // Otherwise use plotX/plotY and bb bb = point.graphic && point.graphic.getBBox(); return bb ? { xMin: point.plotX - bb.width / 2, xMax: point.plotX + bb.width / 2, yMin: point.plotY - bb.height / 2, yMax: point.plotY + bb.height / 2 } : null; } /** * Calculate margin to place around obstacles for the pathfinder in pixels. * Returns a minimum of 1 pixel margin. * * @private * @function * * @param {Array<object>} obstacles * Obstacles to calculate margin from. * * @return {number} * The calculated margin in pixels. At least 1. */ function calculateObstacleMargin(obstacles) { var len = obstacles.length, i = 0, j, obstacleDistance, distances = [], // Compute smallest distance between two rectangles distance = function (a, b, bbMargin) { // Count the distance even if we are slightly off var margin = pick(bbMargin, 10), yOverlap = a.yMax + margin > b.yMin - margin && a.yMin - margin < b.yMax + margin, xOverlap = a.xMax + margin > b.xMin - margin && a.xMin - margin < b.xMax + margin, xDistance = yOverlap ? (a.xMin > b.xMax ? a.xMin - b.xMax : b.xMin - a.xMax) : Infinity, yDistance = xOverlap ? (a.yMin > b.yMax ? a.yMin - b.yMax : b.yMin - a.yMax) : Infinity; // If the rectangles collide, try recomputing with smaller margin. // If they collide anyway, discard the obstacle. if (xOverlap && yOverlap) { return (margin ? distance(a, b, Math.floor(margin / 2)) : Infinity); } return min(xDistance, yDistance); }; // Go over all obstacles and compare them to the others. for (; i < len; ++i) { // Compare to all obstacles ahead. We will already have compared this // obstacle to the ones before. for (j = i + 1; j < len; ++j) { obstacleDistance = distance(obstacles[i], obstacles[j]); // TODO: Magic number 80 if (obstacleDistance < 80) { // Ignore large distances distances.push(obstacleDistance); } } } // Ensure we always have at least one value, even in very spaceous charts distances.push(80); return max(Math.floor(distances.sort(function (a, b) { return (a - b); })[ // Discard first 10% of the relevant distances, and then grab // the smallest one. Math.floor(distances.length / 10)] / 2 - 1 // Divide the distance by 2 and subtract 1. ), 1 // 1 is the minimum margin ); } /* eslint-disable no-invalid-this, valid-jsdoc */ /** * The Connection class. Used internally to represent a connection between two * points. * * @private * @class * @name Highcharts.Connection * * @param {Highcharts.Point} from * Connection runs from this Point. * * @param {Highcharts.Point} to * Connection runs to this Point. * * @param {Highcharts.ConnectorsOptions} [options] * Connection options. */ var Connection = /** @class */ (function () { function Connection(from, to, options) { /* * * * Properties * * */ this.chart = void 0; this.fromPoint = void 0; this.graphics = void 0; this.pathfinder = void 0; this.toPoint = void 0; this.init(from, to, options); } /** * Initialize the Connection object. Used as constructor only. * * @function Highcharts.Connection#init * * @param {Highcharts.Point} from * Connection runs from this Point. * * @param {Highcharts.Point} to * Connection runs to this Point. * * @param {Highcharts.ConnectorsOptions} [options] * Connection options. */ Connection.prototype.init = function (from, to, options) { this.fromPoint = from; this.toPoint = to; this.options = options; this.chart = from.series.chart; this.pathfinder = this.chart.pathfinder; }; /** * Add (or update) this connection's path on chart. Stores reference to the * created element on this.graphics.path. * * @function Highcharts.Connection#renderPath * * @param {Highcharts.SVGPathArray} path * Path to render, in array format. E.g. ['M', 0, 0, 'L', 10, 10] * * @param {Highcharts.SVGAttributes} [attribs] * SVG attributes for the path. * * @param {Partial<Highcharts.AnimationOptionsObject>} [animation] * Animation options for the rendering. */ Connection.prototype.renderPath = function (path, attribs, animation) { var connection = this, chart = this.chart, styledMode = chart.styledMode, pathfinder = chart.pathfinder, animate = !chart.options.chart.forExport && animation !== false, pathGraphic = connection.graphics && connection.graphics.path, anim; // Add the SVG element of the pathfinder group if it doesn't exist if (!pathfinder.group) { pathfinder.group = chart.renderer.g() .addClass('highcharts-pathfinder-group') .attr({ zIndex: -1 }) .add(chart.seriesGroup); } // Shift the group to compensate for plot area. // Note: Do this always (even when redrawing a path) to avoid issues // when updating chart in a way that changes plot metrics. pathfinder.group.translate(chart.plotLeft, chart.plotTop); // Create path if does not exist if (!(pathGraphic && pathGraphic.renderer)) { pathGraphic = chart.renderer.path() .add(pathfinder.group); if (!styledMode) { pathGraphic.attr({ opacity: 0 }); } } // Set path attribs and animate to the new path pathGraphic.attr(attribs); anim = { d: path }; if (!styledMode) { anim.opacity = 1; } pathGraphic[animate ? 'animate' : 'attr'](anim, animation); // Store reference on connection this.graphics = this.graphics || {}; this.graphics.path = pathGraphic; }; /** * Calculate and add marker graphics for connection to the chart. The * created/updated elements are stored on this.graphics.start and * this.graphics.end. * * @function Highcharts.Connection#addMarker * * @param {string} type * Marker type, either 'start' or 'end'. * * @param {Highcharts.ConnectorsMarkerOptions} options * All options for this marker. Not calculated or merged with other * options. * * @param {Highcharts.SVGPathArray} path * Connection path in array format. This is used to calculate the * rotation angle of the markers. */ Connection.prototype.addMarker = function (type, options, path) { var connection = this, chart = connection.fromPoint.series.chart, pathfinder = chart.pathfinder, renderer = chart.renderer, point = (type === 'start' ? connection.fromPoint : connection.toPoint), anchor = point.getPathfinderAnchorPoint(options), markerVector, radians, rotation, box, width, height, pathVector, segment; if (!options.enabled) { return; } // Last vector before start/end of path, used to get angle if (type === 'start') { segment = path[1]; } else { // 'end' segment = path[path.length - 2]; } if (segment && segment[0] === 'M' || segment[0] === 'L') { pathVector = { x: segment[1], y: segment[2] }; // Get angle between pathVector and anchor point and use it to // create marker position. radians = point.getRadiansToVector(pathVector, anchor); markerVector = point.getMarkerVector(radians, options.radius, anchor); // Rotation of marker is calculated from angle between pathVector // and markerVector. // (Note: // Used to recalculate radians between markerVector and pathVector, // but this should be the same as between pathVector and anchor.) rotation = -radians / deg2rad; if (options.width && options.height) { width = options.width; height = options.height; } else { width = height = options.radius * 2; } // Add graphics object if it does not exist connection.graphics = connection.graphics || {}; box = { x: markerVector.x - (width / 2), y: markerVector.y - (height / 2), width: width, height: height, rotation: rotation, rotationOriginX: markerVector.x, rotationOriginY: markerVector.y }; if (!connection.graphics[type]) { // Create new marker element connection.graphics[type] = renderer .symbol(options.symbol) .addClass('highcharts-point-connecting-path-' + type + '-marker') .attr(box) .add(pathfinder.group); if (!renderer.styledMode) { connection.graphics[type].attr({ fill: options.color || connection.fromPoint.color, stroke: options.lineColor, 'stroke-width': options.lineWidth, opacity: 0 }) .animate({ opacity: 1 }, point.series.options.animation); } } else { connection.graphics[type].animate(box); } } }; /** * Calculate and return connection path. * Note: Recalculates chart obstacles on demand if they aren't calculated. * * @function Highcharts.Connection#getPath * * @param {Highcharts.ConnectorsOptions} options * Connector options. Not calculated or merged with other options. * * @return {object|undefined} * Calculated SVG path data in array format. */ Connection.prototype.getPath = function (options) { var pathfinder = this.pathfinder, chart = this.chart, algorithm = pathfinder.algorithms[options.type], chartObstacles = pathfinder.chartObstacles; if (typeof algorithm !== 'function') { error('"' + options.type + '" is not a Pathfinder algorithm.'); return { path: [], obstacles: [] }; } // This function calculates obstacles on demand if they don't exist if (algorithm.requiresObstacles && !chartObstacles) { chartObstacles = pathfinder.chartObstacles = pathfinder.getChartObstacles(options); // If the algorithmMargin was computed, store the result in default // options. chart.options.connectors.algorithmMargin = options.algorithmMargin; // Cache some metrics too pathfinder.chartObstacleMetrics = pathfinder.getObstacleMetrics(chartObstacles); } // Get the SVG path return algorithm( // From this.fromPoint.getPathfinderAnchorPoint(options.startMarker), // To this.toPoint.getPathfinderAnchorPoint(options.endMarker), merge({ chartObstacles: chartObstacles, lineObstacles: pathfinder.lineObstacles || [], obstacleMetrics: pathfinder.chartObstacleMetrics, hardBounds: { xMin: 0, xMax: chart.plotWidth, yMin: 0, yMax: chart.plotHeight }, obstacleOptions: { margin: options.algorithmMargin }, startDirectionX: pathfinder.getAlgorithmStartDirection(options.startMarker) }, options)); }; /** * (re)Calculate and (re)draw the connection. * * @function Highcharts.Connection#render */ Connection.prototype.render = function () { var connection = this, fromPoint = connection.fromPoint, series = fromPoint.series, chart = series.chart, pathfinder = chart.pathfinder, pathResult, path, options = merge(chart.options.connectors, series.options.connectors, fromPoint.options.connectors, connection.options), attribs = {}; // Set path attribs if (!chart.styledMode) { attribs.stroke = options.lineColor || fromPoint.color; attribs['stroke-width'] = options.lineWidth; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } } attribs['class'] = // eslint-disable-line dot-notation 'highcharts-point-connecting-path ' + 'highcharts-color-' + fromPoint.colorIndex; options = merge(attribs, options); // Set common marker options if (!defined(options.marker.radius)) { options.marker.radius = min(max(Math.ceil((options.algorithmMargin || 8) / 2) - 1, 1), 5); } // Get the path pathResult = connection.getPath(options); path = pathResult.path; // Always update obstacle storage with obstacles from this path. // We don't know if future calls will need this for their algorithm. if (pathResult.obstacles) { pathfinder.lineObstacles = pathfinder.lineObstacles || []; pathfinder.lineObstacles = pathfinder.lineObstacles.concat(pathResult.obstacles); } // Add the calculated path to the pathfinder group connection.renderPath(path, attribs, series.options.animation); // Render the markers connection.addMarker('start', merge(options.marker, options.startMarker), path); connection.addMarker('end', merge(options.marker, options.endMarker), path); }; /** * Destroy connection by destroying the added graphics elements. * * @function Highcharts.Connection#destroy */ Connection.prototype.destroy = function () { if (this.graphics) { objectEach(this.graphics, function (val) { val.destroy(); }); delete this.graphics; } }; return Connection; }()); // Add to Highcharts namespace H.Connection = Connection; // Add pathfinding capabilities to Points extend(Point.prototype, /** @lends Point.prototype */ { /** * Get coordinates of anchor point for pathfinder connection. * * @private * @function Highcharts.Point#getPathfinderAnchorPoint * * @param {Highcharts.ConnectorsMarkerOptions} markerOptions * Connection options for position on point. * * @return {Highcharts.PositionObject} * An object with x/y properties for the position. Coordinates are * in plot values, not relative to point. */ getPathfinderAnchorPoint: function (markerOptions) { var bb = getPointBB(this), x, y; switch (markerOptions.align) { // eslint-disable-line default-case case 'right': x = 'xMax'; break; case 'left': x = 'xMin'; } switch (markerOptions.verticalAlign) { // eslint-disable-line default-case case 'top': y = 'yMin'; break; case 'bottom': y = 'yMax'; } return { x: x ? bb[x] : (bb.xMin + bb.xMax) / 2, y: y ? bb[y] : (bb.yMin + bb.yMax) / 2 }; }, /** * Utility to get the angle from one point to another. * * @private * @function Highcharts.Point#getRadiansToVector * * @param {Highcharts.PositionObject} v1 * The first vector, as an object with x/y properties. * * @param {Highcharts.PositionObject} v2 * The second vector, as an object with x/y properties. * * @return {number} * The angle in degrees */ getRadiansToVector: function (v1, v2) { var box; if (!defined(v2)) { box = getPointBB(this); if (box) { v2 = { x: (box.xMin + box.xMax) / 2, y: (box.yMin + box.yMax) / 2 }; } } return Math.atan2(v2.y - v1.y, v1.x - v2.x); }, /** * Utility to get the position of the marker, based on the path angle and * the marker's radius. * * @private * @function Highcharts.Point#getMarkerVector * * @param {number} radians * The angle in radians from the point center to another vector. * * @param {number} markerRadius * The radius of the marker, to calculate the additional distance to * the center of the marker. * * @param {object} anchor * The anchor point of the path and marker as an object with x/y * properties. * * @return {object} * The marker vector as an object with x/y properties. */ getMarkerVector: function (radians, markerRadius, anchor) { var twoPI = Math.PI * 2.0, theta = radians, bb = getPointBB(this), rectWidth = bb.xMax - bb.xMin, rectHeight = bb.yMax - bb.yMin, rAtan = Math.atan2(rectHeight, rectWidth), tanTheta = 1, leftOrRightRegion = false, rectHalfWidth = rectWidth / 2.0, rectHalfHeight = rectHeight / 2.0, rectHorizontalCenter = bb.xMin + rectHalfWidth, rectVerticalCenter = bb.yMin + rectHalfHeight, edgePoint = { x: rectHorizontalCenter, y: rectVerticalCenter }, xFactor = 1, yFactor = 1; while (theta < -Math.PI) { theta += twoPI; } while (theta > Math.PI) { theta -= twoPI; } tanTheta = Math.tan(theta); if ((theta > -rAtan) && (theta <= rAtan)) { // Right side yFactor = -1; leftOrRightRegion = true; } else if (theta > rAtan && theta <= (Math.PI - rAtan)) { // Top side yFactor = -1; } else if (theta > (Math.PI - rAtan) || theta <= -(Math.PI - rAtan)) { // Left side xFactor = -1; leftOrRightRegion = true; } else { // Bottom side xFactor = -1; } // Correct the edgePoint according to the placement of the marker if (leftOrRightRegion) { edgePoint.x += xFactor * (rectHalfWidth); edgePoint.y += yFactor * (rectHalfWidth) * tanTheta; } else { edgePoint.x += xFactor * (rectHeight / (2.0 * tanTheta)); edgePoint.y += yFactor * (rectHalfHeight); } if (anchor.x !== rectHorizontalCenter) { edgePoint.x = anchor.x; } if (anchor.y !== rectVerticalCenter) { edgePoint.y = anchor.y; } return { x: edgePoint.x + (markerRadius * Math.cos(theta)), y: edgePoint.y - (markerRadius * Math.sin(theta)) }; } }); /** * Warn if using legacy options. Copy the options over. Note that this will * still break if using the legacy options in chart.update, addSeries etc. * @private */ function warnLegacy(chart) { if (chart.options.pathfinder || chart.series.reduce(function (acc, series) { if (series.options) { merge(true, (series.options.connectors = series.options.connectors || {}), series.options.pathfinder); } return acc || series.options && series.options.pathfinder; }, false)) { merge(true, (chart.options.connectors = chart.options.connectors || {}), chart.options.pathfinder); error('WARNING: Pathfinder options have been renamed. ' + 'Use "chart.connectors" or "series.connectors" instead.'); } } return Connection; }); _registerModule(_modules, 'Gantt/PathfinderAlgorithms.js', [_modules['Core/Utilities.js']], function (U) { /* * * * (c) 2016 Highsoft AS * Author: Øystein Moseng * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var extend = U.extend, pick = U.pick; var min = Math.min, max = Math.max, abs = Math.abs; /** * Get index of last obstacle before xMin. Employs a type of binary search, and * thus requires that obstacles are sorted by xMin value. * * @private * @function findLastObstacleBefore * * @param {Array<object>} obstacles * Array of obstacles to search in. * * @param {number} xMin * The xMin threshold. * * @param {number} [startIx] * Starting index to search from. Must be within array range. * * @return {number} * The index of the last obstacle element before xMin. */ function findLastObstacleBefore(obstacles, xMin, startIx) { var left = startIx || 0, // left limit right = obstacles.length - 1, // right limit min = xMin - 0.0000001, // Make sure we include all obstacles at xMin cursor, cmp; while (left <= right) { cursor = (right + left) >> 1; cmp = min - obstacles[cursor].xMin; if (cmp > 0) { left = cursor + 1; } else if (cmp < 0) { right = cursor - 1; } else { return cursor; } } return left > 0 ? left - 1 : 0; } /** * Test if a point lays within an obstacle. * * @private * @function pointWithinObstacle * * @param {object} obstacle * Obstacle to test. * * @param {Highcharts.Point} point * Point with x/y props. * * @return {boolean} * Whether point is within the obstacle or not. */ function pointWithinObstacle(obstacle, point) { return (point.x <= obstacle.xMax && point.x >= obstacle.xMin && point.y <= obstacle.yMax && point.y >= obstacle.yMin); } /** * Find the index of an obstacle that wraps around a point. * Returns -1 if not found. * * @private * @function findObstacleFromPoint * * @param {Array<object>} obstacles * Obstacles to test. * * @param {Highcharts.Point} point * Point with x/y props. * * @return {number} * Ix of the obstacle in the array, or -1 if not found. */ function findObstacleFromPoint(obstacles, point) { var i = findLastObstacleBefore(obstacles, point.x + 1) + 1; while (i--) { if (obstacles[i].xMax >= point.x && // optimization using lazy evaluation pointWithinObstacle(obstacles[i], point)) { return i; } } return -1; } /** * Get SVG path array from array of line segments. * * @private * @function pathFromSegments * * @param {Array<object>} segments * The segments to build the path from. * * @return {Highcharts.SVGPathArray} * SVG path array as accepted by the SVG Renderer. */ function pathFromSegments(segments) { var path = []; if (segments.length) { path.push(['M', segments[0].start.x, segments[0].start.y]); for (var i = 0; i < segments.length; ++i) { path.push(['L', segments[i].end.x, segments[i].end.y]); } } return path; } /** * Limits obstacle max/mins in all directions to bounds. Modifies input * obstacle. * * @private * @function limitObstacleToBounds * * @param {object} obstacle * Obstacle to limit. * * @param {object} bounds * Bounds to use as limit. * * @return {void} */ function limitObstacleToBounds(obstacle, bounds) { obstacle.yMin = max(obstacle.yMin, bounds.yMin); obstacle.yMax = min(obstacle.yMax, bounds.yMax); obstacle.xMin = max(obstacle.xMin, bounds.xMin); obstacle.xMax = min(obstacle.xMax, bounds.xMax); } /** * Get an SVG path from a starting coordinate to an ending coordinate. * Draws a straight line. * * @function Highcharts.Pathfinder.algorithms.straight * * @param {Highcharts.PositionObject} start * Starting coordinate, object with x/y props. * * @param {Highcharts.PositionObject} end * Ending coordinate, object with x/y props. * * @return {object} * An object with the SVG path in Array form as accepted by the SVG * renderer, as well as an array of new obstacles making up this * path. */ function straight(start, end) { return { path: [ ['M', start.x, start.y], ['L', end.x, end.y] ], obstacles: [{ start: start, end: end }] }; } /** * Find a path from a starting coordinate to an ending coordinate, using * right angles only, and taking only starting/ending obstacle into * consideration. * * @function Highcharts.Pathfinder.algorithms.simpleConnect * * @param {Highcharts.PositionObject} start * Starting coordinate, object with x/y props. * * @param {Highcharts.PositionObject} end * Ending coordinate, object with x/y props. * * @param {object} options * Options for the algorithm: * - chartObstacles: Array of chart obstacles to avoid * - startDirectionX: Optional. True if starting in the X direction. * If not provided, the algorithm starts in the direction that is * the furthest between start/end. * * @return {object} * An object with the SVG path in Array form as accepted by the SVG * renderer, as well as an array of new obstacles making up this * path. */ var simpleConnect = extend(function (start, end, options) { var segments = [], endSegment, dir = pick(options.startDirectionX, abs(end.x - start.x) > abs(end.y - start.y)) ? 'x' : 'y', chartObstacles = options.chartObstacles, startObstacleIx = findObstacleFromPoint(chartObstacles, start), endObstacleIx = findObstacleFromPoint(chartObstacles, end), startObstacle, endObstacle, prevWaypoint, waypoint, waypoint2, useMax, endPoint; // eslint-disable-next-line valid-jsdoc /** * Return a clone of a point with a property set from a target object, * optionally with an offset * @private */ function copyFromPoint(from, fromKey, to, toKey, offset) { var point = { x: from.x, y: from.y }; point[fromKey] = to[toKey || fromKey] + (offset || 0); return point; } // eslint-disable-next-line valid-jsdoc /** * Return waypoint outside obstacle. * @private */ function getMeOut(obstacle, point, direction) { var useMax = abs(point[direction] - obstacle[direction + 'Min']) > abs(point[direction] - obstacle[direction + 'Max']); return copyFromPoint(point, direction, obstacle, direction + (useMax ? 'Max' : 'Min'), useMax ? 1 : -1); } // Pull out end point if (endObstacleIx > -1) { endObstacle = chartObstacles[endObstacleIx]; waypoint = getMeOut(endObstacle, end, dir); endSegment = { start: waypoint, end: end }; endPoint = waypoint; } else { endPoint = end; } // If an obstacle envelops the start point, add a segment to get out, // and around it. if (startObstacleIx > -1) { startObstacle = chartObstacles[startObstacleIx]; waypoint = getMeOut(startObstacle, start, dir); segments.push({ start: start, end: waypoint }); // If we are going back again, switch direction to get around start // obstacle. if ( // Going towards max from start: waypoint[dir] >= start[dir] === // Going towards min to end: waypoint[dir] >= endPoint[dir]) { dir = dir === 'y' ? 'x' : 'y'; useMax = start[dir] < end[dir]; segments.push({ start: waypoint, end: copyFromPoint(waypoint, dir, startObstacle, dir + (useMax ? 'Max' : 'Min'), useMax ? 1 : -1) }); // Switch direction again dir = dir === 'y' ? 'x' : 'y'; } } // We are around the start obstacle. Go towards the end in one // direction. prevWaypoint = segments.length ? segments[segments.length - 1].end : start; waypoint = copyFromPoint(prevWaypoint, dir, endPoint); segments.push({ start: prevWaypoint, end: waypoint }); // Final run to end point in the other direction dir = dir === 'y' ? 'x' : 'y'; waypoint2 = copyFromPoint(waypoint, dir, endPoint); segments.push({ start: waypoint, end: waypoint2 }); // Finally add the endSegment segments.push(endSegment); return { path: pathFromSegments(segments), obstacles: segments }; }, { requiresObstacles: true }); /** * Find a path from a starting coordinate to an ending coordinate, taking * obstacles into consideration. Might not always find the optimal path, * but is fast, and usually good enough. * * @function Highcharts.Pathfinder.algorithms.fastAvoid * * @param {Highcharts.PositionObject} start * Starting coordinate, object with x/y props. * * @param {Highcharts.PositionObject} end * Ending coordinate, object with x/y props. * * @param {object} options * Options for the algorithm. * - chartObstacles: Array of chart obstacles to avoid * - lineObstacles: Array of line obstacles to jump over * - obstacleMetrics: Object with metrics of chartObstacles cached * - hardBounds: Hard boundaries to not cross * - obstacleOptions: Options for the obstacles, including margin * - startDirectionX: Optional. True if starting in the X direction. * If not provided, the algorithm starts in the * direction that is the furthest between * start/end. * * @return {object} * An object with the SVG path in Array form as accepted by the SVG * renderer, as well as an array of new obstacles making up this * path. */ var fastAvoid = extend(function (start, end, options) { /* Algorithm rules/description - Find initial direction - Determine soft/hard max for each direction. - Move along initial direction until obstacle. - Change direction. - If hitting obstacle, first try to change length of previous line before changing direction again. Soft min/max x = start/destination x +/- widest obstacle + margin Soft min/max y = start/destination y +/- tallest obstacle + margin @todo: - Make retrospective, try changing prev segment to reduce corners - Fix logic for breaking out of end-points - not always picking the best direction currently - When going around the end obstacle we should not always go the shortest route, rather pick the one closer to the end point */ var dirIsX = pick(options.startDirectionX, abs(end.x - start.x) > abs(end.y - start.y)), dir = dirIsX ? 'x' : 'y', segments, useMax, extractedEndPoint, endSegments = [], forceObstacleBreak = false, // Used in clearPathTo to keep track of // when to force break through an obstacle. // Boundaries to stay within. If beyond soft boundary, prefer to // change direction ASAP. If at hard max, always change immediately. metrics = options.obstacleMetrics, softMinX = min(start.x, end.x) - metrics.maxWidth - 10, softMaxX = max(start.x, end.x) + metrics.maxWidth + 10, softMinY = min(start.y, end.y) - metrics.maxHeight - 10, softMaxY = max(start.y, end.y) + metrics.maxHeight + 10, // Obstacles chartObstacles = options.chartObstacles, startObstacleIx = findLastObstacleBefore(chartObstacles, softMinX), endObstacleIx = findLastObstacleBefore(chartObstacles, softMaxX); // eslint-disable-next-line valid-jsdoc /** * How far can you go between two points before hitting an obstacle? * Does not work for diagonal lines (because it doesn't have to). * @private */ function pivotPoint(fromPoint, toPoint, directionIsX) { var firstPoint, lastPoint, highestPoint, lowestPoint, i, searchDirection = fromPoint.x < toPoint.x ? 1 : -1; if (fromPoint.x < toPoint.x) { firstPoint = fromPoint; lastPoint = toPoint; } else { firstPoint = toPoint; lastPoint = fromPoint; } if (fromPoint.y < toPoint.y) { lowestPoint = fromPoint; highestPoint = toPoint; } else { lowestPoint = toPoint; highestPoint = fromPoint; } // Go through obstacle range in reverse if toPoint is before // fromPoint in the X-dimension. i = searchDirection < 0 ? // Searching backwards, start at last obstacle before last point min(findLastObstacleBefore(chartObstacles, lastPoint.x), chartObstacles.length - 1) : // Forwards. Since we're not sorted by xMax, we have to look // at all obstacles. 0; // Go through obstacles in this X range while (chartObstacles[i] && (searchDirection > 0 && chartObstacles[i].xMin <= lastPoint.x || searchDirection < 0 && chartObstacles[i].xMax >= firstPoint.x)) { // If this obstacle is between from and to points in a straight // line, pivot at the intersection. if (chartObstacles[i].xMin <= lastPoint.x && chartObstacles[i].xMax >= firstPoint.x && chartObstacles[i].yMin <= highestPoint.y && chartObstacles[i].yMax >= lowestPoint.y) { if (directionIsX) { return { y: fromPoint.y, x: fromPoint.x < toPoint.x ? chartObstacles[i].xMin - 1 : chartObstacles[i].xMax + 1, obstacle: chartObstacles[i] }; } // else ... return { x: fromPoint.x, y: fromPoint.y < toPoint.y ? chartObstacles[i].yMin - 1 : chartObstacles[i].yMax + 1, obstacle: chartObstacles[i] }; } i += searchDirection; } return toPoint; } /** * Decide in which direction to dodge or get out of an obstacle. * Considers desired direction, which way is shortest, soft and hard * bounds. * * (? Returns a string, either xMin, xMax, yMin or yMax.) * * @private * @function * * @param {object} obstacle * Obstacle to dodge/escape. * * @param {object} fromPoint * Point with x/y props that's dodging/escaping. * * @param {object} toPoint * Goal point. * * @param {boolean} dirIsX * Dodge in X dimension. * * @param {object} bounds * Hard and soft boundaries. * * @return {boolean} * Use max or not. */ function getDodgeDirection(obstacle, fromPoint, toPoint, dirIsX, bounds) { var softBounds = bounds.soft, hardBounds = bounds.hard, dir = dirIsX ? 'x' : 'y', toPointMax = { x: fromPoint.x, y: fromPoint.y }, toPointMin = { x: fromPoint.x, y: fromPoint.y }, minPivot, maxPivot, maxOutOfSoftBounds = obstacle[dir + 'Max'] >= softBounds[dir + 'Max'], minOutOfSoftBounds = obstacle[dir + 'Min'] <= softBounds[dir + 'Min'], maxOutOfHardBounds = obstacle[dir + 'Max'] >= hardBounds[dir + 'Max'], minOutOfHardBounds = obstacle[dir + 'Min'] <= hardBounds[dir + 'Min'], // Find out if we should prefer one direction over the other if // we can choose freely minDistance = abs(obstacle[dir + 'Min'] - fromPoint[dir]), maxDistance = abs(obstacle[dir + 'Max'] - fromPoint[dir]), // If it's a small difference, pick the one leading towards dest // point. Otherwise pick the shortest distance useMax = abs(minDistance - maxDistance) < 10 ? fromPoint[dir] < toPoint[dir] : maxDistance < minDistance; // Check if we hit any obstacles trying to go around in either // direction. toPointMin[dir] = obstacle[dir + 'Min']; toPointMax[dir] = obstacle[dir + 'Max']; minPivot = pivotPoint(fromPoint, toPointMin, dirIsX)[dir] !== toPointMin[dir]; maxPivot = pivotPoint(fromPoint, toPointMax, dirIsX)[dir] !== toPointMax[dir]; useMax = minPivot ? (maxPivot ? useMax : true) : (maxPivot ? false : useMax); // useMax now contains our preferred choice, bounds not taken into // account. If both or neither direction is out of bounds we want to // use this. // Deal with soft bounds useMax = minOutOfSoftBounds ? (maxOutOfSoftBounds ? useMax : true) : // Out on min (maxOutOfSoftBounds ? false : useMax); // Not out on min // Deal with hard bounds useMax = minOutOfHardBounds ? (maxOutOfHardBounds ? useMax : true) : // Out on min (maxOutOfHardBounds ? false : useMax); // Not out on min return useMax; } // eslint-disable-next-line valid-jsdoc /** * Find a clear path between point. * @private */ function clearPathTo(fromPoint, toPoint, dirIsX) { // Don't waste time if we've hit goal if (fromPoint.x === toPoint.x && fromPoint.y === toPoint.y) { return []; } var dir = dirIsX ? 'x' : 'y', pivot, segments, waypoint, waypointUseMax, envelopingObstacle, secondEnvelopingObstacle, envelopWaypoint, obstacleMargin = options.obstacleOptions.margin, bounds = { soft: { xMin: softMinX, xMax: softMaxX, yMin: softMinY, yMax: softMaxY }, hard: options.hardBounds }; // If fromPoint is inside an obstacle we have a problem. Break out // by just going to the outside of this obstacle. We prefer to go to // the nearest edge in the chosen direction. envelopingObstacle = findObstacleFromPoint(chartObstacles, fromPoint); if (envelopingObstacle > -1) { envelopingObstacle = chartObstacles[envelopingObstacle]; waypointUseMax = getDodgeDirection(envelopingObstacle, fromPoint, toPoint, dirIsX, bounds); // Cut obstacle to hard bounds to make sure we stay within limitObstacleToBounds(envelopingObstacle, options.hardBounds); envelopWaypoint = dirIsX ? { y: fromPoint.y, x: envelopingObstacle[waypointUseMax ? 'xMax' : 'xMin'] + (waypointUseMax ? 1 : -1) } : { x: fromPoint.x, y: envelopingObstacle[waypointUseMax ? 'yMax' : 'yMin'] + (waypointUseMax ? 1 : -1) }; // If we crashed into another obstacle doing this, we put the // waypoint between them instead secondEnvelopingObstacle = findObstacleFromPoint(chartObstacles, envelopWaypoint); if (secondEnvelopingObstacle > -1) { secondEnvelopingObstacle = chartObstacles[secondEnvelopingObstacle]; // Cut obstacle to hard bounds limitObstacleToBounds(secondEnvelopingObstacle, options.hardBounds); // Modify waypoint to lay between obstacles envelopWaypoint[dir] = waypointUseMax ? max(envelopingObstacle[dir + 'Max'] - obstacleMargin + 1, (secondEnvelopingObstacle[dir + 'Min'] + envelopingObstacle[dir + 'Max']) / 2) : min((envelopingObstacle[dir + 'Min'] + obstacleMargin - 1), ((secondEnvelopingObstacle[dir + 'Max'] + envelopingObstacle[dir + 'Min']) / 2)); // We are not going anywhere. If this happens for the first // time, do nothing. Otherwise, try to go to the extreme of // the obstacle pair in the current direction. if (fromPoint.x === envelopWaypoint.x && fromPoint.y === envelopWaypoint.y) { if (forceObstacleBreak) { envelopWaypoint[dir] = waypointUseMax ? max(envelopingObstacle[dir + 'Max'], secondEnvelopingObstacle[dir + 'Max']) + 1 : min(envelopingObstacle[dir + 'Min'], secondEnvelopingObstacle[dir + 'Min']) - 1; } // Toggle on if off, and the opposite forceObstacleBreak = !forceObstacleBreak; } else { // This point is not identical to previous. // Clear break trigger. forceObstacleBreak = false; } } segments = [{ start: fromPoint, end: envelopWaypoint }]; } else { // If not enveloping, use standard pivot calculation pivot = pivotPoint(fromPoint, { x: dirIsX ? toPoint.x : fromPoint.x, y: dirIsX ? fromPoint.y : toPoint.y }, dirIsX); segments = [{ start: fromPoint, end: { x: pivot.x, y: pivot.y } }]; // Pivot before goal, use a waypoint to dodge obstacle if (pivot[dirIsX ? 'x' : 'y'] !== toPoint[dirIsX ? 'x' : 'y']) { // Find direction of waypoint waypointUseMax = getDodgeDirection(pivot.obstacle, pivot, toPoint, !dirIsX, bounds); // Cut waypoint to hard bounds limitObstacleToBounds(pivot.obstacle, options.hardBounds); waypoint = { x: dirIsX ? pivot.x : pivot.obstacle[waypointUseMax ? 'xMax' : 'xMin'] + (waypointUseMax ? 1 : -1), y: dirIsX ? pivot.obstacle[waypointUseMax ? 'yMax' : 'yMin'] + (waypointUseMax ? 1 : -1) : pivot.y }; // We're changing direction here, store that to make sure we // also change direction when adding the last segment array // after handling waypoint. dirIsX = !dirIsX; segments = segments.concat(clearPathTo({ x: pivot.x, y: pivot.y }, waypoint, dirIsX)); } } // Get segments for the other direction too // Recursion is our friend segments = segments.concat(clearPathTo(segments[segments.length - 1].end, toPoint, !dirIsX)); return segments; } // eslint-disable-next-line valid-jsdoc /** * Extract point to outside of obstacle in whichever direction is * closest. Returns new point outside obstacle. * @private */ function extractFromObstacle(obstacle, point, goalPoint) { var dirIsX = min(obstacle.xMax - point.x, point.x - obstacle.xMin) < min(obstacle.yMax - point.y, point.y - obstacle.yMin), bounds = { soft: options.hardBounds, hard: options.hardBounds }, useMax = getDodgeDirection(obstacle, point, goalPoint, dirIsX, bounds); return dirIsX ? { y: point.y, x: obstacle[useMax ? 'xMax' : 'xMin'] + (useMax ? 1 : -1) } : { x: point.x, y: obstacle[useMax ? 'yMax' : 'yMin'] + (useMax ? 1 : -1) }; } // Cut the obstacle array to soft bounds for optimization in large // datasets. chartObstacles = chartObstacles.slice(startObstacleIx, endObstacleIx + 1); // If an obstacle envelops the end point, move it out of there and add // a little segment to where it was. if ((endObstacleIx = findObstacleFromPoint(chartObstacles, end)) > -1) { extractedEndPoint = extractFromObstacle(chartObstacles[endObstacleIx], end, start); endSegments.push({ end: end, start: extractedEndPoint }); end = extractedEndPoint; } // If it's still inside one or more obstacles, get out of there by // force-moving towards the start point. while ((endObstacleIx = findObstacleFromPoint(chartObstacles, end)) > -1) { useMax = end[dir] - start[dir] < 0; extractedEndPoint = { x: end.x, y: end.y }; extractedEndPoint[dir] = chartObstacles[endObstacleIx][useMax ? dir + 'Max' : dir + 'Min'] + (useMax ? 1 : -1); endSegments.push({ end: end, start: extractedEndPoint }); end = extractedEndPoint; } // Find the path segments = clearPathTo(start, end, dirIsX); // Add the end-point segments segments = segments.concat(endSegments.reverse()); return { path: pathFromSegments(segments), obstacles: segments }; }, { requiresObstacles: true }); // Define the available pathfinding algorithms. // Algorithms take up to 3 arguments: starting point, ending point, and an // options object. var algorithms = { fastAvoid: fastAvoid, straight: straight, simpleConnect: simpleConnect }; return algorithms; }); _registerModule(_modules, 'Gantt/Pathfinder.js', [_modules['Gantt/Connection.js'], _modules['Core/Chart/Chart.js'], _modules['Core/Globals.js'], _modules['Core/Options.js'], _modules['Core/Series/Point.js'], _modules['Core/Utilities.js'], _modules['Gantt/PathfinderAlgorithms.js']], function (Connection, Chart, H, O, Point, U, pathfinderAlgorithms) { /* * * * (c) 2016 Highsoft AS * Authors: Øystein Moseng, Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ /** * The default pathfinder algorithm to use for a chart. It is possible to define * your own algorithms by adding them to the * `Highcharts.Pathfinder.prototype.algorithms` * object before the chart has been created. * * The default algorithms are as follows: * * `straight`: Draws a straight line between the connecting * points. Does not avoid other points when drawing. * * `simpleConnect`: Finds a path between the points using right angles * only. Takes only starting/ending points into * account, and will not avoid other points. * * `fastAvoid`: Finds a path between the points using right angles * only. Will attempt to avoid other points, but its * focus is performance over accuracy. Works well with * less dense datasets. * * @typedef {"fastAvoid"|"simpleConnect"|"straight"|string} Highcharts.PathfinderTypeValue */ ''; // detach doclets above var defaultOptions = O.defaultOptions; var addEvent = U.addEvent, defined = U.defined, error = U.error, extend = U.extend, merge = U.merge, objectEach = U.objectEach, pick = U.pick, splat = U.splat; var deg2rad = H.deg2rad, max = Math.max, min = Math.min; /* @todo: - Document how to write your own algorithms - Consider adding a Point.pathTo method that wraps creating a connection and rendering it */ // Set default Pathfinder options extend(defaultOptions, { /** * The Pathfinder module allows you to define connections between any two * points, represented as lines - optionally with markers for the start * and/or end points. Multiple algorithms are available for calculating how * the connecting lines are drawn. * * Connector functionality requires Highcharts Gantt to be loaded. In Gantt * charts, the connectors are used to draw dependencies between tasks. * * @see [dependency](series.gantt.data.dependency) * * @sample gantt/pathfinder/demo * Pathfinder connections * * @declare Highcharts.ConnectorsOptions * @product gantt * @optionparent connectors */ connectors: { /** * Enable connectors for this chart. Requires Highcharts Gantt. * * @type {boolean} * @default true * @since 6.2.0 * @apioption connectors.enabled */ /** * Set the default dash style for this chart's connecting lines. * * @type {string} * @default solid * @since 6.2.0 * @apioption connectors.dashStyle */ /** * Set the default color for this chart's Pathfinder connecting lines. * Defaults to the color of the point being connected. * * @type {Highcharts.ColorString} * @since 6.2.0 * @apioption connectors.lineColor */ /** * Set the default pathfinder margin to use, in pixels. Some Pathfinder * algorithms attempt to avoid obstacles, such as other points in the * chart. These algorithms use this margin to determine how close lines * can be to an obstacle. The default is to compute this automatically * from the size of the obstacles in the chart. * * To draw connecting lines close to existing points, set this to a low * number. For more space around existing points, set this number * higher. * * @sample gantt/pathfinder/algorithm-margin * Small algorithmMargin * * @type {number} * @since 6.2.0 * @apioption connectors.algorithmMargin */ /** * Set the default pathfinder algorithm to use for this chart. It is * possible to define your own algorithms by adding them to the * Highcharts.Pathfinder.prototype.algorithms object before the chart * has been created. * * The default algorithms are as follows: * * `straight`: Draws a straight line between the connecting * points. Does not avoid other points when drawing. * * `simpleConnect`: Finds a path between the points using right angles * only. Takes only starting/ending points into * account, and will not avoid other points. * * `fastAvoid`: Finds a path between the points using right angles * only. Will attempt to avoid other points, but its * focus is performance over accuracy. Works well with * less dense datasets. * * Default value: `straight` is used as default for most series types, * while `simpleConnect` is used as default for Gantt series, to show * dependencies between points. * * @sample gantt/pathfinder/demo * Different types used * * @type {Highcharts.PathfinderTypeValue} * @default undefined * @since 6.2.0 */ type: 'straight', /** * Set the default pixel width for this chart's Pathfinder connecting * lines. * * @since 6.2.0 */ lineWidth: 1, /** * Marker options for this chart's Pathfinder connectors. Note that * this option is overridden by the `startMarker` and `endMarker` * options. * * @declare Highcharts.ConnectorsMarkerOptions * @since 6.2.0 */ marker: { /** * Set the radius of the connector markers. The default is * automatically computed based on the algorithmMargin setting. * * Setting marker.width and marker.height will override this * setting. * * @type {number} * @since 6.2.0 * @apioption connectors.marker.radius */ /** * Set the width of the connector markers. If not supplied, this * is inferred from the marker radius. * * @type {number} * @since 6.2.0 * @apioption connectors.marker.width */ /** * Set the height of the connector markers. If not supplied, this * is inferred from the marker radius. * * @type {number} * @since 6.2.0 * @apioption connectors.marker.height */ /** * Set the color of the connector markers. By default this is the * same as the connector color. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @since 6.2.0 * @apioption connectors.marker.color */ /** * Set the line/border color of the connector markers. By default * this is the same as the marker color. * * @type {Highcharts.ColorString} * @since 6.2.0 * @apioption connectors.marker.lineColor */ /** * Enable markers for the connectors. */ enabled: false, /** * Horizontal alignment of the markers relative to the points. * * @type {Highcharts.AlignValue} */ align: 'center', /** * Vertical alignment of the markers relative to the points. * * @type {Highcharts.VerticalAlignValue} */ verticalAlign: 'middle', /** * Whether or not to draw the markers inside the points. */ inside: false, /** * Set the line/border width of the pathfinder markers. */ lineWidth: 1 }, /** * Marker options specific to the start markers for this chart's * Pathfinder connectors. Overrides the generic marker options. * * @declare Highcharts.ConnectorsStartMarkerOptions * @extends connectors.marker * @since 6.2.0 */ startMarker: { /** * Set the symbol of the connector start markers. */ symbol: 'diamond' }, /** * Marker options specific to the end markers for this chart's * Pathfinder connectors. Overrides the generic marker options. * * @declare Highcharts.ConnectorsEndMarkerOptions * @extends connectors.marker * @since 6.2.0 */ endMarker: { /** * Set the symbol of the connector end markers. */ symbol: 'arrow-filled' } } }); /** * Override Pathfinder connector options for a series. Requires Highcharts Gantt * to be loaded. * * @declare Highcharts.SeriesConnectorsOptionsObject * @extends connectors * @since 6.2.0 * @excluding enabled, algorithmMargin * @product gantt * @apioption plotOptions.series.connectors */ /** * Connect to a point. This option can be either a string, referring to the ID * of another point, or an object, or an array of either. If the option is an * array, each element defines a connection. * * @sample gantt/pathfinder/demo * Different connection types * * @declare Highcharts.XrangePointConnectorsOptionsObject * @type {string|Array<string|*>|*} * @extends plotOptions.series.connectors * @since 6.2.0 * @excluding enabled * @product gantt * @requires highcharts-gantt * @apioption series.xrange.data.connect */ /** * The ID of the point to connect to. * * @type {string} * @since 6.2.0 * @product gantt * @apioption series.xrange.data.connect.to */ /** * Get point bounding box using plotX/plotY and shapeArgs. If using * graphic.getBBox() directly, the bbox will be affected by animation. * * @private * @function * * @param {Highcharts.Point} point * The point to get BB of. * * @return {Highcharts.Dictionary<number>|null} * Result xMax, xMin, yMax, yMin. */ function getPointBB(point) { var shapeArgs = point.shapeArgs, bb; // Prefer using shapeArgs (columns) if (shapeArgs) { return { xMin: shapeArgs.x, xMax: shapeArgs.x + shapeArgs.width, yMin: shapeArgs.y, yMax: shapeArgs.y + shapeArgs.height }; } // Otherwise use plotX/plotY and bb bb = point.graphic && point.graphic.getBBox(); return bb ? { xMin: point.plotX - bb.width / 2, xMax: point.plotX + bb.width / 2, yMin: point.plotY - bb.height / 2, yMax: point.plotY + bb.height / 2 } : null; } /** * Calculate margin to place around obstacles for the pathfinder in pixels. * Returns a minimum of 1 pixel margin. * * @private * @function * * @param {Array<object>} obstacles * Obstacles to calculate margin from. * * @return {number} * The calculated margin in pixels. At least 1. */ function calculateObstacleMargin(obstacles) { var len = obstacles.length, i = 0, j, obstacleDistance, distances = [], // Compute smallest distance between two rectangles distance = function (a, b, bbMargin) { // Count the distance even if we are slightly off var margin = pick(bbMargin, 10), yOverlap = a.yMax + margin > b.yMin - margin && a.yMin - margin < b.yMax + margin, xOverlap = a.xMax + margin > b.xMin - margin && a.xMin - margin < b.xMax + margin, xDistance = yOverlap ? (a.xMin > b.xMax ? a.xMin - b.xMax : b.xMin - a.xMax) : Infinity, yDistance = xOverlap ? (a.yMin > b.yMax ? a.yMin - b.yMax : b.yMin - a.yMax) : Infinity; // If the rectangles collide, try recomputing with smaller margin. // If they collide anyway, discard the obstacle. if (xOverlap && yOverlap) { return (margin ? distance(a, b, Math.floor(margin / 2)) : Infinity); } return min(xDistance, yDistance); }; // Go over all obstacles and compare them to the others. for (; i < len; ++i) { // Compare to all obstacles ahead. We will already have compared this // obstacle to the ones before. for (j = i + 1; j < len; ++j) { obstacleDistance = distance(obstacles[i], obstacles[j]); // TODO: Magic number 80 if (obstacleDistance < 80) { // Ignore large distances distances.push(obstacleDistance); } } } // Ensure we always have at least one value, even in very spaceous charts distances.push(80); return max(Math.floor(distances.sort(function (a, b) { return (a - b); })[ // Discard first 10% of the relevant distances, and then grab // the smallest one. Math.floor(distances.length / 10)] / 2 - 1 // Divide the distance by 2 and subtract 1. ), 1 // 1 is the minimum margin ); } /* eslint-disable no-invalid-this, valid-jsdoc */ /** * The Pathfinder class. * * @private * @class * @name Highcharts.Pathfinder * * @param {Highcharts.Chart} chart * The chart to operate on. */ var Pathfinder = /** @class */ (function () { function Pathfinder(chart) { /* * * * Properties * * */ this.chart = void 0; this.chartObstacles = void 0; this.chartObstacleMetrics = void 0; this.connections = void 0; this.group = void 0; this.lineObstacles = void 0; this.init(chart); } /** * @name Highcharts.Pathfinder#algorithms * @type {Highcharts.Dictionary<Function>} */ /** * Initialize the Pathfinder object. * * @function Highcharts.Pathfinder#init * * @param {Highcharts.Chart} chart * The chart context. */ Pathfinder.prototype.init = function (chart) { // Initialize pathfinder with chart context this.chart = chart; // Init connection reference list this.connections = []; // Recalculate paths/obstacles on chart redraw addEvent(chart, 'redraw', function () { this.pathfinder.update(); }); }; /** * Update Pathfinder connections from scratch. * * @function Highcharts.Pathfinder#update * * @param {boolean} [deferRender] * Whether or not to defer rendering of connections until * series.afterAnimate event has fired. Used on first render. */ Pathfinder.prototype.update = function (deferRender) { var chart = this.chart, pathfinder = this, oldConnections = pathfinder.connections; // Rebuild pathfinder connections from options pathfinder.connections = []; chart.series.forEach(function (series) { if (series.visible && !series.options.isInternal) { series.points.forEach(function (point) { var ganttPointOptions = point.options; // For Gantt series the connect could be // defined as a dependency if (ganttPointOptions && ganttPointOptions.dependency) { ganttPointOptions.connect = ganttPointOptions.dependency; } var to, connects = (point.options && point.options.connect && splat(point.options.connect)); if (point.visible && point.isInside !== false && connects) { connects.forEach(function (connect) { to = chart.get(typeof connect === 'string' ? connect : connect.to); if (to instanceof Point && to.series.visible && to.visible && to.isInside !== false) { // Add new connection pathfinder.connections.push(new Connection(point, // from to, typeof connect === 'string' ? {} : connect)); } }); } }); } }); // Clear connections that should not be updated, and move old info over // to new connections. for (var j = 0, k, found, lenOld = oldConnections.length, lenNew = pathfinder.connections.length; j < lenOld; ++j) { found = false; for (k = 0; k < lenNew; ++k) { if (oldConnections[j].fromPoint === pathfinder.connections[k].fromPoint && oldConnections[j].toPoint === pathfinder.connections[k].toPoint) { pathfinder.connections[k].graphics = oldConnections[j].graphics; found = true; break; } } if (!found) { oldConnections[j].destroy(); } } // Clear obstacles to force recalculation. This must be done on every // redraw in case positions have changed. Recalculation is handled in // Connection.getPath on demand. delete this.chartObstacles; delete this.lineObstacles; // Draw the pending connections pathfinder.renderConnections(deferRender); }; /** * Draw the chart's connecting paths. * * @function Highcharts.Pathfinder#renderConnections * * @param {boolean} [deferRender] * Whether or not to defer render until series animation is finished. * Used on first render. */ Pathfinder.prototype.renderConnections = function (deferRender) { if (deferRender) { // Render after series are done animating this.chart.series.forEach(function (series) { var render = function () { // Find pathfinder connections belonging to this series // that haven't rendered, and render them now. var pathfinder = series.chart.pathfinder, conns = pathfinder && pathfinder.connections || []; conns.forEach(function (connection) { if (connection.fromPoint && connection.fromPoint.series === series) { connection.render(); } }); if (series.pathfinderRemoveRenderEvent) { series.pathfinderRemoveRenderEvent(); delete series.pathfinderRemoveRenderEvent; } }; if (series.options.animation === false) { render(); } else { series.pathfinderRemoveRenderEvent = addEvent(series, 'afterAnimate', render); } }); } else { // Go through connections and render them this.connections.forEach(function (connection) { connection.render(); }); } }; /** * Get obstacles for the points in the chart. Does not include connecting * lines from Pathfinder. Applies algorithmMargin to the obstacles. * * @function Highcharts.Pathfinder#getChartObstacles * * @param {object} options * Options for the calculation. Currenlty only * options.algorithmMargin. * * @return {Array<object>} * An array of calculated obstacles. Each obstacle is defined as an * object with xMin, xMax, yMin and yMax properties. */ Pathfinder.prototype.getChartObstacles = function (options) { var obstacles = [], series = this.chart.series, margin = pick(options.algorithmMargin, 0), calculatedMargin; for (var i = 0, sLen = series.length; i < sLen; ++i) { if (series[i].visible && !series[i].options.isInternal) { for (var j = 0, pLen = series[i].points.length, bb, point; j < pLen; ++j) { point = series[i].points[j]; if (point.visible) { bb = getPointBB(point); if (bb) { obstacles.push({ xMin: bb.xMin - margin, xMax: bb.xMax + margin, yMin: bb.yMin - margin, yMax: bb.yMax + margin }); } } } } } // Sort obstacles by xMin for optimization obstacles = obstacles.sort(function (a, b) { return a.xMin - b.xMin; }); // Add auto-calculated margin if the option is not defined if (!defined(options.algorithmMargin)) { calculatedMargin = options.algorithmMargin = calculateObstacleMargin(obstacles); obstacles.forEach(function (obstacle) { obstacle.xMin -= calculatedMargin; obstacle.xMax += calculatedMargin; obstacle.yMin -= calculatedMargin; obstacle.yMax += calculatedMargin; }); } return obstacles; }; /** * Utility function to get metrics for obstacles: * - Widest obstacle width * - Tallest obstacle height * * @function Highcharts.Pathfinder#getObstacleMetrics * * @param {Array<object>} obstacles * An array of obstacles to inspect. * * @return {object} * The calculated metrics, as an object with maxHeight and maxWidth * properties. */ Pathfinder.prototype.getObstacleMetrics = function (obstacles) { var maxWidth = 0, maxHeight = 0, width, height, i = obstacles.length; while (i--) { width = obstacles[i].xMax - obstacles[i].xMin; height = obstacles[i].yMax - obstacles[i].yMin; if (maxWidth < width) { maxWidth = width; } if (maxHeight < height) { maxHeight = height; } } return { maxHeight: maxHeight, maxWidth: maxWidth }; }; /** * Utility to get which direction to start the pathfinding algorithm * (X vs Y), calculated from a set of marker options. * * @function Highcharts.Pathfinder#getAlgorithmStartDirection * * @param {Highcharts.ConnectorsMarkerOptions} markerOptions * Marker options to calculate from. * * @return {boolean} * Returns true for X, false for Y, and undefined for autocalculate. */ Pathfinder.prototype.getAlgorithmStartDirection = function (markerOptions) { var xCenter = markerOptions.align !== 'left' && markerOptions.align !== 'right', yCenter = markerOptions.verticalAlign !== 'top' && markerOptions.verticalAlign !== 'bottom', undef; return xCenter ? (yCenter ? undef : false) : // x is centered (yCenter ? true : undef); // x is off-center }; return Pathfinder; }()); Pathfinder.prototype.algorithms = pathfinderAlgorithms; // Add to Highcharts namespace H.Pathfinder = Pathfinder; // Add pathfinding capabilities to Points extend(Point.prototype, /** @lends Point.prototype */ { /** * Get coordinates of anchor point for pathfinder connection. * * @private * @function Highcharts.Point#getPathfinderAnchorPoint * * @param {Highcharts.ConnectorsMarkerOptions} markerOptions * Connection options for position on point. * * @return {Highcharts.PositionObject} * An object with x/y properties for the position. Coordinates are * in plot values, not relative to point. */ getPathfinderAnchorPoint: function (markerOptions) { var bb = getPointBB(this), x, y; switch (markerOptions.align) { // eslint-disable-line default-case case 'right': x = 'xMax'; break; case 'left': x = 'xMin'; } switch (markerOptions.verticalAlign) { // eslint-disable-line default-case case 'top': y = 'yMin'; break; case 'bottom': y = 'yMax'; } return { x: x ? bb[x] : (bb.xMin + bb.xMax) / 2, y: y ? bb[y] : (bb.yMin + bb.yMax) / 2 }; }, /** * Utility to get the angle from one point to another. * * @private * @function Highcharts.Point#getRadiansToVector * * @param {Highcharts.PositionObject} v1 * The first vector, as an object with x/y properties. * * @param {Highcharts.PositionObject} v2 * The second vector, as an object with x/y properties. * * @return {number} * The angle in degrees */ getRadiansToVector: function (v1, v2) { var box; if (!defined(v2)) { box = getPointBB(this); if (box) { v2 = { x: (box.xMin + box.xMax) / 2, y: (box.yMin + box.yMax) / 2 }; } } return Math.atan2(v2.y - v1.y, v1.x - v2.x); }, /** * Utility to get the position of the marker, based on the path angle and * the marker's radius. * * @private * @function Highcharts.Point#getMarkerVector * * @param {number} radians * The angle in radians from the point center to another vector. * * @param {number} markerRadius * The radius of the marker, to calculate the additional distance to * the center of the marker. * * @param {object} anchor * The anchor point of the path and marker as an object with x/y * properties. * * @return {object} * The marker vector as an object with x/y properties. */ getMarkerVector: function (radians, markerRadius, anchor) { var twoPI = Math.PI * 2.0, theta = radians, bb = getPointBB(this), rectWidth = bb.xMax - bb.xMin, rectHeight = bb.yMax - bb.yMin, rAtan = Math.atan2(rectHeight, rectWidth), tanTheta = 1, leftOrRightRegion = false, rectHalfWidth = rectWidth / 2.0, rectHalfHeight = rectHeight / 2.0, rectHorizontalCenter = bb.xMin + rectHalfWidth, rectVerticalCenter = bb.yMin + rectHalfHeight, edgePoint = { x: rectHorizontalCenter, y: rectVerticalCenter }, xFactor = 1, yFactor = 1; while (theta < -Math.PI) { theta += twoPI; } while (theta > Math.PI) { theta -= twoPI; } tanTheta = Math.tan(theta); if ((theta > -rAtan) && (theta <= rAtan)) { // Right side yFactor = -1; leftOrRightRegion = true; } else if (theta > rAtan && theta <= (Math.PI - rAtan)) { // Top side yFactor = -1; } else if (theta > (Math.PI - rAtan) || theta <= -(Math.PI - rAtan)) { // Left side xFactor = -1; leftOrRightRegion = true; } else { // Bottom side xFactor = -1; } // Correct the edgePoint according to the placement of the marker if (leftOrRightRegion) { edgePoint.x += xFactor * (rectHalfWidth); edgePoint.y += yFactor * (rectHalfWidth) * tanTheta; } else { edgePoint.x += xFactor * (rectHeight / (2.0 * tanTheta)); edgePoint.y += yFactor * (rectHalfHeight); } if (anchor.x !== rectHorizontalCenter) { edgePoint.x = anchor.x; } if (anchor.y !== rectVerticalCenter) { edgePoint.y = anchor.y; } return { x: edgePoint.x + (markerRadius * Math.cos(theta)), y: edgePoint.y - (markerRadius * Math.sin(theta)) }; } }); /** * Warn if using legacy options. Copy the options over. Note that this will * still break if using the legacy options in chart.update, addSeries etc. * @private */ function warnLegacy(chart) { if (chart.options.pathfinder || chart.series.reduce(function (acc, series) { if (series.options) { merge(true, (series.options.connectors = series.options.connectors || {}), series.options.pathfinder); } return acc || series.options && series.options.pathfinder; }, false)) { merge(true, (chart.options.connectors = chart.options.connectors || {}), chart.options.pathfinder); error('WARNING: Pathfinder options have been renamed. ' + 'Use "chart.connectors" or "series.connectors" instead.'); } } // Initialize Pathfinder for charts Chart.prototype.callbacks.push(function (chart) { var options = chart.options; if (options.connectors.enabled !== false) { warnLegacy(chart); this.pathfinder = new Pathfinder(this); this.pathfinder.update(true); // First draw, defer render } }); return Pathfinder; }); _registerModule(_modules, 'masters/modules/pathfinder.src.js', [], function () { }); }));
{ "content_hash": "b3cd521c1db0b181bde691a421d2bcfb", "timestamp": "", "source": "github", "line_count": 2720, "max_line_length": 355, "avg_line_length": 42.78345588235294, "alnum_prop": 0.4478263484888847, "repo_name": "cdnjs/cdnjs", "id": "3fe2a14e9af31dc95e35563a9a654ab9315f313a", "size": "116375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/highcharts/9.0.1/modules/pathfinder.src.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.zstack.storage.primary.nfs; import org.zstack.header.HasThreadContext; import org.zstack.header.core.validation.Validation; import org.zstack.kvm.KVMAgentCommands; import org.zstack.kvm.KVMAgentCommands.AgentCommand; import org.zstack.kvm.KVMAgentCommands.AgentResponse; import java.util.List; public class NfsPrimaryStorageKVMBackendCommands { public static class NfsPrimaryStorageAgentResponse extends AgentResponse { private Long totalCapacity; private Long availableCapacity; public Long getTotalCapacity() { return totalCapacity; } public void setTotalCapacity(Long totalCapacity) { this.totalCapacity = totalCapacity; } public Long getAvailableCapacity() { return availableCapacity; } public void setAvailableCapacity(Long availableCapacity) { this.availableCapacity = availableCapacity; } } public static class NfsPrimaryStorageAgentCommand extends KVMAgentCommands.PrimaryStorageCommand { private String uuid; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; this.primaryStorageUuid = uuid; } } public static class DownloadBitsFromKVMHostRsp extends AgentResponse { public String format; } public static class DownloadBitsFromKVMHostCmd extends AgentCommand { public String hostname; public String username; public String sshKey; public int sshPort; // it's file path on kvm host actually public String backupStorageInstallPath; public String primaryStorageInstallPath; public Long bandWidth; public String identificationCode; } public static class CancelDownloadBitsFromKVMHostCmd extends AgentCommand { public String primaryStorageInstallPath; } public static class GetDownloadBitsFromKVMHostProgressCmd extends AgentCommand { public List<String> volumePaths; } public static class GetDownloadBitsFromKVMHostProgressRsp extends AgentResponse { public long totalSize; } public static class MountCmd extends NfsPrimaryStorageAgentCommand { private String url; private String mountPath; private String options; public String getOptions() { return options; } public void setOptions(String options) { this.options = options; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMountPath() { return mountPath; } public void setMountPath(String mountPath) { this.mountPath = mountPath; } } public static class MountAgentResponse extends NfsPrimaryStorageAgentResponse { } public static class GetCapacityCmd extends NfsPrimaryStorageAgentCommand { private String mountPath; public String getMountPath() { return mountPath; } public void setMountPath(String mountPath) { this.mountPath = mountPath; } } public static class GetCapacityResponse extends NfsPrimaryStorageAgentResponse { } public static class UnmountCmd extends NfsPrimaryStorageAgentCommand { private String mountPath; private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMountPath() { return mountPath; } public void setMountPath(String mountPath) { this.mountPath = mountPath; } } public static class UnmountResponse extends NfsPrimaryStorageAgentResponse { } public static class CreateTemplateFromVolumeCmd extends NfsPrimaryStorageAgentCommand implements HasThreadContext{ private String installPath; private String rootVolumePath; public String getInstallPath() { return installPath; } public void setInstallPath(String installPath) { this.installPath = installPath; } public String getRootVolumePath() { return rootVolumePath; } public void setVolumePath(String rootVolumePath) { this.rootVolumePath = rootVolumePath; } } public static class CreateTemplateFromVolumeRsp extends NfsPrimaryStorageAgentResponse { private long size; private long actualSize; public long getActualSize() { return actualSize; } public void setActualSize(long actualSize) { this.actualSize = actualSize; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } } public static class DownloadBitsFromSftpBackupStorageCmd extends NfsPrimaryStorageAgentCommand { private String sshKey; private String hostname; private String username; private int sshPort; private String backupStorageInstallPath; private String primaryStorageInstallPath; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getSshPort() { return sshPort; } public void setSshPort(int sshPort) { this.sshPort = sshPort; } public String getSshKey() { return sshKey; } public void setSshKey(String sshKey) { this.sshKey = sshKey; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public String getBackupStorageInstallPath() { return backupStorageInstallPath; } public void setBackupStorageInstallPath(String backupStorageInstallPath) { this.backupStorageInstallPath = backupStorageInstallPath; } public String getPrimaryStorageInstallPath() { return primaryStorageInstallPath; } public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) { this.primaryStorageInstallPath = primaryStorageInstallPath; } } public static class DownloadBitsFromSftpBackupStorageResponse extends NfsPrimaryStorageAgentResponse { } public static class CheckIsBitsExistingCmd extends NfsPrimaryStorageAgentCommand { private String installPath; private String hostUuid; public String getHostUuid() { return hostUuid; } public void setHostUuid(String hostUuid) { this.hostUuid = hostUuid; } public String getInstallPath() { return installPath; } public void setInstallPath(String installPath) { this.installPath = installPath; } } public static class CheckIsBitsExistingRsp extends NfsPrimaryStorageAgentResponse { private boolean existing; public boolean isExisting() { return existing; } public void setExisting(boolean existing) { this.existing = existing; } } public static class CreateFolderCmd extends NfsPrimaryStorageAgentCommand { private String installUrl; public String getInstallUrl() { return installUrl; } public void setInstallUrl(String installUrl) { this.installUrl = installUrl; } } public abstract static class CreateVolumeCmd extends NfsPrimaryStorageAgentCommand { private String installUrl; private String accountUuid; private String hypervisorType; private String name; private String volumeUuid; public String getInstallUrl() { return installUrl; } public void setInstallUrl(String installUrl) { this.installUrl = installUrl; } public String getAccountUuid() { return accountUuid; } public void setAccountUuid(String accountUuid) { this.accountUuid = accountUuid; } public String getHypervisorType() { return hypervisorType; } public void setHypervisorType(String hypervisorType) { this.hypervisorType = hypervisorType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVolumeUuid() { return volumeUuid; } public void setVolumeUuid(String uuid) { this.volumeUuid = uuid; } } public static class CreateRootVolumeFromTemplateCmd extends CreateVolumeCmd { private String templatePathInCache; private long timeout; public long getTimeout() { return timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } public String getTemplatePathInCache() { return templatePathInCache; } public void setTemplatePathInCache(String templatePathInCache) { this.templatePathInCache = templatePathInCache; } } public static class CreateRootVolumeFromTemplateResponse extends NfsPrimaryStorageAgentResponse { } public static class CreateVolumeWithBackingCmd extends CreateVolumeCmd { private String templatePathInCache; public String getTemplatePathInCache() { return templatePathInCache; } public void setTemplatePathInCache(String templatePathInCache) { this.templatePathInCache = templatePathInCache; } } public static class CreateVolumeWithBackingRsp extends NfsPrimaryStorageAgentResponse { private long size; private long actualSize; public long getActualSize() { return actualSize; } public void setActualSize(long actualSize) { this.actualSize = actualSize; } public long getSize() { return size; } } public static class CreateEmptyVolumeCmd extends CreateVolumeCmd { private long size; private boolean withoutVolume; public long getSize() { return size; } public void setSize(long size) { this.size = size; } public boolean isWithoutVolume() { return withoutVolume; } public void setWithoutVolume(boolean withoutVolume) { this.withoutVolume = withoutVolume; } } public static class CreateEmptyVolumeResponse extends NfsPrimaryStorageAgentResponse { } public static class DeleteCmd extends NfsPrimaryStorageAgentCommand { private boolean folder; private String installPath; public boolean isFolder() { return folder; } public void setFolder(boolean isFolder) { this.folder = isFolder; } public String getInstallPath() { return installPath; } public void setInstallPath(String installPath) { this.installPath = installPath; } } public static class DeleteResponse extends NfsPrimaryStorageAgentResponse { } public static class ListDirectionCmd extends NfsPrimaryStorageAgentCommand { private String path; public String getPath() { return path; } public void setPath(String path) { this.path = path; } } public static class ListDirectionResponse extends NfsPrimaryStorageAgentResponse { private List<String> paths; public List<String> getPaths() { return paths; } public void setPaths(List<String> paths) { this.paths = paths; } } public static class RevertVolumeFromSnapshotCmd extends NfsPrimaryStorageAgentCommand { private String snapshotInstallPath; public String getSnapshotInstallPath() { return snapshotInstallPath; } public void setSnapshotInstallPath(String snapshotInstallPath) { this.snapshotInstallPath = snapshotInstallPath; } } public static class RevertVolumeFromSnapshotResponse extends NfsPrimaryStorageAgentResponse { @Validation private String newVolumeInstallPath; @Validation private long size; public String getNewVolumeInstallPath() { return newVolumeInstallPath; } public void setNewVolumeInstallPath(String newVolumeInstallPath) { this.newVolumeInstallPath = newVolumeInstallPath; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } } public static class ReInitImageCmd extends NfsPrimaryStorageAgentCommand { private String imagePath; private String volumePath; public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public String getVolumePath() { return volumePath; } public void setVolumePath(String volumePath) { this.volumePath = volumePath; } } public static class ReInitImageRsp extends NfsPrimaryStorageAgentResponse { @Validation private String newVolumeInstallPath; public String getNewVolumeInstallPath() { return newVolumeInstallPath; } public void setNewVolumeInstallPath(String newVolumeInstallPath) { this.newVolumeInstallPath = newVolumeInstallPath; } } public static class UploadToSftpCmd extends NfsPrimaryStorageAgentCommand implements HasThreadContext{ private String primaryStorageInstallPath; private String backupStorageInstallPath; private String backupStorageHostName; private String backupStorageUserName; private String backupStorageSshKey; private int backupStorageSshPort; public String getBackupStorageUserName() { return backupStorageUserName; } public void setBackupStorageUserName(String backupStorageUserName) { this.backupStorageUserName = backupStorageUserName; } public void setBackupStorageSshPort(int backupStorageSshPort) { this.backupStorageSshPort = backupStorageSshPort; } public int getBackupStorageSshPort() { return backupStorageSshPort; } public String getPrimaryStorageInstallPath() { return primaryStorageInstallPath; } public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) { this.primaryStorageInstallPath = primaryStorageInstallPath; } public String getBackupStorageInstallPath() { return backupStorageInstallPath; } public void setBackupStorageInstallPath(String backupStorageInstallPath) { this.backupStorageInstallPath = backupStorageInstallPath; } public String getBackupStorageHostName() { return backupStorageHostName; } public void setBackupStorageHostName(String backupStorageHostName) { this.backupStorageHostName = backupStorageHostName; } public String getBackupStorageSshKey() { return backupStorageSshKey; } public void setBackupStorageSshKey(String backupStorageSshKey) { this.backupStorageSshKey = backupStorageSshKey; } } public static class UploadToSftpResponse extends NfsPrimaryStorageAgentResponse { } public static class MergeSnapshotCmd extends NfsPrimaryStorageAgentCommand { private String volumeUuid; private String snapshotInstallPath; private String workspaceInstallPath; public String getVolumeUuid() { return volumeUuid; } public void setVolumeUuid(String volumeUuid) { this.volumeUuid = volumeUuid; } public String getSnapshotInstallPath() { return snapshotInstallPath; } public void setSnapshotInstallPath(String snapshotInstallPath) { this.snapshotInstallPath = snapshotInstallPath; } public String getWorkspaceInstallPath() { return workspaceInstallPath; } public void setWorkspaceInstallPath(String workspaceInstallPath) { this.workspaceInstallPath = workspaceInstallPath; } } public static class MergeSnapshotResponse extends NfsPrimaryStorageAgentResponse { private long size; private long actualSize; public long getActualSize() { return actualSize; } public void setActualSize(long actualSize) { this.actualSize = actualSize; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } } public static class RebaseAndMergeSnapshotsCmd extends NfsPrimaryStorageAgentCommand { private String volumeUuid; private List<String> snapshotInstallPaths; private String workspaceInstallPath; public String getVolumeUuid() { return volumeUuid; } public void setVolumeUuid(String volumeUuid) { this.volumeUuid = volumeUuid; } public List<String> getSnapshotInstallPaths() { return snapshotInstallPaths; } public void setSnapshotInstallPaths(List<String> snapshotInstallPaths) { this.snapshotInstallPaths = snapshotInstallPaths; } public String getWorkspaceInstallPath() { return workspaceInstallPath; } public void setWorkspaceInstallPath(String workspaceInstallPath) { this.workspaceInstallPath = workspaceInstallPath; } } public static class RebaseAndMergeSnapshotsResponse extends NfsPrimaryStorageAgentResponse { private long size; private long actualSize; public long getActualSize() { return actualSize; } public void setActualSize(long actualSize) { this.actualSize = actualSize; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } } public static class MoveBitsCmd extends NfsPrimaryStorageAgentCommand { private String srcPath; private String destPath; public String getSrcPath() { return srcPath; } public void setSrcPath(String srcPath) { this.srcPath = srcPath; } public String getDestPath() { return destPath; } public void setDestPath(String destPath) { this.destPath = destPath; } } public static class MoveBitsRsp extends NfsPrimaryStorageAgentResponse { } public static class OfflineMergeSnapshotCmd extends NfsPrimaryStorageAgentCommand implements HasThreadContext { private String srcPath; private String destPath; private boolean fullRebase; public boolean isFullRebase() { return fullRebase; } public void setFullRebase(boolean fullRebase) { this.fullRebase = fullRebase; } public String getSrcPath() { return srcPath; } public void setSrcPath(String srcPath) { this.srcPath = srcPath; } public String getDestPath() { return destPath; } public void setDestPath(String destPath) { this.destPath = destPath; } } public static class OfflineMergeSnapshotRsp extends NfsPrimaryStorageAgentResponse { } public static class RemountCmd extends NfsPrimaryStorageAgentCommand { public String url; public String mountPath; public String options; } public static class GetVolumeActualSizeCmd extends NfsPrimaryStorageAgentCommand { public String volumeUuid; public String installPath; } public static class GetVolumeActualSizeRsp extends NfsPrimaryStorageAgentResponse { public long actualSize; public long size; } public static class PingCmd extends NfsPrimaryStorageAgentCommand { public String mountPath; public String url; } /** * volumeInstallDir contains all snapshots and base volume file, * their backing file in imageCacheDir will be identified as the base image. * This takes into consideration multiple snapshot chains and chain-based image. */ public static class GetVolumeBaseImagePathCmd extends NfsPrimaryStorageAgentCommand { public String volumeUuid; public String volumeInstallDir; public String imageCacheDir; } public static class GetVolumeBaseImagePathRsp extends NfsPrimaryStorageAgentResponse { public String path; } public static class UpdateMountPointCmd extends NfsPrimaryStorageAgentCommand { public String oldMountPoint; public String newMountPoint; public String mountPath; public String options; } public static class UpdateMountPointRsp extends NfsPrimaryStorageAgentResponse { } public static class NfsToNfsMigrateBitsCmd extends NfsPrimaryStorageAgentCommand implements HasThreadContext { public String srcFolderPath; public String dstFolderPath; public List<String> filtPaths; public boolean isMounted = false; public String url; public String options; public String mountPath; } public static class NfsToNfsMigrateBitsRsp extends NfsPrimaryStorageAgentResponse { } public static class NfsRebaseVolumeBackingFileCmd extends NfsPrimaryStorageAgentCommand { public String srcPsMountPath; public String dstPsMountPath; public String dstVolumeFolderPath; public String dstImageCacheTemplateFolderPath; } public static class NfsRebaseVolumeBackingFileRsp extends NfsPrimaryStorageAgentResponse { } public static class LinkVolumeNewDirCmd extends NfsPrimaryStorageAgentCommand { public String volumeUuid; public String srcDir; public String dstDir; } public static class LinkVolumeNewDirRsp extends NfsPrimaryStorageAgentResponse { } }
{ "content_hash": "72a41f47458991fc8bfe15a459e23cb0", "timestamp": "", "source": "github", "line_count": 804, "max_line_length": 118, "avg_line_length": 28.90547263681592, "alnum_prop": 0.64315834767642, "repo_name": "zstackorg/zstack", "id": "5ef2c8103f9684a8e8484637c90392d8a8b06db2", "size": "23240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugin/nfsPrimaryStorage/src/main/java/org/zstack/storage/primary/nfs/NfsPrimaryStorageKVMBackendCommands.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "54952" }, { "name": "Batchfile", "bytes": "1132" }, { "name": "Groovy", "bytes": "832169" }, { "name": "Java", "bytes": "15798995" }, { "name": "Shell", "bytes": "152829" } ], "symlink_target": "" }
<application> <component name="Git.Application.Settings"> <option name="myPathToGit" value="C:\Program Files\Git\cmd\git.exe" /> </component> </application>
{ "content_hash": "bfcd9f27960d0bda5d01629b6f87d746", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 74, "avg_line_length": 32.8, "alnum_prop": 0.7134146341463414, "repo_name": "SenorSid/SensorDataVisualizer", "id": "c4ae9e38b7d77c5fbb7504dc71389a4871d0387e", "size": "164", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_windows/git.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "12709" } ], "symlink_target": "" }
<component name="libraryTable"> <library name="gitstats node_modules" type="javaScript"> <properties> <option name="frameworkName" value="node_modules" /> <sourceFilesUrls> <item url="file://$PROJECT_DIR$/node_modules" /> </sourceFilesUrls> </properties> <CLASSES> <root url="file://$PROJECT_DIR$/node_modules" /> </CLASSES> <SOURCES /> </library> </component>
{ "content_hash": "bee44df9022b7db49a10b8855bfd5a24", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 29.714285714285715, "alnum_prop": 0.6225961538461539, "repo_name": "jbetancur/gitstats", "id": "7d384d956b64e22569db8d74927a5c8e9d3c40e1", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/libraries/gitstats_node_modules.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "131" }, { "name": "JavaScript", "bytes": "6303838" }, { "name": "TypeScript", "bytes": "385" } ], "symlink_target": "" }
#define USE_LEGACY_OPENGL 1 #define USE_FPL_OPENGL_CONTEXT_CREATION 1 #define FPL_IMPLEMENTATION #if !USE_FPL_OPENGL_CONTEXT_CREATION # define FPL_NO_VIDEO_OPENGL #endif #include <final_platform_layer.h> #define FGL_IMPLEMENTATION #define FGL_AS_PRIVATE #include <final_dynamic_opengl.h> static GLuint CreateShaderType(GLenum type, const char *source) { GLuint shaderId = glCreateShader(type); glShaderSource(shaderId, 1, &source, fgl_null); glCompileShader(shaderId); GLint compileResult; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compileResult); if(!compileResult) { GLint infoLen; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLen); char *info = (char *)fplStackAllocate(infoLen); glGetShaderInfoLog(shaderId, infoLen, &infoLen, info); fplConsoleFormatError("Failed compiling %s shader!\n", (type == GL_VERTEX_SHADER ? "vertex" : "fragment")); fplConsoleFormatError("%s\n", info); } return(shaderId); } static GLuint CreateShaderProgram(const char *name, const char *vertexSource, const char *fragmentSource) { GLuint programId = glCreateProgram(); GLuint vertexShader = CreateShaderType(GL_VERTEX_SHADER, vertexSource); GLuint fragmentShader = CreateShaderType(GL_FRAGMENT_SHADER, fragmentSource); glAttachShader(programId, vertexShader); glAttachShader(programId, fragmentShader); glLinkProgram(programId); glValidateProgram(programId); GLint linkResult; glGetProgramiv(programId, GL_LINK_STATUS, &linkResult); if(!linkResult) { GLint infoLen; glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLen); char *info = (char *)fplStackAllocate(infoLen); glGetProgramInfoLog(programId, infoLen, &infoLen, info); fplConsoleFormatError("Failed linking '%s' shader!\n", name); fplConsoleFormatError("%s\n", info); } glDeleteShader(fragmentShader); glDeleteShader(vertexShader); return(programId); } static void RunModern(const fglOpenGLContext *context) { const char *version = (const char *)glGetString(GL_VERSION); const char *vendor = (const char *)glGetString(GL_VENDOR); const char *renderer = (const char *)glGetString(GL_RENDERER); fplConsoleFormatOut("OpenGL version: %s\n", version); fplConsoleFormatOut("OpenGL vendor: %s\n", vendor); fplConsoleFormatOut("OpenGL renderer: %s\n", renderer); GLuint vertexArrayID; glGenVertexArrays(1, &vertexArrayID); glBindVertexArray(vertexArrayID); const char *glslVersion = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION); fplConsoleFormatOut("OpenGL GLSL Version %s:\n", glslVersion); int profileMask; int contextFlags; glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &profileMask); glGetIntegerv(GL_CONTEXT_FLAGS, &contextFlags); fplConsoleFormatOut("OpenGL supported profiles:\n"); fplConsoleFormatOut("\tCore: %s\n", ((profileMask & GL_CONTEXT_CORE_PROFILE_BIT) ? "yes" : "no")); fplConsoleFormatOut("\tForward: %s\n", ((contextFlags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) ? "yes" : "no")); fplConsoleOut("Running modern opengl\n"); const char vertexSource[] = { "#version 330 core\n" "\n" "layout(location = 0) in vec4 inPosition;\n" "\n" "void main() {\n" "\tgl_Position = inPosition;\n" "}\n" }; const char fragmentSource[] = { "#version 330 core\n" "\n" "layout(location = 0) out vec4 outColor;\n" "\n" "void main() {\n" "\toutColor = vec4(1.0, 0.0, 0.0, 1.0);\n" "}\n" }; GLuint shaderProgram = CreateShaderProgram("Test", vertexSource, fragmentSource); float vertices[] = { 0.0f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f }; GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glUseProgram(shaderProgram); glBindBuffer(GL_ARRAY_BUFFER, buffer); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, fgl_null); glClearColor(0.39f, 0.58f, 0.93f, 1.0f); while(fplWindowUpdate()) { fplEvent ev; while(fplPollEvent(&ev)) {} fplWindowSize windowArea; fplGetWindowSize(&windowArea); glViewport(0, 0, windowArea.width, windowArea.height); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 3); #if USE_FPL_OPENGL_CONTEXT_CREATION fplVideoFlip(); #else fglPresentOpenGL(context); #endif } glDisableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glDeleteVertexArrays(1, &vertexArrayID); } int main(int argc, char **args) { int result = 0; fplSettings settings; fplSetDefaultSettings(&settings); fplInitFlags initFlags; #if USE_FPL_OPENGL_CONTEXT_CREATION initFlags = fplInitFlags_Video; settings.video.driver = fplVideoDriverType_OpenGL; # if !USE_LEGACY_OPENGL fplCopyString("FPL Modern OpenGL", settings.window.title, fplArrayCount(settings.window.title)); settings.video.graphics.opengl.compabilityFlags = fplOpenGLCompabilityFlags_Core; settings.video.graphics.opengl.majorVersion = 3; settings.video.graphics.opengl.minorVersion = 3; # else fplCopyString("FPL Legacy OpenGL", settings.window.title, fplArrayCount(settings.window.title)); settings.video.graphics.opengl.compabilityFlags = fplOpenGLCompabilityFlags_Legacy; # endif #else initFlags = fplInitFlags_Window; #endif // USE_FPL_OPENGL_CONTEXT_CREATION if(fplPlatformInit(initFlags, &settings)) { #if USE_FPL_OPENGL_CONTEXT_CREATION if(fglLoadOpenGL(true)) { RunModern(fgl_null); fglUnloadOpenGL(); } #else fglOpenGLContextCreationParameters contextCreationParams = { 0 }; # if !USE_LEGACY_OPENGL fplCopyAnsiString("DYNGL Modern OpenGL", settings.window.windowTitle, fplArrayCount(settings.window.windowTitle)); contextCreationParams.profile = fglOpenGLProfileType_CoreProfile; contextCreationParams.majorVersion = 3; contextCreationParams.minorVersion = 3; # else fplCopyAnsiString("DYNGL Legacy OpenGL", settings.window.windowTitle, fplArrayCount(settings.window.windowTitle)); contextCreationParams.profile = fdyngl::OpenGLProfileType::LegacyProfile; # endif # if defined(FGL_PLATFORM_WIN32) contextCreationParams.windowHandle.win32.deviceContext = fpl__global__AppState->window.win32.deviceContext; # endif fglOpenGLContext glContext = { 0 }; if(fglLoadOpenGL(false)) { if(fglCreateOpenGLContext(&contextCreationParams, &glContext)) { fglLoadOpenGLFunctions(); RunModern(&glContext); fglDestroyOpenGLContext(&glContext); } fglUnloadOpenGL(); } #endif // USE_FPL_OPENGL_CONTEXT_CREATION fplPlatformRelease(); result = 0; } else { result = -1; } return(result); }
{ "content_hash": "beb6d86381e8433ba3e4731bc940d61a", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 116, "avg_line_length": 30.13364055299539, "alnum_prop": 0.746138553295611, "repo_name": "f1nalspace/final_game_tech", "id": "537ca29566db82a14155deaf7b191a0d67af5c59", "size": "7384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demos/FOGL_Test/fogl_test.c", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "202" }, { "name": "C", "bytes": "2724436" }, { "name": "C#", "bytes": "30177" }, { "name": "C++", "bytes": "56221" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../spec_helper' describe WebserviceTags do before do @page = Page.create!( :title => 'New Page', :slug => 'page', :breadcrumb => 'New Page', :status_id => '100' ) success_remote_expectations end it "should get remote data from webservice by <r:webservice />" do Webservice.create!(:title => "Geocoder", :base_url => 'http://maps.google.com/maps/geo', :rule_scheme => "q: boguchany\noutput: xml\nkey: abcdefg" ) @page.should render("<r:webservice name='Geocoder'>Geo</r:webservice>").as('Geo') end it "should show remote data from webservice by <r:value-of />" do Webservice.create!(:title => "Geocoder", :base_url => 'http://maps.google.com/maps/geo', :rule_scheme => "q: boguchany\noutput: xml\nkey: abcdefg" ) @page.should render( "<r:webservice name='Geocoder'><r:webservice:content select='.//xmlns:coordinates' /></r:webservice>" ).as('97.4598388,58.3798219,0') end it "should show nothing if webservice:content is not inside webservice" do Webservice.create!(:title => "Geocoder", :base_url => 'http://maps.google.com/maps/geo', :rule_scheme => "q: boguchany\noutput: xml\nkey: abcdefg" ) @page.should render( "<r:webservice name='Geocoder'></r:webservice><r:webservice:content select='.//xmlns:coordinates' />" ).as('') end it "should get remote data with tag's attributes" do Webservice.create!( :title => "Geocoder", :base_url => 'http://maps.google.com/maps/geo', :rule_scheme => "q: boguchany\noutput: xml\nkey: abcdefg" ) @page.should render( "<r:webservice name='Geocoder' q='boguchany' output='xml'>" + "<r:webservice:content select='.//xmlns:coordinates' />" + "</r:webservice>" ).as('97.4598388,58.3798219,0') end if Object.const_defined?("RouteHandlerExtension") it "should get remote date with attributes from route_handler_params" do Webservice.create!( :title => "Geocoder", :base_url => 'http://maps.google.com/maps/geo', :rule_scheme => "q: boguchany\noutput: xml\nkey: abcdefg" ) @page.route_handler_params = { :q => 'boguchany', :output => 'xml', :something => 'some' } @page.should render( "<r:webservice name='Geocoder'>" + "<r:webservice:content select='.//xmlns:coordinates' />" + "</r:webservice>" ).as('97.4598388,58.3798219,0') end end end
{ "content_hash": "bdf3aef6a391e42229976ad8d4906c6a", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 107, "avg_line_length": 36.36231884057971, "alnum_prop": 0.612196094061379, "repo_name": "astashov/radiant-webservices-extension", "id": "8c55306c4082baa9d6498d72ef7595ff729585f1", "size": "2509", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/models/webservice_tags_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "21221" } ], "symlink_target": "" }
import React, { Component } from 'react'; /** * The number of dots to display in AudioLevelIndicator. * * IMPORTANT: AudioLevelIndicator assumes that this is an odd number. */ const AUDIO_LEVEL_DOTS = 5; /** * The index of the dot that is at the direct middle of all other dots. */ const CENTER_DOT_INDEX = Math.floor(AUDIO_LEVEL_DOTS / 2); /** * Creates a ReactElement responsible for drawing audio levels. * * @extends {Component} */ class AudioLevelIndicator extends Component { /** * {@code AudioLevelIndicator}'s property types. * * @static */ static propTypes = { /** * The current audio level to display. The value should be a number * between 0 and 1. * * @type {number} */ audioLevel: React.PropTypes.number }; /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { // First make sure we are sensitive enough. const audioLevel = Math.min(this.props.audioLevel * 1.2, 1); // Let's now stretch the audio level over the number of dots we have. const stretchedAudioLevel = AUDIO_LEVEL_DOTS * audioLevel; const audioLevelDots = []; for (let i = 0; i < AUDIO_LEVEL_DOTS; i++) { const distanceFromCenter = CENTER_DOT_INDEX - i; const audioLevelFromCenter = stretchedAudioLevel - Math.abs(distanceFromCenter); const cappedOpacity = Math.min( 1, Math.max(0, audioLevelFromCenter)); let className; if (distanceFromCenter === 0) { className = 'audiodot-middle'; } else if (distanceFromCenter < 0) { className = 'audiodot-top'; } else { className = 'audiodot-bottom'; } audioLevelDots.push( <span className = { className } key = { i } style = {{ opacity: cappedOpacity }} /> ); } return ( <span className = 'audioindicator in-react'> { audioLevelDots } </span> ); } } export default AudioLevelIndicator;
{ "content_hash": "89f4b2d8d14a962c5e701096bb764769", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 77, "avg_line_length": 27.63855421686747, "alnum_prop": 0.5466434176111595, "repo_name": "KalinduDN/kalindudn.github.io", "id": "629e0b1061ce2152982ab23e9cbfc9ed1e7d94c4", "size": "2294", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "react/features/audio-level-indicator/components/AudioLevelIndicator.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "143673" }, { "name": "HTML", "bytes": "5468" }, { "name": "Java", "bytes": "53960" }, { "name": "JavaScript", "bytes": "1498014" }, { "name": "Lua", "bytes": "44736" }, { "name": "Makefile", "bytes": "1694" }, { "name": "Objective-C", "bytes": "35244" }, { "name": "Python", "bytes": "138" }, { "name": "Ruby", "bytes": "925" }, { "name": "Shell", "bytes": "6607" } ], "symlink_target": "" }
package edu.nie.asynctaskandnetwork; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.http.GET; import retrofit2.http.Url; public class ServerActivity extends AppCompatActivity { private Server server; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setup(); setContentView(R.layout.activity_server); // create a variable named `get` which is of type View. Assign // the value of `get` to whatever is returned by the method `findViewById`. // // Just like // int i = someMethod(); // in C++ View get = findViewById(R.id.get); // `get` which is a `View` has a method `setOnClickListener` // like public methods in C++/JAVA classes. This method takes in // 1 argument, an object of type `View.OnClickListener`. So whenever // the `get` view is clicked by the user, The Android OS will call // the `onClick` method of this object. // It is a callback, take whatever action you want inside the `onClick` // method. get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View button) { // First find the input edit text view and get the text set on it. String url = ((EditText) findViewById(R.id.input)).getText().toString(); // break up of the above statement // View temp1 = ((EditText) findViewById(R.id.input)) -> get a view // Editable temp2 = temp1.getText() -> returns a type(class) Editable // String url = temp2.toString() -> return the text inside the Editable object // check if the user has entered something // by simply checking if the length of the // text is zero or not if (url.length() == 0) { // if zero, show a toast to user Toast.makeText(button.getContext(), "Enter a url", Toast.LENGTH_SHORT).show(); // and return without doing anything return; } // Now find the output text view where // you will dump the data from the server TextView outputTextView = (TextView) findViewById(R.id.output); // while the data is being loaded // set it's text to `Loading..` outputTextView.setText("Loading..."); // Also disable the button that was clicked so that the user // can press it again and again before we are done button.setEnabled(false); // Now call the getDataFromUrl method // we are passing the url the user entered // the output text view where we will dump the result // the button, so that we can enabled it back after we are done getDataFromUrl(url, outputTextView, button); } }); } private void getDataFromUrl(String url, final TextView outputView, final View button) { // create a new async task // the 1st type here is `String` which is like the input type // the 2nd type is Void, just ignore it for now // the 3rd type is String, which is like the result type. new AsyncTask<String, Void, String>() { // This is the actual stuff that is running in the // background. Please do not modify any views here // if you do that, the app will crash. @Override protected String doInBackground(String... url) { try { // ignore this // url is an array of Strings // the input type (1st argument) // which you passed int the execute method // this method makes the call // and get the data as a string // and then returns it return getFromServer(url[0]); } catch (IOException e) { // ignore this e.printStackTrace(); // ignore this } // if something went wrong just return null or nothing. return null; } // This method is call after the `doInBackground` is done // This is called on the main thread. So you can modify the views here @Override protected void onPostExecute(String result) { super.onPostExecute(result); // remember if we returned null, means something went wrong // so let's do tell that to the user if (result == null) { result = "some error occurred !"; } // now enable the button again // you users can use it again button.setEnabled(true); // Now set the result you got from the // server to the output text view. outputView.setText(result); } }.execute(url); // actually starts the task you defined above. } /** * SETUP CODE RELATED TO NETWORK COMMUNICATION */ private String getFromServer(String url) throws IOException { return server.get(url).execute().body().string(); } public interface Server { @GET Call<ResponseBody> get(@Url String url); } private void setup() { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://10.0.2.2:8080/") .build(); server = retrofit.create(Server.class); } }
{ "content_hash": "842d503227cbde334c4e3ed787174953", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 98, "avg_line_length": 37.72049689440994, "alnum_prop": 0.5647949942367858, "repo_name": "adityasharat/nie-android-workshop-apr-17", "id": "4ca98d74746ab6ced0f84b48ed783bda1342fcfb", "size": "6073", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "6. AsyncTask And Network/src/main/java/edu/nie/asynctaskandnetwork/ServerActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "81642" } ], "symlink_target": "" }
<?php namespace osCommerce\OM\Core\Site\Admin\Application\Dashboard\SQL\ANSI; use osCommerce\OM\Core\Registry; /** * @since v3.0.3 */ class SaveShortcut { public static function execute($data) { $OSCOM_PDO = Registry::get('PDO'); $Qsc = $OSCOM_PDO->prepare('insert into :table_administrator_shortcuts (administrators_id, module, last_viewed) values (:administrators_id, :module, null)'); $Qsc->bindInt(':administrators_id', $data['admin_id']); $Qsc->bindValue(':module', $data['application']); $Qsc->execute(); return ( ($Qsc->rowCount() === 1) || !$Qsc->isError() ); } } ?>
{ "content_hash": "74905c8942586c48b0ce6c5360b6acaa", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 163, "avg_line_length": 26.5, "alnum_prop": 0.6242138364779874, "repo_name": "haraldpdl/oscommerce", "id": "42f581116a449610c485088b6015a301a107832a", "size": "814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "osCommerce/OM/Core/Site/Admin/Application/Dashboard/SQL/ANSI/SaveShortcut.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "23470" }, { "name": "JavaScript", "bytes": "83142" }, { "name": "PHP", "bytes": "2202823" } ], "symlink_target": "" }
require 'ruby-swagger/data/operation' require 'ruby-swagger/grape/type' require 'ruby-swagger/grape/route_settings' module Swagger::Grape class Method attr_reader :operation, :types, :scopes def initialize(route_name, route) @route_settings = Swagger::Grape::RouteSettings.new(route) @route_name = route_name @route = route @types = [] @scopes = [] new_operation operation_params operation_responses operation_security self end private # generate the base of the operation def new_operation @operation = Swagger::Data::Operation.new @operation.tags = grape_tags @operation.operationId = @route_settings.api_name if @route_settings.api_name && !@route_settings.api_name.empty? @operation.summary = @route_settings.description @operation.description = (@route_settings.detail && !@route_settings.detail.empty?) ? @route_settings.detail : @route_settings.description @operation.deprecated = @route_settings.deprecated if @route_settings.deprecated # grape extension @operation end # extract all the parameters from the method definition (in path, url, body) def operation_params extract_params_and_types @params.each do |_param_name, parameter| operation.add_parameter(parameter) end end # extract the data about the response of the method def operation_responses @operation.responses = Swagger::Data::Responses.new # Include all the possible errors in the response (store the types, they are documented separately) (@route_settings.errors || {}).each do |code, response| error_response = { 'description' => response['description'] || response[:description] } if (entity = (response[:entity] || response['entity'])) type = Object.const_get entity.to_s error_response['schema'] = {} error_response['schema']['$ref'] = "#/definitions/#{type}" remember_type(type) end @operation.responses.add_response(code, Swagger::Data::Response.parse(error_response)) end if @route_settings.response.present? && @route_settings.response[:entity].present? rainbow_response = { 'description' => 'Successful result of the operation' } type = Swagger::Grape::Type.new(@route_settings.response[:entity].to_s) rainbow_response['schema'] = {} remember_type(@route_settings.response[:entity]) # Include any response headers in the documentation of the response if @route_settings.response[:headers].present? @route_settings.response[:headers].each do |header_key, header_value| next unless header_value.present? rainbow_response['headers'] ||= {} rainbow_response['headers'][header_key] = { 'description' => header_value['description'] || header_value[:description], 'type' => header_value['type'] || header_value[:type], 'format' => header_value['format'] || header_value[:format] } end end # rubocop:disable IfInsideElse if @route_settings.response[:root].present? # A case where the response contains a single key in the response if @route_settings.response[:isArray] == true # an array that starts from a key named root rainbow_response['schema']['type'] = 'object' rainbow_response['schema']['properties'] = { @route_settings.response[:root] => { 'type' => 'array', 'items' => type.to_swagger } } else rainbow_response['schema']['type'] = 'object' rainbow_response['schema']['properties'] = { @route_settings.response[:root] => type.to_swagger } end else if @route_settings.response[:isArray] == true rainbow_response['schema']['type'] = 'array' rainbow_response['schema']['items'] = type.to_swagger else rainbow_response['schema'] = type.to_swagger end end # rubocop:enable IfInsideElse @operation.responses.add_response('200', Swagger::Data::Response.parse(rainbow_response)) end @operation.responses.add_response('default', Swagger::Data::Response.parse({ 'description' => 'Unexpected error' })) end def operation_security if @route_settings.scopes # grape extensions security = Swagger::Data::SecurityRequirement.new security.add_requirement('oauth2', @route_settings.scopes) @operation.security = [security] @route_settings.scopes.each do |scope| @scopes << scope unless @scopes.include?(scope) end end end # extract the tags def grape_tags (@route_settings.tags && !@route_settings.tags.empty?) ? @route_settings.tags : [@route_name.split('/')[1]] end def extract_params_and_types @params = {} header_params path_params case @route_settings.method.downcase when 'get' query_params when 'delete' query_params when 'post' body_params when 'put' body_params when 'patch' body_params when 'head' raise ArgumentError.new("Don't know how to handle the http verb HEAD for #{@route_name}") else raise ArgumentError.new("Don't know how to handle the http verb #{@route_settings.method} for #{@route_name}") end @params end def header_params @params ||= {} # include all the parameters that are in the headers if @route_settings.headers @route_settings.headers.each do |header_key, header_value| @params[header_key] = { 'name' => header_key, 'in' => 'header', 'required' => (header_value[:required] == true), 'type' => 'string', 'description' => header_value[:description] } end end @params end def path_params # include all the parameters that are in the path @route_name.scan(/\{[a-zA-Z0-9\-\_]+\}/).each do |parameter| # scan all parameters in the url param_name = parameter[1..parameter.length - 2] @params[param_name] = { 'name' => param_name, 'in' => 'path', 'required' => true, 'type' => 'string' } end end def query_params @route_settings.params.each do |parameter| next if @params[parameter.first.to_s] swag_param = Swagger::Data::Parameter.from_grape(parameter) next unless swag_param swag_param.in = 'query' @params[parameter.first.to_s] = swag_param end end def body_params # include all the parameters that are in the content-body return unless @route_settings.params && !@route_settings.params.empty? body_name = @operation.operationId ? "#{@operation.operationId}_body" : 'body' root_param = Swagger::Data::Parameter.parse({ 'name' => body_name, 'in' => 'body', 'description' => 'the content of the request', 'schema' => { 'type' => 'object', 'properties' => {} } }) # create the params schema @route_settings.params.each do |parameter| param_name = parameter.first param_value = parameter.last schema = root_param.schema next if @params.keys.include?(param_name) if param_name.scan(/[0-9a-zA-Z_]+/).count == 1 # it's a simple parameter, adding it to the properties of the main object converted_param = Swagger::Grape::Param.new(param_value) schema.properties[param_name] = converted_param.to_swagger_without_required required_parameter(schema, param_name, param_value) documented_paramter(schema, param_name, param_value) remember_type(converted_param.type_definition) if converted_param.has_type_definition? else schema_with_subobjects(schema, param_name, parameter.last) end end schema = root_param.schema @params['body'] = root_param if !schema.properties.nil? && !schema.properties.keys.empty? end # Can potentionelly be used for per-param documentation, for now used for example values def documented_paramter(schema, target, parameter) return if parameter.nil? || parameter[:documentation].nil? unless parameter[:documentation][:example].nil? schema['example'] ||= {} if target.is_a? Array nesting = target[0] target = target[1] schema['example'][nesting] ||= {} schema['example'][nesting][target] = parameter[:documentation][:example] else schema['example'][target] = parameter[:documentation][:example] end end end def required_parameter(schema, name, parameter) return if parameter.nil? || parameter[:required].nil? || parameter[:required] == false schema['required'] = [] unless schema['required'].is_a?(Array) schema['required'] << name end def schema_with_subobjects(schema, param_name, parameter) path = param_name.scan(/[0-9a-zA-Z_]+/) append_to = find_elem_in_schema(schema, path.dup) converted_param = Swagger::Grape::Param.new(parameter) append_to['properties'][path.last] = converted_param.to_swagger_without_required remember_type(converted_param.type_definition) if converted_param.has_type_definition? required_parameter(append_to, path.last, parameter) documented_paramter(schema, path, parameter) end def find_elem_in_schema(root, schema_path) return root if schema_path.nil? || schema_path.empty? next_elem = schema_path.shift return root if root['properties'][next_elem].nil? case root['properties'][next_elem]['type'] when 'array' # to descend an array this must be an array of objects root['properties'][next_elem]['items']['type'] = 'object' root['properties'][next_elem]['items']['properties'] ||= {} find_elem_in_schema(root['properties'][next_elem]['items'], schema_path) when 'object' find_elem_in_schema(root['properties'][next_elem], schema_path) else raise ArgumentError.new("Don't know how to handle the schema path #{schema_path.join('/')}") end end # Store an object "type" seen on parameters or response types def remember_type(type) @types ||= [] return if %w(string integer boolean float array symbol virtus::attribute::boolean rack::multipart::uploadedfile date datetime).include?(type.to_s.downcase) type = Object.const_get type.to_s return if @types.include?(type.to_s) @types << type.to_s end end end
{ "content_hash": "4ad26fa78e607c74b6323cae494f3fa8", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 161, "avg_line_length": 35.722044728434504, "alnum_prop": 0.6002146498524282, "repo_name": "reverbdotcom/ruby-swagger", "id": "51a1f29265424c5c169ec85159c863a2e3721b95", "size": "11181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/ruby-swagger/grape/method.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "208865" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- Copyright (C) 2015-2019 Fabrice Bouyé All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. --> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div>This package contains the classes used to map data from the mounts/types API v2 endpoint. <br>More information on this endpoint:</div> <ul> <li>Official forum: <li>Wiki: <a href="https://wiki.guildwars2.com/wiki/API:2/mounts/types">API:2/mounts/types</a></li> </ul> </body> </html>
{ "content_hash": "7c4faee296881e5a69ce7627611c4bad", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 111, "avg_line_length": 32.65217391304348, "alnum_prop": 0.6245006657789614, "repo_name": "fabricebouye/gw2-web-api-mapping", "id": "e622390ebe9cefae1f9b7ab4c59cdfb7d2a9178b", "size": "752", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/api/web/gw2/mapping/v2/mounts/types/package.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "98497" }, { "name": "Java", "bytes": "748471" } ], "symlink_target": "" }
using System; using CoreGraphics; using UIKit; using Toggl.Ross.Theme; namespace Toggl.Ross.Views { public class TableViewHeaderView : UIView { private UIView backgroundView; public TableViewHeaderView () { backgroundView = new UIView (); AddSubview (backgroundView); this.Apply (Style.TableViewHeader); } public override void LayoutSubviews () { base.LayoutSubviews (); backgroundView.Frame = new CGRect (0, -480, Frame.Width, 480); } public override UIColor BackgroundColor { get { return backgroundView.BackgroundColor; } set { backgroundView.BackgroundColor = value; } } } }
{ "content_hash": "3d3f2731dc9cefa774a9b1731820ce79", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 74, "avg_line_length": 23.060606060606062, "alnum_prop": 0.5913272010512484, "repo_name": "peeedge/mobile", "id": "e3603087ae764601b049bd3e84f969c0ccc29610", "size": "761", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Ross/Views/TableViewHeaderView.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "1950546" }, { "name": "Makefile", "bytes": "1582" }, { "name": "Shell", "bytes": "2332" } ], "symlink_target": "" }
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.graphics.NinePatch ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_GRAPHICS_NINEPATCH_HPP_DECL #define J2CPP_ANDROID_GRAPHICS_NINEPATCH_HPP_DECL namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace android { namespace graphics { class Canvas; } } } namespace j2cpp { namespace android { namespace graphics { class Paint; } } } namespace j2cpp { namespace android { namespace graphics { class Rect; } } } namespace j2cpp { namespace android { namespace graphics { class Bitmap; } } } namespace j2cpp { namespace android { namespace graphics { class RectF; } } } namespace j2cpp { namespace android { namespace graphics { class Region; } } } #include <android/graphics/Bitmap.hpp> #include <android/graphics/Canvas.hpp> #include <android/graphics/Paint.hpp> #include <android/graphics/Rect.hpp> #include <android/graphics/RectF.hpp> #include <android/graphics/Region.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace android { namespace graphics { class NinePatch; class NinePatch : public object<NinePatch> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) explicit NinePatch(jobject jobj) : object<NinePatch>(jobj) { } operator local_ref<java::lang::Object>() const; NinePatch(local_ref< android::graphics::Bitmap > const&, local_ref< array<jbyte,1> > const&, local_ref< java::lang::String > const&); void setPaint(local_ref< android::graphics::Paint > const&); void draw(local_ref< android::graphics::Canvas > const&, local_ref< android::graphics::RectF > const&); void draw(local_ref< android::graphics::Canvas > const&, local_ref< android::graphics::Rect > const&); void draw(local_ref< android::graphics::Canvas > const&, local_ref< android::graphics::Rect > const&, local_ref< android::graphics::Paint > const&); jint getDensity(); jint getWidth(); jint getHeight(); jboolean hasAlpha(); local_ref< android::graphics::Region > getTransparentRegion(local_ref< android::graphics::Rect > const&); static jboolean isNinePatchChunk(local_ref< array<jbyte,1> > const&); }; //class NinePatch } //namespace graphics } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_GRAPHICS_NINEPATCH_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_GRAPHICS_NINEPATCH_HPP_IMPL #define J2CPP_ANDROID_GRAPHICS_NINEPATCH_HPP_IMPL namespace j2cpp { android::graphics::NinePatch::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::graphics::NinePatch::NinePatch(local_ref< android::graphics::Bitmap > const &a0, local_ref< array<jbyte,1> > const &a1, local_ref< java::lang::String > const &a2) : object<android::graphics::NinePatch>( call_new_object< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(0), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(0) >(a0, a1, a2) ) { } void android::graphics::NinePatch::setPaint(local_ref< android::graphics::Paint > const &a0) { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(1), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(1), void >(get_jobject(), a0); } void android::graphics::NinePatch::draw(local_ref< android::graphics::Canvas > const &a0, local_ref< android::graphics::RectF > const &a1) { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(2), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(2), void >(get_jobject(), a0, a1); } void android::graphics::NinePatch::draw(local_ref< android::graphics::Canvas > const &a0, local_ref< android::graphics::Rect > const &a1) { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(3), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject(), a0, a1); } void android::graphics::NinePatch::draw(local_ref< android::graphics::Canvas > const &a0, local_ref< android::graphics::Rect > const &a1, local_ref< android::graphics::Paint > const &a2) { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(4), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(4), void >(get_jobject(), a0, a1, a2); } jint android::graphics::NinePatch::getDensity() { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(5), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject()); } jint android::graphics::NinePatch::getWidth() { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(6), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(6), jint >(get_jobject()); } jint android::graphics::NinePatch::getHeight() { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(7), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(7), jint >(get_jobject()); } jboolean android::graphics::NinePatch::hasAlpha() { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(8), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(8), jboolean >(get_jobject()); } local_ref< android::graphics::Region > android::graphics::NinePatch::getTransparentRegion(local_ref< android::graphics::Rect > const &a0) { return call_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(9), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(9), local_ref< android::graphics::Region > >(get_jobject(), a0); } jboolean android::graphics::NinePatch::isNinePatchChunk(local_ref< array<jbyte,1> > const &a0) { return call_static_method< android::graphics::NinePatch::J2CPP_CLASS_NAME, android::graphics::NinePatch::J2CPP_METHOD_NAME(10), android::graphics::NinePatch::J2CPP_METHOD_SIGNATURE(10), jboolean >(a0); } J2CPP_DEFINE_CLASS(android::graphics::NinePatch,"android/graphics/NinePatch") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,0,"<init>","(Landroid/graphics/Bitmap;[BLjava/lang/String;)V") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,1,"setPaint","(Landroid/graphics/Paint;)V") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,2,"draw","(Landroid/graphics/Canvas;Landroid/graphics/RectF;)V") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,3,"draw","(Landroid/graphics/Canvas;Landroid/graphics/Rect;)V") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,4,"draw","(Landroid/graphics/Canvas;Landroid/graphics/Rect;Landroid/graphics/Paint;)V") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,5,"getDensity","()I") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,6,"getWidth","()I") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,7,"getHeight","()I") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,8,"hasAlpha","()Z") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,9,"getTransparentRegion","(Landroid/graphics/Rect;)Landroid/graphics/Region;") J2CPP_DEFINE_METHOD(android::graphics::NinePatch,10,"isNinePatchChunk","([B)Z") } //namespace j2cpp #endif //J2CPP_ANDROID_GRAPHICS_NINEPATCH_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
{ "content_hash": "3b6262ca31899e1cc96ffc93f743459f", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 186, "avg_line_length": 35.904761904761905, "alnum_prop": 0.698818422956354, "repo_name": "hyEvans/ph-open", "id": "e84c048420ecc6c7af8e7e1df653c02017fbbc37", "size": "8294", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "proj.android/jni/puzzleHero/platforms/android-9/android/graphics/NinePatch.hpp", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
package com.hazelcast.mapreduce; import com.hazelcast.core.HazelcastException; import java.util.List; /** * This exception class is used to show stack traces of multiple failed * remote operations at once. This can happen if the {@link com.hazelcast.mapreduce.impl.operation.GetResultOperation} * fails to retrieve values for some reason. * @deprecated MapReduce is deprecated and will be removed in 4.0. * For map aggregations, you can use {@link com.hazelcast.aggregation.Aggregator} on IMap. * For general data processing, it is superseded by <a href="http://jet.hazelcast.org">Hazelcast Jet</a>. */ @Deprecated public class RemoteMapReduceException extends HazelcastException { public RemoteMapReduceException(String message, List<Exception> remoteCauses) { super(message); setStackTraceElements(remoteCauses); } private void setStackTraceElements(List<Exception> remoteCauses) { StackTraceElement[] originalElements = super.getStackTrace(); int stackTraceSize = originalElements.length; for (Exception remoteCause : remoteCauses) { stackTraceSize += remoteCause.getStackTrace().length + 1; } StackTraceElement[] elements = new StackTraceElement[stackTraceSize]; System.arraycopy(originalElements, 0, elements, 0, originalElements.length); int pos = originalElements.length; for (Exception remoteCause : remoteCauses) { StackTraceElement[] remoteStackTraceElements = remoteCause.getStackTrace(); elements[pos++] = new StackTraceElement("--- Remote Exception: " + remoteCause.getMessage() + " ---", "", null, 0); for (int i = 0; i < remoteStackTraceElements.length; i++) { StackTraceElement element = remoteStackTraceElements[i]; String className = " " + element.getClassName(); String methodName = element.getMethodName(); String fileName = element.getFileName(); elements[pos++] = new StackTraceElement(className, methodName, fileName, element.getLineNumber()); } } setStackTrace(elements); } }
{ "content_hash": "7b6a379b6ce472d6c5bd4a7d470e77bc", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 127, "avg_line_length": 43.58, "alnum_prop": 0.6851766865534649, "repo_name": "juanavelez/hazelcast", "id": "3faddf66ce7dca0fe652d32e1277e4feebd9d190", "size": "2804", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/mapreduce/RemoteMapReduceException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1449" }, { "name": "Java", "bytes": "34162014" }, { "name": "Shell", "bytes": "12372" } ], "symlink_target": "" }
#region License #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml.Serialization; using MessyLab.Platforms; namespace MessyLab { /// <summary> /// Represents a Messy Lab project. /// </summary> public class Project { public Project() { Items = new List<ProjectItem>(); } /// <summary> /// The name of the project file. /// </summary> /// <example>UberCode.mlp</example> public string Filename { get { string res = string.Empty; try { res = System.IO.Path.GetFileName(Path); } catch { } return res; } } /// <summary> /// Full directory name of the project. /// </summary> /// <example> /// c:\Users\JSmith\Ducuments\Messy Lab Projects\UberCode /// </example> public string Directory { get { string res = string.Empty; try { res = System.IO.Path.GetDirectoryName(Path); } catch { } return res; } } /// <summary> /// Full path to the project file. /// </summary> /// <example> /// c:\Users\JSmith\Ducuments\Messy Lab Projects\UberCode\UberCode.mlp /// </example> public string Path { get; set; } /// <summary> /// A list of project items. /// </summary> public List<ProjectItem> Items { get; private set; } /// <summary> /// The main (start-up) project item. /// </summary> public ProjectItem MainItem { get; set; } /// <summary> /// Check whether the an item with the specified path /// already exists. /// </summary> /// <param name="relativePath">The relative path to check.</param> /// <returns>A value indicating whether the an item with the /// specified path already exists withing the project</returns> public bool ItemExists(string relativePath) { foreach (var i in Items) { if (Program.IsSamePath(i.RelativePath, relativePath)) { return true; } } return false; } /// <summary> /// Instance of the Project's Platform. /// </summary> public Platform Platform { get; set; } /// <summary> /// Factory object used to create the platform by name. /// </summary> public PlatformFactory PlatformFactory { get; set; } /// <summary> /// Sets the Platform by creating it for the specified name /// using the PlatformFactory. /// </summary> /// <param name="name">The platform name.</param> public void SetPlatformByName(string name) { PlatformFactory factory; if (PlatformFactory == null) { factory = PlatformFactory.Default; } else { factory = PlatformFactory; } Platform = factory.CreatePlatform(this, name); } /// <summary> /// Saves the project state to a memento. /// </summary> /// <returns>Memento containing the project state.</returns> public ProjectMemento CreateMemento() { var memento = new ProjectMemento(); foreach (var item in Items) { memento.Items.Add(item.RelativePath); } if (MainItem != null) { memento.MainItem = MainItem.RelativePath; } memento.Platform = Platform.Name; return memento; } /// <summary> /// Restores the project state from the specified memento. /// </summary> /// <param name="memento">The memento to restore.</param> public void SetMemento(ProjectMemento memento) { Items.Clear(); MainItem = null; foreach (var i in memento.Items) { var item = new ProjectItem(); item.Project = this; item.RelativePath = i; if (!File.Exists(item.Path)) { File.WriteAllText(item.Path, string.Empty); } Items.Add(item); if (i == memento.MainItem) { MainItem = item; } } SetPlatformByName(memento.Platform); } /// <summary> /// Save the project to file. /// </summary> /// <param name="newProject">A value indicating whether the project to save is newly created.</param> public void Save(bool newProject) { foreach (var item in Items) { item.Save(); } var memento = CreateMemento(); XmlSerializer s = new XmlSerializer(memento.GetType()); TextWriter w = new StreamWriter(Path); s.Serialize(w, memento); w.Close(); // Only save settings for the open projects. if (!newProject) { Platform.SaveSettings(); } OnSaved(); } /// <summary> /// Saves the project to file. /// </summary> public void Save() { Save(false); } /// <summary> /// Opens the project form file. /// </summary> /// <param name="path">The path to the project file.</param> public void Open(string path) { XmlSerializer s = new XmlSerializer(typeof(ProjectMemento)); TextReader r = new StreamReader(path); var memento = s.Deserialize(r) as ProjectMemento; r.Close(); Path = path; SetMemento(memento); Platform.LoadSettings(); } /// <summary> /// Indicates whether the any of the items has been modified. /// </summary> public bool IsModified { get { foreach (var item in Items) { var editor = Platform.Editors.GetEditorFormIfExists(item); if (editor != null && editor.IsModified) return true; } return false; } } /// <summary> /// Reverts changes made to the items. /// </summary> public void Revert() { foreach (var item in Items) { var editor = Platform.Editors.GetEditorFormIfExists(item); if (editor != null) editor.Revert(); } } /// <summary> /// Occurs when the project is opened. /// </summary> public event Action Saved; protected void OnSaved() { if (Saved != null) Saved(); } } }
{ "content_hash": "4a7dc629ea7201b2c1a24db7596296f7", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 103, "avg_line_length": 23.132, "alnum_prop": 0.6026283935673525, "repo_name": "drstorm/messylab", "id": "31dbfe7638d09198133c6eadb319fd622ed406e0", "size": "6407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MessyLab/Project.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "91" }, { "name": "C#", "bytes": "1821461" }, { "name": "Inno Setup", "bytes": "4007" } ], "symlink_target": "" }
class ManagerInterface: def __init__(self): self._state = {} @property def state(self): return self._state def _get_state_data(self, obj): raise NotImplementedError def subscribe(self, obj): key, value = self._get_state_data(obj) self._subscribe(key=key, value=value) def _subscribe(self, key, value): if key in self.state: assert self.state[key] == value else: self.state[key] = value def knows(self, key): return key in self.state def get(self, key): return self.state.get(key) @property def keys(self): return self.state.keys() @property def values(self): return self.state.values() @property def items(self): return self.state.items()
{ "content_hash": "e79c30d4b642745fc3b768b1b6278800", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 46, "avg_line_length": 21.68421052631579, "alnum_prop": 0.5703883495145631, "repo_name": "polyaxon/polyaxon", "id": "7223c5669772f190f3e4ee8c9120681d857a222d", "size": "1430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/polyaxon/utils/manager_interface.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1989" }, { "name": "Python", "bytes": "5201898" }, { "name": "Shell", "bytes": "1565" } ], "symlink_target": "" }
package core import ( "k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common" "net/http" ) // UpdateBootVolumeKmsKeyRequest wrapper for the UpdateBootVolumeKmsKey operation // // # See also // // Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/UpdateBootVolumeKmsKey.go.html to see an example of how to use UpdateBootVolumeKmsKeyRequest. type UpdateBootVolumeKmsKeyRequest struct { // The OCID of the boot volume. BootVolumeId *string `mandatory:"true" contributesTo:"path" name:"bootVolumeId"` // Updates the Key Management master encryption key assigned to the specified boot volume. UpdateBootVolumeKmsKeyDetails `contributesTo:"body"` // For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` // parameter to the value of the etag from a previous GET or POST response for that resource. The resource // will be updated or deleted only if the etag you provide matches the resource's current etag value. IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"` // Unique Oracle-assigned identifier for the request. // If you need to contact Oracle about a particular request, please provide the request ID. OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` // Metadata about the request. This information will not be transmitted to the service, but // represents information that the SDK will consume to drive retry behavior. RequestMetadata common.RequestMetadata } func (request UpdateBootVolumeKmsKeyRequest) String() string { return common.PointerString(request) } // HTTPRequest implements the OCIRequest interface func (request UpdateBootVolumeKmsKeyRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request) } // BinaryRequestBody implements the OCIRequest interface func (request UpdateBootVolumeKmsKeyRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } // RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy. func (request UpdateBootVolumeKmsKeyRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } // UpdateBootVolumeKmsKeyResponse wrapper for the UpdateBootVolumeKmsKey operation type UpdateBootVolumeKmsKeyResponse struct { // The underlying http response RawResponse *http.Response // The BootVolumeKmsKey instance BootVolumeKmsKey `presentIn:"body"` // For optimistic concurrency control. See `if-match`. Etag *string `presentIn:"header" name:"etag"` // Unique Oracle-assigned identifier for the request. If you need to contact // Oracle about a particular request, please provide the request ID. OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response UpdateBootVolumeKmsKeyResponse) String() string { return common.PointerString(response) } // HTTPResponse implements the OCIResponse interface func (response UpdateBootVolumeKmsKeyResponse) HTTPResponse() *http.Response { return response.RawResponse }
{ "content_hash": "7aed76b67ce2a16e923881abec1bd524", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 177, "avg_line_length": 39.44444444444444, "alnum_prop": 0.7971830985915493, "repo_name": "kubernetes/autoscaler", "id": "19d63c97b321642e98dd688f74f6d5da37806891", "size": "3562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/core/update_boot_volume_kms_key_request_response.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "5407" }, { "name": "Go", "bytes": "19468437" }, { "name": "Makefile", "bytes": "19380" }, { "name": "Mustache", "bytes": "4034" }, { "name": "Python", "bytes": "20902" }, { "name": "Roff", "bytes": "1730" }, { "name": "Ruby", "bytes": "1255" }, { "name": "Shell", "bytes": "53412" } ], "symlink_target": "" }
from msrest.serialization import Model class ConnectivityHop(Model): """Information about a hop between the source and the destination. Variables are only populated by the server, and will be ignored when sending a request. :ivar type: The type of the hop. :vartype type: str :ivar id: The ID of the hop. :vartype id: str :ivar address: The IP address of the hop. :vartype address: str :ivar resource_id: The ID of the resource corresponding to this hop. :vartype resource_id: str :ivar next_hop_ids: List of next hop identifiers. :vartype next_hop_ids: list[str] :ivar issues: List of issues. :vartype issues: list[~azure.mgmt.network.v2017_09_01.models.ConnectivityIssue] """ _validation = { 'type': {'readonly': True}, 'id': {'readonly': True}, 'address': {'readonly': True}, 'resource_id': {'readonly': True}, 'next_hop_ids': {'readonly': True}, 'issues': {'readonly': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'address': {'key': 'address', 'type': 'str'}, 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'next_hop_ids': {'key': 'nextHopIds', 'type': '[str]'}, 'issues': {'key': 'issues', 'type': '[ConnectivityIssue]'}, } def __init__(self, **kwargs): super(ConnectivityHop, self).__init__(**kwargs) self.type = None self.id = None self.address = None self.resource_id = None self.next_hop_ids = None self.issues = None
{ "content_hash": "ca30cae0ece50f65a6a19a9138e19111", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 72, "avg_line_length": 32.8, "alnum_prop": 0.5762195121951219, "repo_name": "lmazuel/azure-sdk-for-python", "id": "82a36aebb693cd804c82bd8216b8b0ae7665885e", "size": "2114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/connectivity_hop.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42572767" } ], "symlink_target": "" }
"""Extract reference documentation from the NumPy source tree. """ from __future__ import print_statement import inspect import textwrap import re import pydoc from StringIO import StringIO from warnings import warn class Reader(object): """A line-based string reader. """ def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data,list): self._str = data else: self._str = data.split('\n') # store string as list of lines self.reset() def __getitem__(self, n): return self._str[n] def reset(self): self._l = 0 # current line nr def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return '' def seek_next_non_empty_line(self): for l in self[self._l:]: if l.strip(): break else: self._l += 1 def eof(self): return self._l >= len(self._str) def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start:self._l] self._l += 1 if self.eof(): return self[start:self._l+1] return [] def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty) def read_to_next_unindented_line(self): def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line))) return self.read_to_condition(is_unindented) def peek(self,n=0): if self._l + n < len(self._str): return self[self._l + n] else: return '' def is_empty(self): return not ''.join(self._str).strip() class NumpyDocString(object): def __init__(self,docstring): docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], 'Notes': [], 'Warnings': [], 'References': '', 'Examples': '', 'index': {} } self._parse() def __getitem__(self,key): return self._parsed_data[key] def __setitem__(self,key,val): if not self._parsed_data.has_key(key): warn("Unknown section %s" % key) else: self._parsed_data[key] = val def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) def _strip(self,doc): i = 0 j = 0 for i,line in enumerate(doc): if line.strip(): break for j,line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc)-j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self,content): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) params.append((arg_name,arg_type,desc)) return params _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|" r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X) def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not a item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): self['Summary'] = self._doc.read_to_next_empty_line() else: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() for (section,content) in self._read_sections(): if not section.startswith('..'): section = ' '.join([s.capitalize() for s in section.split(' ')]) if section in ('Parameters', 'Attributes', 'Methods', 'Returns', 'Raises', 'Warns'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content # string conversion routines def _str_header(self, name, symbol='-'): return [name, len(name)*symbol] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*','\*')] + [''] else: return [''] def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return [] def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param,param_type,desc in self[name]: out += ['%s : %s' % (param, param_type)] out += self._str_indent(desc) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") last_had_desc = True for func, desc, role in self['See Also']: if role: link = ':%s:`%s`' % (role, func) elif func_role: link = ':%s:`%s`' % (func_role, func) else: link = "`%s`_" % func if desc or last_had_desc: out += [''] out += [link] else: out[-1] += ", %s" % link if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += [''] return out def _str_index(self): idx = self['index'] out = [] out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.items(): if section == 'default': continue out += [' :%s: %s' % (section, ', '.join(references))] return out def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters','Returns','Raises'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes','References','Examples'): out += self._str_section(s) out += self._str_index() return '\n'.join(out) def indent(str,indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") def header(text, style='-'): return text + '\n' + style*len(text) + '\n' class FunctionDoc(NumpyDocString): def __init__(self, func, role='func', doc=None): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: doc = inspect.getdoc(func) or '' try: NumpyDocString.__init__(self, doc) except ValueError, e: print('*'*78) print("ERROR: '%s' while parsing `%s`" % (e, self._f)) print('*'*78) #print "Docstring follows:" #print doclines #print '='*78 if not self['Signature']: func, func_name = self.get_func() try: # try to read signature argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*','\*') signature = '%s%s' % (func_name, argspec) except TypeError, e: signature = '%s()' % func_name self['Signature'] = signature def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, '__call__', self._f.__init__) else: func = self._f return func, func_name def __str__(self): out = '' func, func_name = self.get_func() signature = self['Signature'].replace('*', '\*') roles = {'func': 'function', 'meth': 'method'} if self._role: if not roles.has_key(self._role): print("Warning: invalid role %s" % self._role) out += '.. %s:: %s\n \n\n' % (roles.get(self._role,''), func_name) out += super(FunctionDoc, self).__str__(func_role=self._role) return out class ClassDoc(NumpyDocString): def __init__(self,cls,modulename='',func_doc=FunctionDoc,doc=None): if not inspect.isclass(cls): raise ValueError("Initialise using a class. Got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename self._name = cls.__name__ self._func_doc = func_doc if doc is None: doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) @property def methods(self): return [name for name,func in inspect.getmembers(self._cls) if not name.startswith('_') and callable(func)] def __str__(self): out = '' out += super(ClassDoc, self).__str__() out += "\n\n" #for m in self.methods: # print "Parsing `%s`" % m # out += str(self._func_doc(getattr(self._cls,m), 'meth')) + '\n\n' # out += '.. index::\n single: %s; %s\n\n' % (self._name, m) return out
{ "content_hash": "8a3e94f8d7b96e0cba969c2ea428db13", "timestamp": "", "source": "github", "line_count": 499, "max_line_length": 80, "avg_line_length": 29.81362725450902, "alnum_prop": 0.4724070713181421, "repo_name": "whitergh/brainx", "id": "91b2ef55db427205a9e4de65f91c7c8921ec2e73", "size": "14877", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/sphinxext/docscrape.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "232998" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/ludoblues/sitemap-stream.svg?branch=master)](https://travis-ci.org/ludoblues/sitemap-stream) [![Coverage Status](https://coveralls.io/repos/ludoblues/sitemap-stream/badge.svg?branch=master&service=github)](https://coveralls.io/github/ludoblues/sitemap-stream?branch=master) # sitemap-stream SitemapStream is a simple and fast tool that build sitemaps using streams. It automatically creates separated files, following the [Google specifications](https://support.google.com/webmasters/topic/4581190?hl=en&ref_topic=4581352) You can find information about the sitemap's syntax [here](http://www.sitemaps.org/protocol.html) (you'll find the authorized values the #inject method can receive). *Notes:* - This package respects the [semver](http://semver.org/) and the [keep a changelog](http://keepachangelog.com/) specifications. - This module's code is using ES6 features, so you'll probably need to run your application with the flag --harmony (depending to your Node version). ## Install npm i sitemap-stream ## Methods #### SitemapStream#Constructor(options): ```js { sitemapDirectoryUrl: String, limit: Number, // (default: 50000) isMobile: Boolean, // (default: false) outputFolder: String // (default: './') toCompress: Boolean // (default: true) } ``` #### SitemapStream#inject(url || options) Url Case: ```js // The url ``` Options Case: ````js { url: String, // (required) changeFreq: String, priority: String } ```` #### SitemapStream#reset Useful if you want to start writing a new sitemap using the same SitemapStream instance ## Events SitemapStream use streams, so it emit events to let you know what happens. Here are the events you can listen to: #### error ````js sg.on('error', err => { console.error(`Something wrong happened: ${err}`); }); ```` #### drain ````js let i = 0; function injectUrls() { while (i<1000000) { const isInjected = sg.inject(`http://test-${i}.com`); if (!isInjected) return i; i++; } } sg.on('drain', () => { console.info(`Because we have injected a big amount of lines in a short time, the stream could need to be drained, in this case, the sg#inject method returns false and the drain event is emitted when the stream is ready to write again`); injectUrls(); }); injectUrls(); ```` #### sitemap-created ````js sg.on('sitemap-created', path => { console.info(`A sitemap file has just been written here: ${path}`); }); ```` #### sitemap-index ````js sg.on('sitemap-index', path => { console.info(`A sitemapindex file has just been written here: ${path}`); }); ```` #### done ````js sg.on('done', nbFiles => { console.info(`The job is done, we have written ${nbFiles} files !`); }); ```` ## Examples Basic ```` js const sg = require('sitemap-stream')(); sg.inject('/some-path'); sg.inject({ url: '/another-path' }); sg.inject({ url: '/my-last-path', changeFreq: 'daily', priority: 0.7 }); sg.done(); ```` With options ```` js const sg = require('sitemap-stream')({ isMobile: true }); sg.inject('/some-path'); sg.inject({ url: '/another-path' }); sg.inject({ url: '/my-last-path', changeFreq: 'daily', priority: 0.7 }); sg.done(); ```` With Events ```` js const sg = require('sitemap-stream')(); sg.on('sitemap-created', (fileName) => { // This listener will be trigger twice, one when the first 50 000 urls will be injected, and another time when you'll call the #done method console.log('A sitemap has been created !'); }); sg.on('sitemapindex-index', () => { // When listener will be trigger once the sitemapindex file will be written console.log('The sitemapindex has been created, we are done !'); }); sg.on('done', () => { console.info('Everything is done !'); }); for (let i=0; i<60000; i++) sg.inject(`/some-path-${i}`); sg.done(); ````
{ "content_hash": "796b8749ea1570ffe26dc60fd5fd4434", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 239, "avg_line_length": 25.149350649350648, "alnum_prop": 0.6656338755486703, "repo_name": "ludoblues/sitemap-stream", "id": "2257bbb2a3861085cf9ad6ee3d0f13f9681e8196", "size": "3873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "32122" } ], "symlink_target": "" }
<?php // Heading $_['heading_title'] = 'Coupon'; // Text $_['text_success'] = 'Success: You have modified coupons!'; $_['text_percent'] = 'Percentage'; $_['text_amount'] = 'Fixed Amount'; // Column $_['column_name'] = 'Coupon Name'; $_['column_code'] = 'Code'; $_['column_discount'] = 'Discount'; $_['column_date_start'] = 'Date Start'; $_['column_date_end'] = 'Date End'; $_['column_status'] = 'Status'; $_['column_action'] = 'Action'; // Entry $_['entry_name'] = 'Coupon Name:'; $_['entry_description'] = 'Coupon Description:'; $_['entry_code'] = 'Code:<br /><span class="help">The code the customer enters to get the discount</span>'; $_['entry_type'] = 'Type:<br /><span class="help">Percentage or Fixed Amount</span>'; $_['entry_discount'] = 'Discount:'; $_['entry_logged'] = 'Customer Login:<br /><span class="help">Customer must be logged in to use the coupon.</span>'; $_['entry_shipping'] = 'Free Shipping:'; $_['entry_total'] = 'Total Amount:<br /><span class="help">The total amount that must reached before the coupon is valid.</span>'; $_['entry_product'] = 'Products:'; $_['entry_date_start'] = 'Date Start:'; $_['entry_date_end'] = 'Date End:'; $_['entry_uses_total'] = 'Uses Per Coupon:<br /><span class="help">The maximum number of times the coupon can be used by any customer. Leave blank for unlimited</span>'; $_['entry_uses_customer'] = 'Uses Per Customer:<br /><span class="help">The maximum number of times the coupon can be used by a single customer. Leave blank for unlimited</span>'; $_['entry_status'] = 'Status:'; // Error $_['error_permission'] = 'Warning: You do not have permission to modify coupons!'; $_['error_name'] = 'Coupon Name must be between 3 and 64 characters!'; $_['error_description'] = 'Coupon Description must be between 3 characters!'; $_['error_code'] = 'Code must be between 3 and 10 characters!'; ?>
{ "content_hash": "11f424eb6e9dfc434afd16a97bc48edd", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 179, "avg_line_length": 50.575, "alnum_prop": 0.59268413247652, "repo_name": "yangchf/testBed", "id": "e1742881874a3ef971e9d03388f327a9f7f82296", "size": "2023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "appSrc/store/admin/language/english/sale/coupon.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "1062" }, { "name": "Batchfile", "bytes": "3196" }, { "name": "CSS", "bytes": "170629" }, { "name": "HTML", "bytes": "372470" }, { "name": "JavaScript", "bytes": "771410" }, { "name": "Makefile", "bytes": "451" }, { "name": "PHP", "bytes": "1984456" }, { "name": "Shell", "bytes": "1925" }, { "name": "Smarty", "bytes": "917786" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" dir="ltr"> <!--<![endif]--> <!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) --> <!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca --> <head> <!-- Title begins / Début du titre --> <title> EP Physiotherapy - Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada </title> <!-- Title ends / Fin du titre --> <!-- Meta-data begins / Début des métadonnées --> <meta charset="utf-8" /> <meta name="dcterms.language" title="ISO639-2" content="eng" /> <meta name="dcterms.title" content="" /> <meta name="description" content="" /> <meta name="dcterms.description" content="" /> <meta name="dcterms.type" content="report, data set" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.issued" title="W3CDTF" content="" /> <meta name="dcterms.modified" title="W3CDTF" content="" /> <meta name="keywords" content="" /> <meta name="dcterms.creator" content="" /> <meta name="author" content="" /> <meta name="dcterms.created" title="W3CDTF" content="" /> <meta name="dcterms.publisher" content="" /> <meta name="dcterms.audience" title="icaudience" content="" /> <meta name="dcterms.spatial" title="ISO3166-1" content="" /> <meta name="dcterms.spatial" title="gcgeonames" content="" /> <meta name="dcterms.format" content="HTML" /> <meta name="dcterms.identifier" title="ICsiteProduct" content="536" /> <!-- EPI-11240 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- MCG-202 --> <meta content="width=device-width,initial-scale=1" name="viewport"> <!-- EPI-11567 --> <meta name = "format-detection" content = "telephone=no"> <!-- EPI-12603 --> <meta name="robots" content="noarchive"> <!-- EPI-11190 - Webtrends --> <script> var startTime = new Date(); startTime = startTime.getTime(); </script> <!--[if gte IE 9 | !IE ]><!--> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon"> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css"> <!--<![endif]--> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css"> <!--[if lt IE 9]> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" /> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script> <![endif]--> <!--[if lte IE 9]> <![endif]--> <noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <script>dataLayer1 = [];</script> <!-- End Google Tag Manager --> <!-- EPI-11235 --> <link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body class="home" vocab="http://schema.org/" typeof="WebPage"> <!-- EPIC HEADER BEGIN --> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script> <!-- End Google Tag Manager --> <!-- EPI-12801 --> <span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span> <ul id="wb-tphp"> <li class="wb-slc"> <a class="wb-sl" href="#wb-cont">Skip to main content</a> </li> <li class="wb-slc visible-sm visible-md visible-lg"> <a class="wb-sl" href="#wb-info">Skip to "About this site"</a> </li> </ul> <header role="banner"> <div id="wb-bnr" class="container"> <section id="wb-lng" class="visible-md visible-lg text-right"> <h2 class="wb-inv">Language selection</h2> <div class="row"> <div class="col-md-12"> <ul class="list-inline mrgn-bttm-0"> <li><a href="nvgt.do?V_TOKEN=1492284092504&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=16307&V_SEARCH.docsStart=16306&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn//magmi/web/download_file.php?_flId?_flxKy=e1s1&amp;estblmntNo=234567041301&amp;profileId=61&amp;_evId=bck&amp;lang=eng&amp;V_SEARCH.showStricts=false&amp;prtl=1&amp;_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li> </ul> </div> </div> </section> <div class="row"> <div class="brand col-xs-8 col-sm-9 col-md-6"> <a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a> </div> <section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn"> <h2>Search and menus</h2> <ul class="list-inline text-right chvrn"> <li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li> </ul> <div id="mb-pnl"></div> </section> <!-- Site Search Removed --> </div> </div> <nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement"> <h2 class="wb-inv">Topics menu</h2> <div class="container nvbar"> <div class="row"> <ul class="list-inline menu"> <li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li> <li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li> <li><a href="https://travel.gc.ca/">Travel</a></li> <li><a href="https://www.canada.ca/en/services/business.html">Business</a></li> <li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li> <li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li> <li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li> <li><a href="https://www.canada.ca/en/services.html">More services</a></li> </ul> </div> </div> </nav> <!-- EPIC BODY BEGIN --> <nav role="navigation" id="wb-bc" class="" property="breadcrumb"> <h2 class="wb-inv">You are here:</h2> <div class="container"> <div class="row"> <ol class="breadcrumb"> <li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li> <li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li> <li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li> </ol> </div> </div> </nav> </header> <main id="wb-cont" role="main" property="mainContentOfPage" class="container"> <!-- End Header --> <!-- Begin Body --> <!-- Begin Body Title --> <!-- End Body Title --> <!-- Begin Body Head --> <!-- End Body Head --> <!-- Begin Body Content --> <br> <!-- Complete Profile --> <!-- Company Information above tabbed area--> <input id="showMore" type="hidden" value='more'/> <input id="showLess" type="hidden" value='less'/> <h1 id="wb-cont"> Company profile - Canadian Company Capabilities </h1> <div class="profileInfo hidden-print"> <ul class="list-inline"> <li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&amp;rstBtn.x=" class="btn btn-link">New Search</a>&nbsp;|</li> <li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do"> <input type="hidden" name="lang" value="eng" /> <input type="hidden" name="profileId" value="" /> <input type="hidden" name="prtl" value="1" /> <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" /> <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" /> <input type="hidden" name="V_SEARCH.depth" value="1" /> <input type="hidden" name="V_SEARCH.showStricts" value="false" /> <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" /> </form></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=16305&amp;V_DOCUMENT.docRank=16306&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492284103919&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567103018&amp;profileId=&amp;key.newSearchLabel=">Previous Company</a></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=16307&amp;V_DOCUMENT.docRank=16308&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492284103919&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=131038177771&amp;profileId=&amp;key.newSearchLabel=">Next Company</a></li> </ul> </div> <details> <summary>Third-Party Information Liability Disclaimer</summary> <p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p> </details> <h2> EP Physiotherapy </h2> <div class="row"> <div class="col-md-5"> <h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2> <p>EP Physiotherapy</p> <div class="mrgn-tp-md"></div> <p class="mrgn-bttm-0" ><a href="http://www.epphysio.pthealth.ca" target="_blank" title="Website URL">http://www.epphysio.pthealth.ca</a></p> <p><a href="mailto:consults@pthealth.ca" title="consults@pthealth.ca">consults@pthealth.ca</a></p> </div> <div class="col-md-4 mrgn-sm-sm"> <h2 class="h5 mrgn-bttm-0">Mailing Address:</h2> <address class="mrgn-bttm-md"> 1534 Shore Rd<br/> EASTERN PASSAGE, Nova Scotia<br/> B3G 1M5 <br/> </address> <h2 class="h5 mrgn-bttm-0">Location Address:</h2> <address class="mrgn-bttm-md"> 1534 Shore Rd<br/> EASTERN PASSAGE, Nova Scotia<br/> B3G 1M5 <br/> </address> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (902) 466-9012 </p> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (866) 749-7461</p> <p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>: (902) 466-9013</p> </div> <div class="col-md-3 mrgn-tp-md"> <h2 class="wb-inv">Logo</h2> <img class="img-responsive text-left" src="https://www.ic.gc.ca/app/ccc/srch/media?estblmntNo=234567149103&amp;graphFileName=ep.jpg&amp;applicationCode=AP&amp;lang=eng" alt="Logo" /> </div> </div> <div class="row mrgn-tp-md mrgn-bttm-md"> <div class="col-md-12"> <h2 class="wb-inv">Company Profile</h2> <br> EP Physiotherapy offers an array of insurance covered physiotherapy &amp; pain relief services that can help you feel your best. Call us today for a no-obligation appointment.<br> </div> </div> <!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> --> <div class="wb-tabs ignore-session"> <div class="tabpanels"> <details id="details-panel1"> <summary> Full profile </summary> <!-- Tab 1 --> <h2 class="wb-invisible"> Full profile </h2> <!-- Contact Information --> <h3 class="page-header"> Contact information </h3> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Christian Krohn </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> Senior Manager of E-Marketing<br> </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Domestic Sales & Marketing. </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (866) 749-7461 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> ckrohn1@pthealth.ca </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Company Description --> <h3 class="page-header"> Company description </h3> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1995 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> No &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Alternate Industries (NAICS): </strong> </div> <div class="col-md-7"> 621340 - Offices of Physical, Occupational, and Speech Therapists and Audiologists<br> </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Services &nbsp; </div> </div> </section> <!-- Products / Services / Licensing --> <h3 class="page-header"> Product / Service / Licensing </h3> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Service Name: </strong> </div> <div class="col-md-9"> Physiotherapy<br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-12"> At EP Physiotherapy you can expect: <br> <br> Results: Proven, one-to-one, evidence-based therapy <br> <br> Coverage Options: Covered by most insurance plans with minimal out-of-pocket fees <br> <br> Efficient Recovery: We get you back to enjoying a pain free life as quickly as possible <br> <br> Short &amp; Long Term Relief: We focus on the root cause of your pain, not just symptoms <br> <br> Flexible Scheduling: Convenient scheduling around work and home obligations <br> <br> Prevention Strategies: We show you how to keep pain from coming back - on your own <br> <br> Experienced Clinicians: Licensed clinicians who genuinely care about reaching your goals <br> <br> No Wait List: Access to therapy in under 48 hours - normally same day <br> <br> We also offer a convenient no-obligation appointment if you would like to learn more about how we can help without worry of commitment. <br> <br> Tired of living in pain? Consider EP Physiotherapy. We&#39;ve helped thousands of patients across Eastern Passage feel their best again and we&#39;d love the opportunity to do the same for you. <br> <br> We work closely with you to assess and treat your injury, while making your physiotherapy treatment a comfortable and enjoyable experience. We&#39;ll provide you with every tool required to help you make a fast and full recovery! <br> <br> An Array of Insurance Covered Service to Help You Feel Your Best. <br> <br> EP Physiotherapy uses many therapy options to ensure an optimal approach to your care. You will experience a variety of gentle therapy solutions that can help reduce pain, strengthen, add flexibility, improve joint range, and more. Some of our services include: <br> <br> Acupuncture <br> Bracing <br> Chronic Condition Management <br> Compression Garments <br> Ergonomic Assessment <br> Functional Abilities Evaluation (FAE/FCE) <br> Interferential Current (IFC) <br> Intramuscular Stimulation (IMS) <br> Manual Therapy <br> Massage Therapy <br> McKenzie Method <br> Myofascial Release <br> Occupational Therapy <br> Orthotics <br> Physical Demands Analysis <br> Physiotherapy <br> Sport Injury Rehabilitation <br> Transcutaneous Electrical Nerve Stimulation (TENS) <br> Ultrasound (Therapeutic) <br> Work Conditioning<br> <br> </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Technology Profile --> <!-- Market Profile --> <!-- Sector Information --> <details class="mrgn-tp-md mrgn-bttm-md"> <summary> Third-Party Information Liability Disclaimer </summary> <p> Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements. </p> </details> </details> <details id="details-panel2"> <summary> Contacts </summary> <h2 class="wb-invisible"> Contact information </h2> <!-- Contact Information --> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Christian Krohn </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> Senior Manager of E-Marketing<br> </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Domestic Sales & Marketing. </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (866) 749-7461 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> ckrohn1@pthealth.ca </div> </div> </section> </details> <details id="details-panel3"> <summary> Description </summary> <h2 class="wb-invisible"> Company description </h2> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1995 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> No &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Alternate Industries (NAICS): </strong> </div> <div class="col-md-7"> 621340 - Offices of Physical, Occupational, and Speech Therapists and Audiologists<br> </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Services &nbsp; </div> </div> </section> </details> <details id="details-panel4"> <summary> Products, services and licensing </summary> <h2 class="wb-invisible"> Product / Service / Licensing </h2> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Service Name: </strong> </div> <div class="col-md-9"> Physiotherapy<br> </div> </div> <div class="row mrgn-bttm-md"> <div class="col-md-12"> At EP Physiotherapy you can expect: <br> <br> Results: Proven, one-to-one, evidence-based therapy <br> <br> Coverage Options: Covered by most insurance plans with minimal out-of-pocket fees <br> <br> Efficient Recovery: We get you back to enjoying a pain free life as quickly as possible <br> <br> Short &amp; Long Term Relief: We focus on the root cause of your pain, not just symptoms <br> <br> Flexible Scheduling: Convenient scheduling around work and home obligations <br> <br> Prevention Strategies: We show you how to keep pain from coming back - on your own <br> <br> Experienced Clinicians: Licensed clinicians who genuinely care about reaching your goals <br> <br> No Wait List: Access to therapy in under 48 hours - normally same day <br> <br> We also offer a convenient no-obligation appointment if you would like to learn more about how we can help without worry of commitment. <br> <br> Tired of living in pain? Consider EP Physiotherapy. We&#39;ve helped thousands of patients across Eastern Passage feel their best again and we&#39;d love the opportunity to do the same for you. <br> <br> We work closely with you to assess and treat your injury, while making your physiotherapy treatment a comfortable and enjoyable experience. We&#39;ll provide you with every tool required to help you make a fast and full recovery! <br> <br> An Array of Insurance Covered Service to Help You Feel Your Best. <br> <br> EP Physiotherapy uses many therapy options to ensure an optimal approach to your care. You will experience a variety of gentle therapy solutions that can help reduce pain, strengthen, add flexibility, improve joint range, and more. Some of our services include: <br> <br> Acupuncture <br> Bracing <br> Chronic Condition Management <br> Compression Garments <br> Ergonomic Assessment <br> Functional Abilities Evaluation (FAE/FCE) <br> Interferential Current (IFC) <br> Intramuscular Stimulation (IMS) <br> Manual Therapy <br> Massage Therapy <br> McKenzie Method <br> Myofascial Release <br> Occupational Therapy <br> Orthotics <br> Physical Demands Analysis <br> Physiotherapy <br> Sport Injury Rehabilitation <br> Transcutaneous Electrical Nerve Stimulation (TENS) <br> Ultrasound (Therapeutic) <br> Work Conditioning<br> <br> </div> </div> </section> </details> </div> </div> <div class="row"> <div class="col-md-12 text-right"> Last Update Date 2014-04-10 </div> </div> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z --> <!-- End Body Content --> <!-- Begin Body Foot --> <!-- End Body Foot --> <!-- END MAIN TABLE --> <!-- End body --> <!-- Begin footer --> <div class="row pagedetails"> <div class="col-sm-5 col-xs-12 datemod"> <dl id="wb-dtmd"> <dt class=" hidden-print">Date Modified:</dt> <dd class=" hidden-print"> <span><time>2017-03-02</time></span> </dd> </dl> </div> <div class="clear visible-xs"></div> <div class="col-sm-4 col-xs-6"> </div> <div class="col-sm-3 col-xs-6 text-right"> </div> <div class="clear visible-xs"></div> </div> </main> <footer role="contentinfo" id="wb-info"> <nav role="navigation" class="container wb-navcurr"> <h2 class="wb-inv">About government</h2> <!-- EPIC FOOTER BEGIN --> <!-- EPI-11638 Contact us --> <ul class="list-unstyled colcount-sm-2 colcount-md-3"> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&amp;from=Industries">Contact us</a></li> <li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li> <li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li> <li><a href="https://www.canada.ca/en/news.html">News</a></li> <li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li> <li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li> <li><a href="http://pm.gc.ca/eng">Prime Minister</a></li> <li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li> <li><a href="http://open.canada.ca/en/">Open government</a></li> </ul> </nav> <div class="brand"> <div class="container"> <div class="row"> <nav class="col-md-10 ftr-urlt-lnk"> <h2 class="wb-inv">About this site</h2> <ul> <li><a href="https://www.canada.ca/en/social.html">Social media</a></li> <li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li> <li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li> </ul> </nav> <div class="col-xs-6 visible-sm visible-xs tofpg"> <a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a> </div> <div class="col-xs-6 col-md-2 text-right"> <object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object> </div> </div> </div> </div> </footer> <!--[if gte IE 9 | !IE ]><!--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script> <!--<![endif]--> <!--[if lt IE 9]> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script> <![endif]--> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script> <!-- EPI-10519 --> <span class="wb-sessto" data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span> <script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script> <!-- EPI-11190 - Webtrends --> <script src="/eic/home.nsf/js/webtrends.js"></script> <script>var endTime = new Date();</script> <noscript> <div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&amp;WT.js=No&amp;WT.tv=9.4.0&amp;dcssip=www.ic.gc.ca"/></div> </noscript> <!-- /Webtrends --> <!-- JS deps --> <script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script> <!-- EPI-11262 - Util JS --> <script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script> <!-- EPI-11383 --> <script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script> <span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span> </body></html> <!-- End Footer --> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z -->
{ "content_hash": "eb0fbd46aeb294aaccd4f42b80d6da9c", "timestamp": "", "source": "github", "line_count": 2354, "max_line_length": 450, "avg_line_length": 16.579014443500427, "alnum_prop": 0.4778486688702693, "repo_name": "GoC-Spending/data-corporations", "id": "b3ae91b1228f882fe34e3ac543ebc0c0de2ce250", "size": "39052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/234567149103.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2475938634" }, { "name": "JavaScript", "bytes": "11415" } ], "symlink_target": "" }
package com.udacity.bakingtime.injector.components; import com.udacity.bakingtime.injector.PerFragment; import com.udacity.bakingtime.recipelist.RecipeListActivity; import com.udacity.bakingtime.recipedetail.RecipeDetailActivity; import com.udacity.bakingtime.recipedetail.ingredientlist.RecipeIngredientListFragment; import com.udacity.bakingtime.recipedetail.stepdetail.RecipeStepDetailFragment; import com.udacity.bakingtime.recipedetail.steplist.RecipeStepListFragment; import com.udacity.bakingtime.recipelistinator.RecipeListinatorFragment; import com.udacity.bakingtime.widget.RecipeIngredientListViewService; import com.udacity.bakingtime.widget.RecipeShortcutWidgetProvider; import dagger.Component; @PerFragment @Component(dependencies = ApplicationComponent.class) public interface FragmentComponent { void inject(RecipeDetailActivity fragment); void inject(RecipeListActivity fragment); void inject(RecipeStepListFragment fragment); void inject(RecipeIngredientListFragment fragment); void inject(RecipeStepDetailFragment fragment); void inject(RecipeListinatorFragment fragment); void inject(RecipeShortcutWidgetProvider recipeShortcutWidgetProvider); void inject(RecipeIngredientListViewService.WidgetRemoteViewsFactory widgetRemoteViewsFactory); }
{ "content_hash": "323fcc283870c3d0ecc493d4bf20dc21", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 99, "avg_line_length": 38.411764705882355, "alnum_prop": 0.8575803981623277, "repo_name": "luanalbineli/baking-time", "id": "8b85181b766429c45b58d2141adebe0b1c7f979e", "size": "1306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/udacity/bakingtime/injector/components/FragmentComponent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "153249" } ], "symlink_target": "" }
package org.apache.arrow.gandiva.evaluator; import org.apache.arrow.gandiva.ipc.GandivaTypes.SelectionVectorType; import org.apache.arrow.memory.ArrowBuf; /** * Selection vector with records of arrow type INT16. */ public class SelectionVectorInt16 extends SelectionVector { public SelectionVectorInt16(ArrowBuf buffer) { super(buffer); } @Override public int getRecordSize() { return 2; } @Override public SelectionVectorType getType() { return SelectionVectorType.SV_INT16; } @Override public int getIndex(int index) { checkReadBounds(index); char value = getBuffer().getChar(index * getRecordSize()); return (int) value; } }
{ "content_hash": "861be10d34aca97a992a2e145caada6d", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 69, "avg_line_length": 20.147058823529413, "alnum_prop": 0.7255474452554744, "repo_name": "icexelloss/arrow", "id": "84c795b67027c9267f08971a699f499a315a479e", "size": "1485", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "java/gandiva/src/main/java/org/apache/arrow/gandiva/evaluator/SelectionVectorInt16.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "3709" }, { "name": "Batchfile", "bytes": "31136" }, { "name": "C", "bytes": "1303179" }, { "name": "C#", "bytes": "1029129" }, { "name": "C++", "bytes": "24357294" }, { "name": "CMake", "bytes": "707501" }, { "name": "Cython", "bytes": "1546990" }, { "name": "Dockerfile", "bytes": "144408" }, { "name": "Emacs Lisp", "bytes": "1064" }, { "name": "FreeMarker", "bytes": "2312" }, { "name": "Go", "bytes": "4254915" }, { "name": "HTML", "bytes": "3430" }, { "name": "Java", "bytes": "6990057" }, { "name": "JavaScript", "bytes": "127157" }, { "name": "Jinja", "bytes": "19371" }, { "name": "Lua", "bytes": "8771" }, { "name": "MATLAB", "bytes": "40399" }, { "name": "Makefile", "bytes": "31661" }, { "name": "Meson", "bytes": "69508" }, { "name": "Objective-C++", "bytes": "11472" }, { "name": "Perl", "bytes": "3803" }, { "name": "Python", "bytes": "3019333" }, { "name": "R", "bytes": "1508383" }, { "name": "Ruby", "bytes": "1596677" }, { "name": "Shell", "bytes": "385605" }, { "name": "Thrift", "bytes": "34246" }, { "name": "TypeScript", "bytes": "1075563" }, { "name": "Vala", "bytes": "24798" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_75) on Tue May 19 17:15:49 PDT 2015 --> <title>Uses of Class org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter (Hadoop 2.6.0-mr1-cdh5.4.2 API)</title> <meta name="date" content="2015-05-19"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter (Hadoop 2.6.0-mr1-cdh5.4.2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.html" title="class in org.apache.hadoop.mapreduce.lib.output">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/output/class-use/FileOutputCommitter.html" target="_top">Frames</a></li> <li><a href="FileOutputCommitter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter" class="title">Uses of Class<br>org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter</h2> </div> <div class="classUseContainer">No usage of org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.html" title="class in org.apache.hadoop.mapreduce.lib.output">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/output/class-use/FileOutputCommitter.html" target="_top">Frames</a></li> <li><a href="FileOutputCommitter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2009 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "4367be2e69955fc69529acab65724b1d", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 179, "avg_line_length": 39.741379310344826, "alnum_prop": 0.618004338394794, "repo_name": "ZhangXFeng/hadoop", "id": "c9ecd96ab693298a2718e6e0e75853f7a869ac3e", "size": "4610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "share/doc/hadoop-mapreduce1/api/org/apache/hadoop/mapreduce/lib/output/class-use/FileOutputCommitter.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "189381" }, { "name": "Batchfile", "bytes": "215694" }, { "name": "C", "bytes": "3575939" }, { "name": "C++", "bytes": "2163041" }, { "name": "CMake", "bytes": "100256" }, { "name": "CSS", "bytes": "621096" }, { "name": "HTML", "bytes": "96504707" }, { "name": "Java", "bytes": "111573402" }, { "name": "JavaScript", "bytes": "228374" }, { "name": "Makefile", "bytes": "7278" }, { "name": "Objective-C", "bytes": "118273" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "187872" }, { "name": "Protocol Buffer", "bytes": "561225" }, { "name": "Python", "bytes": "1166492" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "912677" }, { "name": "Smalltalk", "bytes": "56562" }, { "name": "TeX", "bytes": "45082" }, { "name": "Thrift", "bytes": "3965" }, { "name": "XSLT", "bytes": "183042" } ], "symlink_target": "" }
package cromwell.backend.impl.tes /** * GRANULAR: The TES payload will list outputs individually in the outputs section of the payload * ROOT: The TES payload will list only the root execution directory in the outputs section of the payload */ object OutputMode extends Enumeration { type OutputMode = Value val GRANULAR, ROOT = Value }
{ "content_hash": "3181018fa5b889668b2748d8973e469d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 107, "avg_line_length": 34.8, "alnum_prop": 0.764367816091954, "repo_name": "broadinstitute/cromwell", "id": "11c6a577bce9bb28d5024c8b51d1361ca6fb4718", "size": "348", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "supportedBackends/tes/src/main/scala/cromwell/backend/impl/tes/OutputMode.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Common Workflow Language", "bytes": "900516" }, { "name": "Dockerfile", "bytes": "2932" }, { "name": "HTML", "bytes": "11173" }, { "name": "Java", "bytes": "1197857" }, { "name": "JavaScript", "bytes": "540512" }, { "name": "Python", "bytes": "109340" }, { "name": "Scala", "bytes": "7699420" }, { "name": "Shell", "bytes": "198407" }, { "name": "wdl", "bytes": "980982" } ], "symlink_target": "" }
================ Style Guidelines ================ Before contributing code or documentation to the mtools project, please familiarize yourself with these style guidelines. Code guidelines ~~~~~~~~~~~~~~~ mtools is not overly prescriptive in terms of style: readability and functionality are the main guiding principles. As a general rule, follow the style used elsewhere in the code and always add meaningful comments. If you implement a new feature anywhere in mlaunch, please write a test function or test class for the feature and document it. PEP 8 ----- mtools adheres to most of the standard Python guidelines provided in `PEP 8 <https://www.python.org/dev/peps/pep-0008/>`__, with the main exception being that mixedCase function and variable names are permitted in order to match usage in MongoDB (for example ``serverStatus``). `flake8 <http://flake8.pycqa.org/en/latest/>`__ is used for style checking. Import order ------------ To improve readability, imports are sorted alphabetically by type of import. `isort <https://readthedocs.org/projects/isort/>`__ is used for import structure checking. Docstrings (PEP 257) -------------------- Please add a descriptive docstring to all new modules, classes, and functions. `pydocstyle <http://www.pydocstyle.org>`__ is used to check docstrings comply with `PEP 257 <https://www.python.org/dev/peps/pep-0257/>`__. Documentation guidelines ~~~~~~~~~~~~~~~~~~~~~~~~ mtools documentation is written in `reStructuredText <http://www.sphinx-doc.org/en/stable/rest.html>`__ and built using `Sphinx <http://www.sphinx-doc.org/en/stable/index.html>`__. The mtools documentation uses only standard RST and Sphinx syntax. As a general rule, follow the style used in the rest of the documentation. Indentation ----------- Indent 3 spaces. Line length ----------- Limit all lines to 79 characters. Exceptions: - code blocks - URLs Code blocks ----------- Use the ``code-block`` directive and specify the language. For example: .. code-block:: text .. code-block:: python import re
{ "content_hash": "6435c2db4f7755dc5c71d7e6136f3c29", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 79, "avg_line_length": 26.435897435897434, "alnum_prop": 0.7138700290979632, "repo_name": "rueckstiess/mtools", "id": "0ccb07b3757acf15273f1c3e911add1187035604", "size": "2062", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "doc/style.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "672" }, { "name": "Python", "bytes": "548352" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ce540929cda1191e0cb716c92eb781a7", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "8ffc71521f89cc07682f61bb482e26a5b5e44020", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Chromista/Ochrophyta/Phaeophyceae/Laminariales/Chordaceae/Chorda/Chorda filum/ Syn. Chorda filum pumila/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Acf\DataBundle\Repository; use Acf\DataBundle\Entity\AoCateg; use Doctrine\ORM\EntityRepository; /** * AoSubCategRepository * This class was generated by the Doctrine ORM. * Add your own custom * repository methods below. */ class AoSubCategRepository extends EntityRepository { /** * Get Query for All Entities * * @return \Doctrine\ORM\Query */ public function getAllQuery() { $qb = $this->createQueryBuilder('sc') ->orderBy('sc.priority', 'ASC') ->addOrderBy('sc.ref', 'ASC'); $query = $qb->getQuery(); return $query; } /** * Get All Entities * * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL */ public function getAll() { return $this->getAllQuery()->execute(); } /** * Get Query for All Entities * * @param AoCateg $categ * * @return \Doctrine\ORM\Query */ public function getAllByCategQuery(AoCateg $categ) { $qb = $this->createQueryBuilder('sc') ->join('sc.categ', 'c') ->where('c.id = :id') ->orderBy('sc.priority', 'ASC') ->addOrderBy('sc.ref', 'ASC') ->setParameter('id', $categ->getId()); $query = $qb->getQuery(); return $query; } /** * Get All Entities * * @param AoCateg $categ * * @return mixed|\Doctrine\DBAL\Driver\Statement|array|NULL */ public function getAllByCateg(AoCateg $categ) { return $this->getAllByCategQuery($categ)->execute(); } }
{ "content_hash": "e18066c634ac155139d1978cb93bf28a", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 63, "avg_line_length": 22.10958904109589, "alnum_prop": 0.5594795539033457, "repo_name": "sasedev/acf-expert", "id": "4338dcfbce9536427b11f0bebe6ff5ed2dfe5c49", "size": "1614", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Acf/DataBundle/Repository/AoSubCategRepository.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "690156" }, { "name": "CoffeeScript", "bytes": "50493" }, { "name": "HTML", "bytes": "2095168" }, { "name": "JavaScript", "bytes": "9978754" }, { "name": "Makefile", "bytes": "743" }, { "name": "PHP", "bytes": "4506157" }, { "name": "PLpgSQL", "bytes": "92638" }, { "name": "Shell", "bytes": "960" } ], "symlink_target": "" }
var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../demo-dist/index.html'), assetsRoot: path.resolve(__dirname, '../demo-dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./dev.env'), port: 9000, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
{ "content_hash": "ccc5e402294a12756c4f0ba121778106", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 71, "avg_line_length": 35.096774193548384, "alnum_prop": 0.6599264705882353, "repo_name": "dattn/vue-map", "id": "456f19d02ba94e1383342ff694e8f587dc241c52", "size": "1155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "195" }, { "name": "JavaScript", "bytes": "25868" }, { "name": "Vue", "bytes": "6886" } ], "symlink_target": "" }
package demo.pages import chandu0101.scalajs.react.components.WithAsyncScript import demo.components.LeftNavPage import demo.routes.LeftRoute import demo.routes.SuiRouteModule import japgolly.scalajs.react._ import japgolly.scalajs.react.vdom.html_<^._ import japgolly.scalajs.react.extra.router.RouterCtl object SuiPage { case class Props(selectedPage: LeftRoute, ctrl: RouterCtl[LeftRoute]) case class Backend($ : BackendScope[Props, _]) { def render(P: Props) = WithAsyncScript("assets/semantic_ui-bundle.js") { LeftNavPage(SuiRouteModule.menu, P.selectedPage, P.ctrl) } } val component = ScalaComponent .builder[Props]("SuiPage") .renderBackend[Backend] .build def apply(selectedPage: LeftRoute, ctrl: RouterCtl[LeftRoute]) = component(Props(selectedPage, ctrl)) }
{ "content_hash": "d11a2a4d5fef686e2e558af8e8689b1c", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 71, "avg_line_length": 28.448275862068964, "alnum_prop": 0.7466666666666667, "repo_name": "rleibman/scalajs-react-components", "id": "311bc47f20ce8aa0a9fb1b532a648873b50ccf90", "size": "825", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/src/main/scala/demo/pages/SuiPage.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "583605" }, { "name": "Shell", "bytes": "666" } ], "symlink_target": "" }
using std::vector; #include <utility> using std::pair; #include <math.h> #include <string.h> namespace ASAPSPACE { PyAsap_NeighborLocatorObject *PyAsap_NewNeighborList(Atoms *atoms, double rCut, double driftfactor); class NeighborList : public NeighborLocator { protected: /// Generate a neighbor list for atoms a with cutoff rCut. /// The neighbor list will contain all neighbors within the distance /// rCut. The neighborlist can be reused until an atom has moved /// more than rCut*driftfactor. NeighborList(Atoms *a, double rCut, double driftfactor); virtual ~NeighborList(); friend ASAPSPACE::PyAsap_NeighborLocatorObject *PyAsap_NewNeighborList(Atoms *atoms, double rCut, double driftfactor); friend void PyAsap_Dealloc<PyAsap_NeighborLocatorObject>(PyObject *self); public: /// Enable full neighbor lists by calling this just after the constructor void EnableFullNeighborLists(); /// Check if full lists are enabled bool HasFullNeighborLists() const {return fulllists;} /// Get wrapped positions of all the atoms const vector<Vec> &GetWrappedPositions() const {return cells->GetWrappedPositions();} void GetWrappedPositions(vector<Vec> &wp) const {cells->GetWrappedPositions(wp);} /// Get scaled positions of all the atoms const vector<Vec> &GetScaledPositions() const {return cells->GetScaledPositions();} /// Check the neighbor list. /// /// Check if the neighbor list can still be reused, return true if /// it should be updated. virtual bool CheckNeighborList(); /// Update neighbor list virtual void UpdateNeighborList(); /// Check if the neighbor list can still be reused, update if not. bool CheckAndUpdateNeighborList(); /// Check if the neighbor list can still be reused, update if not. /// /// This version is used when called from Python virtual bool CheckAndUpdateNeighborList(PyObject *atoms); /// Get information about the neighbors of atom n ("half" neighbor list) /// /// Input values: n is the number of the atom. r (optional) is a /// cutoff, must be less than rCut in the constructor (not /// checked!). /// /// In-out values: size contains the maximum space in the arrays. /// It is decremented by the number of neighbors placed in the /// arrays. It is an error to call GetNeighbors with too small a /// value of size. /// /// Out values: neighbors[] contains the numbers of the atoms, /// diffs[] contains the \em relative positions of the atoms, /// diffs2[] contains the norms of the diffs vectors. /// /// Return value: The number of neighbors. virtual int GetNeighbors(int n, int *neighbors, Vec *diffs, double *diffs2, int& size, double r = -1.0) const; /// Get information about the neighbors of atom n ("half" neighbor list) /// /// This version of GetNeighbors only returns the numbers of the neighbors. /// It is intended for the Python interface. virtual void GetNeighbors(int n, vector<int> &neighbors) const; /// GetFullNeighbors is as GetNeighbors, but return a full list int GetFullNeighbors(int n, int *neighbors, Vec *diffs, double *diffs2, int& size, double r = -1.0) const; /// Get information about the neighbors of atom n (full neighbor list) /// /// This version of GetNeighbors only returns the numbers of the neighbors. /// It is intended for the Python interface. void GetFullNeighbors(int n, vector<int> &neighbors) const; /// Return the guaranteed maximal length of a single atom's NB list. /// Call this before using GetNeighbors() to make sure the arrays /// are big enough. The value may change when the neighbor list is /// updated. int MaxNeighborListLength() const {return maxLength;} /// Get the number of atoms in the corresponding list of atoms. int GetNumberOfAtoms() const {return nAtoms;} // Used by interface. /// Return the cutoff distance (rCut) specified when creating this nblist. double GetCutoffRadius() const {return rCut;} /// Return the cutoff distance including twice the drift. double GetCutoffRadiusWithDrift() const {return rCut + 2*drift;} /// Remake the list for one or more atoms that have moved. /// /// Their neighbor's lists will also be remade, their identities /// will be reported in the set 'affected'. void RemakeLists(const set<int> &modified, set<int> &affected); /// Test the partial remaking of lists. NEVER CALL ON IN-USE NB LIST! /// /// This function is the Python interface to RemakeLists. It should /// only be called directly for testing purposes. Calling it on a /// neighbor list used by a potential will lead to INCORRECT /// energies and forces! int TestPartialUpdate(set<int> modified, PyObject *pyatoms); /// Normalize the positions and calculate scaled space version /// /// This is used when a neighbor list is updated void ScaleAndNormalizePositions(); /// Normalize some positions and calculate scaled space version /// /// The first argument is a set of atoms to be normalized, the /// corresponding scaled positions are placed in scaledpos. void ScaleAndNormalizePositions(const set<int> &modified, vector<Vec> &scaledpos); /// Return the atoms access object. Used by a few tool functions. virtual Atoms *GetAtoms() const {return atoms;} string GetName() const {return "NeighborList";} /// Print internal info about an atom virtual void print_info(int n); /// Print memory usage virtual long PrintMemory() const; protected: /// Generate a new neighbor list. virtual void MakeList(); /// Make the lists of neighboring cells. void MakeNeighboringCellLists(); void CheckFullListConsistency(const string where, bool chkdst = true); void printlist(int n) const; double GetMaxStrainDisplacement(); protected: Atoms *atoms; ///< A pointer to the atoms. int nAtoms; ///< The number of atoms excluding ghosts. int nAllAtoms; ///< The number of atoms including ghosts. double rCut; ///< The cutoff radius. double rCut2; ///< The square of the cutoff radius. double drift; ///< The maximally allowed drift of an atom. double drift2; ///< The square of the maximally allowed drift of an atom. int maxLength; ///< The lenght of the longest neighbor list. bool firsttime; ///< True during the very first update. bool fulllists; ///< True if full neighbor lists are supported. bool pbc[3]; ///< Boundary conditions at last update. Vec storedSuperCell[3]; ///< So full neighbor list can be accessed. Vec referenceSuperCell[3]; ///< For detecting shape changes. /// Cell locator used when constructing the neighbor list. NeighborCellLocator *cells; PyObject *cells_obj; /// Table of possible translation vectors vector<IVec> translationTable; /// The actual neigbor list (half list) vector< vector< pair<int, translationsidx_t> > > nbList; /// The complementary neighbor list if full lists are enabled. vector< vector< pair<int, translationsidx_t> > > complNbList; }; } // end namespace #endif // NEIGHBORLIST2
{ "content_hash": "026e53b6a9521cd46c7df714fe21cdc8", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 86, "avg_line_length": 36.17766497461929, "alnum_prop": 0.7096955240634208, "repo_name": "auag92/n2dm", "id": "35031d14d1e19e5312fd38aeadb94fc96806ed1e", "size": "8793", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Asap-3.8.4/Basics/NeighborList.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4529" }, { "name": "C++", "bytes": "1472384" }, { "name": "CSS", "bytes": "5059" }, { "name": "Jupyter Notebook", "bytes": "7328" }, { "name": "Makefile", "bytes": "86067" }, { "name": "Matlab", "bytes": "87" }, { "name": "Python", "bytes": "1232765" }, { "name": "Shell", "bytes": "13226" }, { "name": "Smarty", "bytes": "4212" }, { "name": "TeX", "bytes": "5561" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EPOS { public partial class Discount : Form { List<ListObject> theList = new List<ListObject>(); public Discount() { InitializeComponent(); } private void Discount_Load(object sender, EventArgs e) { this.TopMost = true; this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; Recolor(); fillbox(); } private void Recolor() { Globals.GetColors(); BackColor = Color.FromName(Globals.Backcolor); labelName.Text = Globals.Pubname; foreach (Control c in this.Controls) { Globals.UpdateColorControls(c); } } private void fillbox() { listBox1.DataSource = null; listBox1.Items.Clear(); theList.Clear(); SqlConnection discount = new SqlConnection(Globals.dataconnection); SqlCommand show = new SqlCommand("SELECT DiscountID, Name FROM Discount ORDER BY Name", discount); discount.Open(); SqlDataReader reader = show.ExecuteReader(); while (reader.Read()) { theList.Add(new ListObject(reader.GetString(1), reader.GetInt32(0))); } discount.Close(); listBox1.DataSource = theList; listBox1.DisplayMember = "Name"; listBox1.ValueMember = "ID"; listBox1.SelectedIndex = -1; } private void timer1_Tick(object sender, EventArgs e) { labelDate.Text = DateTime.Now.ToString("MMMM dd, yyyy") + Environment.NewLine + DateTime.Now.ToString("HH:mm:ss"); } private void buttonBack_Click(object sender, EventArgs e) { this.Close(); } private void buttonEdit_Click(object sender, EventArgs e) { if (listBox1.SelectedIndex != -1) { Globals.IDNo = int.Parse(listBox1.SelectedValue.ToString()); AddEditDiscount addedit = new AddEditDiscount(); addedit.ShowDialog(); fillbox(); } else { MessageBox.Show("Please select a discount from the list"); } } private void buttonDelete_Click(object sender, EventArgs e) { if (listBox1.SelectedIndex != -1) { DialogResult dr = MessageBox.Show("Are you sure you want to delete this discount?", "Delete?", MessageBoxButtons.YesNo); switch (dr) { case DialogResult.Yes: int id = int.Parse(listBox1.SelectedValue.ToString()); SqlConnection cat = new SqlConnection(Globals.dataconnection); cat.Open(); SqlCommand delete = new SqlCommand("DELETE FROM Discount WHERE DiscountID = @id", cat); delete.Parameters.AddWithValue("@id", id); delete.ExecuteNonQuery(); cat.Close(); break; case DialogResult.No: break; } } else { MessageBox.Show("Please select a discount from the list"); } fillbox(); } private void buttonAdd_Click(object sender, EventArgs e) { Globals.IDNo = -1; AddEditDiscount addedit = new AddEditDiscount(); addedit.ShowDialog(); fillbox(); } } }
{ "content_hash": "1610fa98af0832d633aac325ee43f1f1", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 126, "avg_line_length": 33.108333333333334, "alnum_prop": 0.5285678328718852, "repo_name": "JoeBurnside/FinalYearProject", "id": "770a22512f4f3873c35345a7db99d2c82eda9d25", "size": "3975", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EPOS/Discount.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "180399" } ], "symlink_target": "" }
package org.apache.sysds.hops.estim; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.apache.commons.math3.random.Well1024a; import org.apache.sysds.hops.OptimizerUtils; import org.apache.sysds.runtime.data.DenseBlock; import org.apache.sysds.runtime.data.SparseBlock; import org.apache.sysds.runtime.matrix.data.MatrixBlock; import org.apache.sysds.runtime.meta.DataCharacteristics; import org.apache.sysds.runtime.meta.MatrixCharacteristics; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * This estimator implements an approach based on a so-called layered graph, * introduced in * Edith Cohen. Structure prediction and computation of sparse matrix * products. J. Comb. Optim., 2(4):307–332, 1998. * */ public class EstimatorLayeredGraph extends SparsityEstimator { private static final int ROUNDS = 32; private final int _rounds; public EstimatorLayeredGraph() { this(ROUNDS); } public EstimatorLayeredGraph(int rounds) { _rounds = rounds; } @Override public DataCharacteristics estim(MMNode root) { List<MatrixBlock> leafs = getMatrices(root, new ArrayList<>()); long nnz = new LayeredGraph(leafs, _rounds).estimateNnz(); return root.setDataCharacteristics(new MatrixCharacteristics( leafs.get(0).getNumRows(), leafs.get(leafs.size()-1).getNumColumns(), nnz)); } @Override public double estim(MatrixBlock m1, MatrixBlock m2, OpCode op) { if( op == OpCode.MM ) return estim(m1, m2); throw new NotImplementedException(); } @Override public double estim(MatrixBlock m, OpCode op) { throw new NotImplementedException(); } @Override public double estim(MatrixBlock m1, MatrixBlock m2) { LayeredGraph graph = new LayeredGraph(Arrays.asList(m1,m2), _rounds); return OptimizerUtils.getSparsity( m1.getNumRows(), m2.getNumColumns(), graph.estimateNnz()); } private List<MatrixBlock> getMatrices(MMNode node, List<MatrixBlock> leafs) { //NOTE: this extraction is only correct and efficient for chains, no DAGs if( node.isLeaf() ) leafs.add(node.getData()); else { getMatrices(node.getLeft(), leafs); getMatrices(node.getRight(), leafs); } return leafs; } public static class LayeredGraph { private final List<Node[]> _nodes; //nodes partitioned by graph level private final int _rounds; //length of propagated r-vectors public LayeredGraph(List<MatrixBlock> chain, int r) { _nodes = new ArrayList<>(); _rounds = r; chain.forEach(i -> buildNext(i)); } public void buildNext(MatrixBlock mb) { if( mb.isEmpty() ) return; final int m = mb.getNumRows(); final int n = mb.getNumColumns(); //step 1: create node arrays for rows/cols Node[] rows = null, cols = null; if( _nodes.size() == 0 ) { rows = new Node[m]; for(int i=0; i<m; i++) rows[i] = new Node(); _nodes.add(rows); } else { rows = _nodes.get(_nodes.size()-1); } cols = new Node[n]; for(int j=0; j<n; j++) cols[j] = new Node(); _nodes.add(cols); //step 2: create edges for non-zero values if( mb.isInSparseFormat() ) { SparseBlock a = mb.getSparseBlock(); for(int i=0; i < m; i++) { if( a.isEmpty(i) ) continue; int apos = a.pos(i); int alen = a.size(i); int[] aix = a.indexes(i); for(int k=apos; k<apos+alen; k++) cols[aix[k]].addInput(rows[i]); } } else { //dense DenseBlock a = mb.getDenseBlock(); for (int i=0; i<m; i++) { double[] avals = a.values(i); int aix = a.pos(i); for (int j=0; j<n; j++) if( avals[aix+j] != 0 ) cols[j].addInput(rows[i]); } } } public long estimateNnz() { //step 1: assign random vectors ~exp(lambda=1) to all leaf nodes //(lambda is not the mean, if lambda is 2 mean is 1/2) ExponentialDistribution random = new ExponentialDistribution(new Well1024a(), 1); for( Node n : _nodes.get(0) ) { double[] rvect = new double[_rounds]; for (int g = 0; g < _rounds; g++) rvect[g] = random.sample(); n.setVector(rvect); } //step 2: propagate vectors bottom-up and aggregate nnz return Math.round(Arrays.stream(_nodes.get(_nodes.size()-1)) .mapToDouble(n -> calcNNZ(n.computeVector(_rounds), _rounds)).sum()); } private static double calcNNZ(double[] inpvec, int rounds) { return (inpvec != null && inpvec.length > 0) ? (rounds - 1) / Arrays.stream(inpvec).sum() : 0; } private static class Node { private List<Node> _input = new ArrayList<>(); private double[] _rvect; public List<Node> getInput() { return _input; } @SuppressWarnings("unused") public double[] getVector() { return _rvect; } public void setVector(double[] rvect) { _rvect = rvect; } public void addInput(Node dest) { _input.add(dest); } private double[] computeVector(int rounds) { if( _rvect != null || getInput().isEmpty() ) return _rvect; //recursively compute input vectors List<double[]> ltmp = getInput().stream().map(n -> n.computeVector(rounds)) .filter(v -> v!=null).collect(Collectors.toList()); if( ltmp.isEmpty() ) return null; else if( ltmp.size() == 1 ) return _rvect = ltmp.get(0); else { double[] tmp = ltmp.get(0).clone(); for(int i=1; i<ltmp.size(); i++) { double[] v2 = ltmp.get(i); for(int j=0; j<rounds; j++) tmp[j] = Math.min(tmp[j], v2[j]); } return _rvect = tmp; } } } } }
{ "content_hash": "30e02b557623efc4c662dd4fc7d7d916", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 84, "avg_line_length": 28.414141414141415, "alnum_prop": 0.6473515819409883, "repo_name": "apache/incubator-systemml", "id": "beafb9f81a66da2605b158b197c0c71ad94d2a50", "size": "6435", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/apache/sysds/hops/estim/EstimatorLayeredGraph.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "31285" }, { "name": "Batchfile", "bytes": "22265" }, { "name": "C", "bytes": "8676" }, { "name": "C++", "bytes": "30804" }, { "name": "CMake", "bytes": "10312" }, { "name": "Cuda", "bytes": "30575" }, { "name": "Java", "bytes": "12990600" }, { "name": "Jupyter Notebook", "bytes": "36387" }, { "name": "Makefile", "bytes": "936" }, { "name": "Protocol Buffer", "bytes": "66399" }, { "name": "Python", "bytes": "195969" }, { "name": "R", "bytes": "672462" }, { "name": "Scala", "bytes": "185698" }, { "name": "Shell", "bytes": "152940" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>interval: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+2 / interval - 4.5.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> interval <small> 4.5.2 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-09-10 09:25:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-10 09:25:57 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;guillaume.melquiond@inria.fr&quot; homepage: &quot;https://coqinterval.gitlabpages.inria.fr/&quot; dev-repo: &quot;git+https://gitlab.inria.fr/coqinterval/interval.git&quot; bug-reports: &quot;https://gitlab.inria.fr/coqinterval/interval/issues&quot; license: &quot;CeCILL-C&quot; build: [ [&quot;autoconf&quot;] {dev} [&quot;./configure&quot;] [&quot;./remake&quot; &quot;-j%{jobs}%&quot;] ] install: [&quot;./remake&quot; &quot;install&quot;] depends: [ &quot;coq&quot; {&gt;= &quot;8.8&quot;} &quot;coq-bignums&quot; &quot;coq-flocq&quot; {&gt;= &quot;3.1&quot;} &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.6&quot;} &quot;coq-coquelicot&quot; {&gt;= &quot;3.0&quot;} &quot;conf-autoconf&quot; {build &amp; dev} (&quot;conf-g++&quot; {build} | &quot;conf-clang&quot; {build}) ] tags: [ &quot;keyword:interval arithmetic&quot; &quot;keyword:decision procedure&quot; &quot;keyword:floating-point arithmetic&quot; &quot;keyword:reflexive tactic&quot; &quot;keyword:Taylor models&quot; &quot;category:Mathematics/Real Calculus and Topology&quot; &quot;category:Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; &quot;logpath:Interval&quot; &quot;date:2022-08-25&quot; ] authors: [ &quot;Guillaume Melquiond &lt;guillaume.melquiond@inria.fr&gt;&quot; &quot;Érik Martin-Dorel &lt;erik.martin-dorel@irit.fr&gt;&quot; &quot;Pierre Roux &lt;pierre.roux@onera.fr&gt;&quot; &quot;Thomas Sibut-Pinote &lt;thomas.sibut-pinote@inria.fr&gt;&quot; ] synopsis: &quot;A Coq tactic for proving bounds on real-valued expressions automatically&quot; url { src: &quot;https://coqinterval.gitlabpages.inria.fr/releases/interval-4.5.2.tar.gz&quot; checksum: &quot;sha512=74be5915cb242f3a9fecab6a60d33169ddf20a21dd4479258fe869e59d77e212ec08890864d2adfcc9d27c132a9839b50d88e3d8ba8f791adba4dcc3c067b903&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-interval.4.5.2 coq.8.7.1+2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2). The following dependencies couldn&#39;t be met: - coq-interval -&gt; coq &gt;= 8.8 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-interval.4.5.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "2d1ade6c66990b90e44a536e81fe665e", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 159, "avg_line_length": 42.04812834224599, "alnum_prop": 0.5653058629022002, "repo_name": "coq-bench/coq-bench.github.io", "id": "fb812e9cd94f4e27d7e3eacb072ff1904ece34d1", "size": "7889", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.7.1+2/interval/4.5.2.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#import "SwiffImport.h" #import "SwiffTypes.h" @class SwiffDynamicTextAttributes; @interface SwiffHTMLToCoreTextConverter : NSObject + (id) sharedInstance; - (NSAttributedString *) copyAttributedStringForHTML:(NSString *)string baseAttributes:(SwiffDynamicTextAttributes *)baseAttributes NS_RETURNS_RETAINED; @end
{ "content_hash": "4337a653578ac8b4a8f78466a4c0ca57", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 152, "avg_line_length": 22.928571428571427, "alnum_prop": 0.8099688473520249, "repo_name": "noughts/SwiffCore", "id": "864cd0bca9add17f6b8040e5f126aca9ab258ecd", "size": "1963", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "SwiffCore/Source/SwiffHTMLToCoreTextConverter.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "3148" }, { "name": "JavaScript", "bytes": "2511" }, { "name": "Objective-C", "bytes": "497592" } ], "symlink_target": "" }
/** * Sprint * * @module :: Model * @description :: This model represents project sprint. * @docs :: http://sailsjs.org/#!documentation/models */ "use strict"; var _ = require("lodash"); module.exports = _.merge(_.cloneDeep(require("../services/baseModel")), { attributes: { // Relation to Project model projectId: { type: "integer", required: true }, // Sprint title title: { type: "string", required: true }, // Description of the sprint description: { type: "text", defaultsTo: "" }, // Sprint start date dateStart: { type: "date", required: true }, // Sprint end date dateEnd: { type: "date", required: true }, // Ignore weekends on sprint, this will affect to burndown charts and phase duration calculations ignoreWeekends: { type: "boolean", defaultsTo: false }, // Dynamic data attributes // Note that this doesn't account possible sprint exclude days durationDays: function() { var output = 0; if (this.ignoreWeekends) { var _start = this.dateStartObject().clone(); while (this.dateEndObject().diff(_start, "days") >= 0) { var weekDay = _start.isoWeekday(); if (weekDay !== 6 && weekDay !== 7) { output = output + 1; } _start.add("days", 1); } } else { output = this.dateEndObject().diff(this.dateStartObject(), "days") + 1; } return output; }, dateStartObject: function() { return (this.dateStart && this.dateStart != "0000-00-00") ? DateService.convertDateObjectToUtc(this.dateStart) : null; }, dateEndObject: function() { return (this.dateEnd && this.dateEnd != "0000-00-00") ? DateService.convertDateObjectToUtc(this.dateEnd) : null; } }, // Life cycle callbacks /** * After create callback. * * @param {sails.model.sprint} values * @param {Function} next */ afterCreate: function(values, next) { HistoryService.write("Sprint", values); next(); }, /** * After update callback. * * @param {sails.model.sprint} values * @param {Function} next */ afterUpdate: function(values, next) { HistoryService.write("Sprint", values); next(); }, /** * Before destroy callback. * * @param {{}} terms * @param {Function} next */ beforeDestroy: function(terms, next) { DataService.getSprint(terms, function(error, sprint) { if (!error) { HistoryService.remove("Sprint", sprint.id); // Update all stories sprint id to 0 which belongs to delete sprint Story .update( {sprintId: sprint.id}, {sprintId: 0}, function(error) { if (error) { sails.log.error(__filename + ":" + __line + " [Sprint story updates failed.]"); sails.log.error(error); } next(error); } ); } else { next(error); } }); } });
{ "content_hash": "e71a8b74e1f8828c56f72bd326ffac46", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 107, "avg_line_length": 27.94814814814815, "alnum_prop": 0.452160084813146, "repo_name": "simman/Taskboard", "id": "978fa8a99e1933708ea143d612422ae6a78bbbbf", "size": "3773", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "api/models/Sprint.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "36477" }, { "name": "HTML", "bytes": "1283" }, { "name": "JavaScript", "bytes": "917605" }, { "name": "Shell", "bytes": "3050" } ], "symlink_target": "" }
<?php namespace Illuminate\Queue\Jobs; use Closure; use Illuminate\Container\Container; class SyncJob extends Job { /** * The class name of the job. * * @var string */ protected $job; /** * The queue message data. * * @var string */ protected $data; /** * Create a new job instance. * * @param \Illuminate\Container $container * @param string $job * @param string $data * @return void */ public function __construct(Container $container, $job, $data = '') { $this->job = $job; $this->data = $data; $this->container = $container; } /** * Fire the job. * * @return void */ public function fire() { if ($this->job instanceof Closure) { call_user_func($this->job, $this, $this->data); } else { $this->resolveAndFire(array('job' => $this->job, 'data' => $this->data)); } } /** * Delete the job from the queue. * * @return void */ public function delete() { // } /** * Release the job back into the queue. * * @param int $delay * @return void */ public function release($delay = 0) { // } /** * Get the number of times the job has been attempted. * * @return int */ public function attempts() { return 1; } }
{ "content_hash": "a4b3250f5b0cd471cb978b47a9036621", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 76, "avg_line_length": 15.564705882352941, "alnum_prop": 0.5419501133786848, "repo_name": "tjoskar/odot", "id": "17f24977bf462c0e1969647ae2622cfb2a11381a", "size": "1323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/laravel/framework/src/Illuminate/Queue/Jobs/SyncJob.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1005797" }, { "name": "PHP", "bytes": "755327" }, { "name": "Perl", "bytes": "2791" }, { "name": "Shell", "bytes": "69" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/Bonus.iml" filepath="$PROJECT_DIR$/Bonus.iml" /> </modules> </component> </project>
{ "content_hash": "8b6bb16a60c11efdaf4e18cdb1f577b0", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 92, "avg_line_length": 31.25, "alnum_prop": 0.652, "repo_name": "tcsiwula/java_code", "id": "76f9f9fcb8089cc91ca79f169a98a5909b88a958", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "classes/cs245/project/Bonus/.idea/modules.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "1483189" }, { "name": "Assembly", "bytes": "134524" }, { "name": "Awk", "bytes": "251" }, { "name": "Batchfile", "bytes": "491" }, { "name": "C", "bytes": "103168" }, { "name": "C#", "bytes": "22932" }, { "name": "C++", "bytes": "367" }, { "name": "CMake", "bytes": "1930" }, { "name": "CSS", "bytes": "3886" }, { "name": "Erlang", "bytes": "2303" }, { "name": "GAP", "bytes": "226361" }, { "name": "HTML", "bytes": "2676449" }, { "name": "Java", "bytes": "13914043" }, { "name": "JavaScript", "bytes": "104216" }, { "name": "Lua", "bytes": "278" }, { "name": "M", "bytes": "5739" }, { "name": "Makefile", "bytes": "417" }, { "name": "Matlab", "bytes": "23" }, { "name": "Objective-C", "bytes": "134542" }, { "name": "PHP", "bytes": "8070" }, { "name": "PLSQL", "bytes": "8695" }, { "name": "PLpgSQL", "bytes": "35862" }, { "name": "Pascal", "bytes": "13808" }, { "name": "PowerShell", "bytes": "6138" }, { "name": "Python", "bytes": "8598" }, { "name": "R", "bytes": "61" }, { "name": "Ruby", "bytes": "1715" }, { "name": "SQLPL", "bytes": "31877" }, { "name": "Shell", "bytes": "2317" }, { "name": "Smalltalk", "bytes": "19" }, { "name": "Swift", "bytes": "83207" }, { "name": "TypeScript", "bytes": "1174" }, { "name": "VHDL", "bytes": "401678" }, { "name": "Visual Basic", "bytes": "1564" } ], "symlink_target": "" }
using System; using System.Globalization; using System.Runtime.Serialization; namespace Platinum { /// <summary /> [Serializable] public abstract class ActorException : Exception { /// <summary /> public ActorException( string message ) : base( message ) { } /// <summary /> public ActorException( string message, Exception innerException ) : base( message, innerException ) { } /// <summary /> protected ActorException( SerializationInfo info, StreamingContext context ) : base( info, context ) { } /// <summary> /// Gets the name of the actor which raised the error/exception. /// </summary> public abstract string Actor { get; } /// <summary> /// Gets the error code of the error/exception. /// </summary> public abstract int Code { get; } /// <summary> /// Gets the programmer friendly description of the error/exception. /// </summary> /// <remarks> /// No application/business code should ever make use of this value! If /// conditions exist over errors/exceptions they should make use of the /// .Actor/.Code properties. /// </remarks> public abstract string Description { get; } /// <summary> /// Override the default implementation of .ToString(), so that all /// relevant information is available in the string representation. /// </summary> /// <returns>String representation of error.</returns> public override string ToString() { string s = string.Format( CultureInfo.InvariantCulture, "({0}/{1}) {2} [{3}]", this.Actor, this.Code, this.Description, this.Message ); if ( this.StackTrace != null ) s = s + "\n" + this.StackTrace; if ( this.InnerException != null ) s = s + "\n\n" + this.InnerException.ToString(); return s; } } } /* eof */
{ "content_hash": "f03bc01a86b721f1cdc6eff3946b23f3", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 147, "avg_line_length": 26.023809523809526, "alnum_prop": 0.5338517840805124, "repo_name": "filipetoscano/Platinum", "id": "6152a01798405343ac021c78e5dad8a3780fd839", "size": "2188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Platinum.Core/Exception/ActorException.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "566302" }, { "name": "JavaScript", "bytes": "395" }, { "name": "PLSQL", "bytes": "2197" }, { "name": "PLpgSQL", "bytes": "353" }, { "name": "SQLPL", "bytes": "398" }, { "name": "XSLT", "bytes": "41209" } ], "symlink_target": "" }
package lfs import ( "fmt" "net/http" "net/url" "os" "path" "path/filepath" "regexp" "strconv" "strings" "sync" "github.com/github/git-lfs/git" ) type Configuration struct { CurrentRemote string httpClient *HttpClient redirectingHttpClient *http.Client envVars map[string]string isTracingHttp bool isLoggingStats bool loading sync.Mutex // guards initialization of gitConfig and remotes gitConfig map[string]string remotes []string } type Endpoint struct { Url string SshUserAndHost string SshPath string } var ( Config = NewConfig() httpPrefixRe = regexp.MustCompile("\\Ahttps?://") defaultRemote = "origin" ) func NewConfig() *Configuration { c := &Configuration{ CurrentRemote: defaultRemote, envVars: make(map[string]string), } c.isTracingHttp = c.GetenvBool("GIT_CURL_VERBOSE", false) c.isLoggingStats = c.GetenvBool("GIT_LOG_STATS", false) return c } func (c *Configuration) Getenv(key string) string { if i, ok := c.envVars[key]; ok { return i } v := os.Getenv(key) c.envVars[key] = v return v } // GetenvBool parses a boolean environment variable and returns the result as a bool. // If the environment variable is unset, empty, or if the parsing fails, // the value of def (default) is returned instead. func (c *Configuration) GetenvBool(key string, def bool) bool { s := c.Getenv(key) if len(s) == 0 { return def } b, err := strconv.ParseBool(s) if err != nil { return def } return b } func (c *Configuration) Endpoint() Endpoint { if url, ok := c.GitConfig("lfs.url"); ok { return NewEndpoint(url) } if len(c.CurrentRemote) > 0 && c.CurrentRemote != defaultRemote { if endpoint := c.RemoteEndpoint(c.CurrentRemote); len(endpoint.Url) > 0 { return endpoint } } return c.RemoteEndpoint(defaultRemote) } func (c *Configuration) ConcurrentTransfers() int { uploads := 3 if v, ok := c.GitConfig("lfs.concurrenttransfers"); ok { n, err := strconv.Atoi(v) if err == nil && n > 0 { uploads = n } } return uploads } func (c *Configuration) BatchTransfer() bool { if v, ok := c.GitConfig("lfs.batch"); ok { if v == "true" || v == "" { return true } // Any numeric value except 0 is considered true if n, err := strconv.Atoi(v); err == nil && n != 0 { return true } } return false } func (c *Configuration) RemoteEndpoint(remote string) Endpoint { if len(remote) == 0 { remote = defaultRemote } if url, ok := c.GitConfig("remote." + remote + ".lfsurl"); ok { return NewEndpoint(url) } if url, ok := c.GitConfig("remote." + remote + ".url"); ok { return NewEndpointFromCloneURL(url) } return Endpoint{} } const ENDPOINT_URL_UNKNOWN = "<unknown>" // Create a new endpoint from a URL associated with a git clone URL // The difference to NewEndpoint is that it appends [.git]/info/lfs to the URL since it // is the clone URL func NewEndpointFromCloneURL(url string) Endpoint { e := NewEndpoint(url) if e.Url != ENDPOINT_URL_UNKNOWN { // When using main remote URL for HTTP, append info/lfs if path.Ext(url) == ".git" { e.Url += "/info/lfs" } else { e.Url += ".git/info/lfs" } } return e } // Create a new endpoint from a general URL func NewEndpoint(url string) Endpoint { e := Endpoint{Url: url} if !httpPrefixRe.MatchString(url) { pieces := strings.SplitN(url, ":", 2) hostPieces := strings.SplitN(pieces[0], "@", 2) if len(hostPieces) == 2 { e.SshUserAndHost = pieces[0] e.SshPath = pieces[1] e.Url = fmt.Sprintf("https://%s/%s", hostPieces[1], pieces[1]) } } return e } func (c *Configuration) Remotes() []string { c.loadGitConfig() return c.remotes } func (c *Configuration) GitConfig(key string) (string, bool) { c.loadGitConfig() value, ok := c.gitConfig[strings.ToLower(key)] return value, ok } func (c *Configuration) SetConfig(key, value string) { c.loadGitConfig() c.gitConfig[key] = value } func (c *Configuration) ObjectUrl(oid string) (*url.URL, error) { return ObjectUrl(c.Endpoint(), oid) } func ObjectUrl(endpoint Endpoint, oid string) (*url.URL, error) { u, err := url.Parse(endpoint.Url) if err != nil { return nil, err } u.Path = path.Join(u.Path, "objects") if len(oid) > 0 { u.Path = path.Join(u.Path, oid) } return u, nil } func (c *Configuration) loadGitConfig() { c.loading.Lock() defer c.loading.Unlock() if c.gitConfig != nil { return } uniqRemotes := make(map[string]bool) c.gitConfig = make(map[string]string) var output string listOutput, err := git.Config.List() if err != nil { panic(fmt.Errorf("Error listing git config: %s", err)) } configFile := filepath.Join(LocalWorkingDir, ".gitconfig") fileOutput, err := git.Config.ListFromFile(configFile) if err != nil { panic(fmt.Errorf("Error listing git config from file: %s", err)) } output = fileOutput + "\n" + listOutput lines := strings.Split(output, "\n") for _, line := range lines { pieces := strings.SplitN(line, "=", 2) if len(pieces) < 2 { continue } key := strings.ToLower(pieces[0]) c.gitConfig[key] = pieces[1] keyParts := strings.Split(key, ".") if len(keyParts) > 1 && keyParts[0] == "remote" { remote := keyParts[1] uniqRemotes[remote] = remote == "origin" } } c.remotes = make([]string, 0, len(uniqRemotes)) for remote, isOrigin := range uniqRemotes { if isOrigin { continue } c.remotes = append(c.remotes, remote) } }
{ "content_hash": "f7f12983140f54983ef1a2454e834237", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 87, "avg_line_length": 21.71031746031746, "alnum_prop": 0.6552732590020106, "repo_name": "michael-k/git-lfs", "id": "66d01be657bd3ea870c2676f784c80851fa9676b", "size": "5471", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lfs/config.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "180271" }, { "name": "Shell", "bytes": "60383" } ], "symlink_target": "" }
<?php namespace metastore; /** * Autogenerated by Thrift Compiler (0.16.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ use Thrift\Base\TBase; use Thrift\Type\TType; use Thrift\Type\TMessageType; use Thrift\Exception\TException; use Thrift\Exception\TProtocolException; use Thrift\Protocol\TProtocol; use Thrift\Protocol\TBinaryProtocolAccelerated; use Thrift\Exception\TApplicationException; class ISchema { static public $isValidate = false; static public $_TSPEC = array( 1 => array( 'var' => 'schemaType', 'isRequired' => false, 'type' => TType::I32, 'class' => '\metastore\SchemaType', ), 2 => array( 'var' => 'name', 'isRequired' => false, 'type' => TType::STRING, ), 3 => array( 'var' => 'catName', 'isRequired' => false, 'type' => TType::STRING, ), 4 => array( 'var' => 'dbName', 'isRequired' => false, 'type' => TType::STRING, ), 5 => array( 'var' => 'compatibility', 'isRequired' => false, 'type' => TType::I32, 'class' => '\metastore\SchemaCompatibility', ), 6 => array( 'var' => 'validationLevel', 'isRequired' => false, 'type' => TType::I32, 'class' => '\metastore\SchemaValidation', ), 7 => array( 'var' => 'canEvolve', 'isRequired' => false, 'type' => TType::BOOL, ), 8 => array( 'var' => 'schemaGroup', 'isRequired' => false, 'type' => TType::STRING, ), 9 => array( 'var' => 'description', 'isRequired' => false, 'type' => TType::STRING, ), ); /** * @var int */ public $schemaType = null; /** * @var string */ public $name = null; /** * @var string */ public $catName = null; /** * @var string */ public $dbName = null; /** * @var int */ public $compatibility = null; /** * @var int */ public $validationLevel = null; /** * @var bool */ public $canEvolve = null; /** * @var string */ public $schemaGroup = null; /** * @var string */ public $description = null; public function __construct($vals = null) { if (is_array($vals)) { if (isset($vals['schemaType'])) { $this->schemaType = $vals['schemaType']; } if (isset($vals['name'])) { $this->name = $vals['name']; } if (isset($vals['catName'])) { $this->catName = $vals['catName']; } if (isset($vals['dbName'])) { $this->dbName = $vals['dbName']; } if (isset($vals['compatibility'])) { $this->compatibility = $vals['compatibility']; } if (isset($vals['validationLevel'])) { $this->validationLevel = $vals['validationLevel']; } if (isset($vals['canEvolve'])) { $this->canEvolve = $vals['canEvolve']; } if (isset($vals['schemaGroup'])) { $this->schemaGroup = $vals['schemaGroup']; } if (isset($vals['description'])) { $this->description = $vals['description']; } } } public function getName() { return 'ISchema'; } public function read($input) { $xfer = 0; $fname = null; $ftype = 0; $fid = 0; $xfer += $input->readStructBegin($fname); while (true) { $xfer += $input->readFieldBegin($fname, $ftype, $fid); if ($ftype == TType::STOP) { break; } switch ($fid) { case 1: if ($ftype == TType::I32) { $xfer += $input->readI32($this->schemaType); } else { $xfer += $input->skip($ftype); } break; case 2: if ($ftype == TType::STRING) { $xfer += $input->readString($this->name); } else { $xfer += $input->skip($ftype); } break; case 3: if ($ftype == TType::STRING) { $xfer += $input->readString($this->catName); } else { $xfer += $input->skip($ftype); } break; case 4: if ($ftype == TType::STRING) { $xfer += $input->readString($this->dbName); } else { $xfer += $input->skip($ftype); } break; case 5: if ($ftype == TType::I32) { $xfer += $input->readI32($this->compatibility); } else { $xfer += $input->skip($ftype); } break; case 6: if ($ftype == TType::I32) { $xfer += $input->readI32($this->validationLevel); } else { $xfer += $input->skip($ftype); } break; case 7: if ($ftype == TType::BOOL) { $xfer += $input->readBool($this->canEvolve); } else { $xfer += $input->skip($ftype); } break; case 8: if ($ftype == TType::STRING) { $xfer += $input->readString($this->schemaGroup); } else { $xfer += $input->skip($ftype); } break; case 9: if ($ftype == TType::STRING) { $xfer += $input->readString($this->description); } else { $xfer += $input->skip($ftype); } break; default: $xfer += $input->skip($ftype); break; } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } public function write($output) { $xfer = 0; $xfer += $output->writeStructBegin('ISchema'); if ($this->schemaType !== null) { $xfer += $output->writeFieldBegin('schemaType', TType::I32, 1); $xfer += $output->writeI32($this->schemaType); $xfer += $output->writeFieldEnd(); } if ($this->name !== null) { $xfer += $output->writeFieldBegin('name', TType::STRING, 2); $xfer += $output->writeString($this->name); $xfer += $output->writeFieldEnd(); } if ($this->catName !== null) { $xfer += $output->writeFieldBegin('catName', TType::STRING, 3); $xfer += $output->writeString($this->catName); $xfer += $output->writeFieldEnd(); } if ($this->dbName !== null) { $xfer += $output->writeFieldBegin('dbName', TType::STRING, 4); $xfer += $output->writeString($this->dbName); $xfer += $output->writeFieldEnd(); } if ($this->compatibility !== null) { $xfer += $output->writeFieldBegin('compatibility', TType::I32, 5); $xfer += $output->writeI32($this->compatibility); $xfer += $output->writeFieldEnd(); } if ($this->validationLevel !== null) { $xfer += $output->writeFieldBegin('validationLevel', TType::I32, 6); $xfer += $output->writeI32($this->validationLevel); $xfer += $output->writeFieldEnd(); } if ($this->canEvolve !== null) { $xfer += $output->writeFieldBegin('canEvolve', TType::BOOL, 7); $xfer += $output->writeBool($this->canEvolve); $xfer += $output->writeFieldEnd(); } if ($this->schemaGroup !== null) { $xfer += $output->writeFieldBegin('schemaGroup', TType::STRING, 8); $xfer += $output->writeString($this->schemaGroup); $xfer += $output->writeFieldEnd(); } if ($this->description !== null) { $xfer += $output->writeFieldBegin('description', TType::STRING, 9); $xfer += $output->writeString($this->description); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } }
{ "content_hash": "3c279706bb497bc60bbb503554caa25d", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 80, "avg_line_length": 31.757785467128027, "alnum_prop": 0.41850076269339725, "repo_name": "sankarh/hive", "id": "7f276805b1e45a2bc123189037e9674672b802a7", "size": "9178", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "standalone-metastore/metastore-common/src/gen/thrift/gen-php/metastore/ISchema.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "55440" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "96657" }, { "name": "CSS", "bytes": "4742" }, { "name": "GAP", "bytes": "204254" }, { "name": "HTML", "bytes": "24102" }, { "name": "HiveQL", "bytes": "8290287" }, { "name": "Java", "bytes": "59285075" }, { "name": "JavaScript", "bytes": "44139" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "9105" }, { "name": "PLpgSQL", "bytes": "294996" }, { "name": "Perl", "bytes": "319742" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "383647" }, { "name": "ReScript", "bytes": "3460" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "1190" }, { "name": "Shell", "bytes": "271549" }, { "name": "TSQL", "bytes": "14126" }, { "name": "Thrift", "bytes": "164235" }, { "name": "XSLT", "bytes": "1329" }, { "name": "q", "bytes": "289182" } ], "symlink_target": "" }
namespace Mailjet.Client.Resources { public static class Contactfilter { public static readonly ResourceInfo Resource = new ResourceInfo("contactfilter"); public const string Description = "Description"; public const string Expression = "Expression"; public const string ID = "ID"; public const string Name = "Name"; public const string Status = "Status"; public const string ShowDeleted = "ShowDeleted"; public const string Limit = "Limit"; public const string Offset = "Offset"; public const string Sort = "Sort"; public const string CountOnly = "CountOnly"; } }
{ "content_hash": "9541b4a66362ed66f9fcf05d8cc5c4cd", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 89, "avg_line_length": 33.4, "alnum_prop": 0.6511976047904192, "repo_name": "mailjet/mailjet-apiv3-dotnet", "id": "71a1c4e6305b94017ebd4c709981636ee8eadc1c", "size": "668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mailjet.Client/Resources/Contactfilter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "178033" } ], "symlink_target": "" }
ACCEPTED #### According to World Register of Marine Species #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9145dcbd7afef5e650b9fdb74f125ca8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 32, "avg_line_length": 9.76923076923077, "alnum_prop": 0.7007874015748031, "repo_name": "mdoering/backbone", "id": "71d21a5774f661a0ebc9f48f932b68ceac7f3026", "size": "208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Bacteria/Proteobacteria/Gammaproteobacteria/Oceanospirillales/Alcanivoracaceae/Alcanivorax/Alcanivorax hongdengensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package at.ac.tuwien.dsg.smartcom.services.dao; import at.ac.tuwien.dsg.smartcom.model.QueryCriteria; import at.ac.tuwien.dsg.smartcom.services.QueryCriteriaImpl; import at.ac.tuwien.dsg.smartcom.utils.MessageQueryTestClass; import org.junit.Before; public class MongoDBMessageQueryDAOTest extends MessageQueryTestClass { private MongoDBMessageQueryDAO dao; @Before public void setUp() throws Exception { super.setUp(); dao = new MongoDBMessageQueryDAO(mongoDB.getClient(), "test-log", "log"); } @Override public QueryCriteria createCriteria() { return new QueryCriteriaImpl(dao); } }
{ "content_hash": "9688d821dd1fb819917b7eb15f167690", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 81, "avg_line_length": 26.791666666666668, "alnum_prop": 0.7402799377916018, "repo_name": "tuwiendsg/SmartCom", "id": "f5235ec11298ba8b28a86e644ebbfb63df3c393f", "size": "1460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "message-query/src/test/java/at/ac/tuwien/dsg/smartcom/services/dao/MongoDBMessageQueryDAOTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1004960" } ], "symlink_target": "" }
set -e usage() { echo "run_cppcheck.sh install_dir" exit 1 } if [ "$#" -ne "1" ]; then usage fi INSTALL_DIR=$1 CPPCHECK_EXECUTABLE=${CPPCHECK_INSTALL_DIR}/cppcheck/cppcheck FAILED=0 $CPPCHECK_EXECUTABLE --version $CPPCHECK_EXECUTABLE --std=c99 --error-exitcode=-1 --quiet -j 8 --enable=all --template='[{file}:{line}]: ({severity}:{id}) {message}' --inline-suppr --suppressions-list=codebuild/bin/cppcheck_suppressions.txt -I ./tests api bin crypto error stuffer ./tests/unit tls utils || FAILED=1 if [ $FAILED == 1 ]; then printf "\\033[31;1mFAILED cppcheck\\033[0m\\n" exit -1 else printf "\\033[32;1mPASSED cppcheck\\033[0m\\n" fi
{ "content_hash": "0c928e0d1887b91d1eb1d081cac0017e", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 284, "avg_line_length": 25.192307692307693, "alnum_prop": 0.6793893129770993, "repo_name": "colmmacc/s2n", "id": "5d586080712e41adeb3d8405efa25c8cd327eec2", "size": "1226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codebuild/bin/run_cppcheck.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "42646" }, { "name": "C", "bytes": "2470024" }, { "name": "C++", "bytes": "11503" }, { "name": "CMake", "bytes": "11249" }, { "name": "Coq", "bytes": "1249456" }, { "name": "Makefile", "bytes": "47513" }, { "name": "Objective-C", "bytes": "2807" }, { "name": "Perl", "bytes": "4169" }, { "name": "Python", "bytes": "112772" }, { "name": "Ruby", "bytes": "6523" }, { "name": "Shell", "bytes": "88444" } ], "symlink_target": "" }
<section id="contact" class="map"> <div class="container"> <div class="row text-left"> <div class="col-lg-12 "> <hr/> <div class="row"> <div class="col-lg-12"> <div class="panel panel-warning"> <div class="panel-heading"> <h3>Training's Module</h3> </div> <div class="panel-body"> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav" id="main_menu"> <li id="event"><a href="<?php echo site_url('training/1');?>"><strong><span class="glyphicon glyphicon-home"></span></strong></a></li> <li id="crud_event"><a href="<?php echo site_url('training/3');?>"><strong><span class="glyphicon glyphicon-calendar"></span></strong></a> </li> <li id="instructor"><a href="<?php echo site_url('training/2');?>" ><strong><span class="glyphicon glyphicon-user"></span></strong></a></li> <li id="modul"><a href="<?php echo site_url('training/4');?>" ><strong><span class="glyphicon glyphicon-book"></span></strong></a></li> </ul> </div> </div> </nav> <!-- Content --> <div id="training_content"></div> <!-- End Content --> </div> </div> </div> </div> </div> </div> </div> <script type="text/javascript"> /* Main Function */ var page = '<?php echo $page;?>'; load_content(page); function set_content(str){ $('#training_content').empty(); $('#training_content').html(str); } function load_content(event){ $('#<?php echo $page;?>').attr('class','active'); switch(event){ case 'event': display_content_event(); break; case 'instructor': display_content_instructor(); break; case 'crud_event': display_content_crud_event(); break; case 'module' : display_content_module(); break; default: display_content_event(); break; } } /* End Main Function */ /**************************************************************************************************/ /* Module Function */ function display_content_module(){ var str = '<div class="panel panel-default"><div class="panel-body"><form id="frm_add_module" onSubmit="return false">'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Nama Module</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_module" name="txt_module" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><input type="Submit" value="Simpan" onClick="add_module()" /><input type="Reset" value="Reset"/></div>'+ '</div>'+ '</form></div></div>'+ '<div class="panel panel-default"><div class="panel-heading"><span style="font-size:14px;font-weight:bold;">Daftar Module</span></div><div class="panel-body" id="list-module"></div></div>'; set_content(str); list_module(); } function list_module(){ var no,str; $.get('<?php echo site_url('training/module')?>',{}).done(function(response){ str = '<table class="table table-hover" id="table_module"><thead><tr><th>NO</th><th>NAMA MODULE</th><th>Action</th></tr></thead><tbody>'; no=1; $.each(response,function(index,value){ str = str + '<tr>'+ '<td>'+ no +'</td>'+ '<td>'+ value['MODULE_NAME'] +'</td>'+ '<td>'+ '<button onClick="detail_module('+value['MODULE_ID']+')"><span class="glyphicon glyphicon-edit"></span></button>'+ '<button onClick="delete_module('+value['MODULE_ID']+')"><span class="glyphicon glyphicon-trash"></span></button>'+ '</td>'+ '</tr>'; no++; }); str = str + '</tbody></table>'; $('#list-module').empty(); $('#list-module').html(str) $('#table_module').dataTable(); }); } function add_module(){ var data = $('#frm_add_module').serialize(); $.getJSON('<?php echo base_url('training/add_module')?>',data).done(function(response){ list_module(); }); } function detail_module(id_module){ var str = '<div class="panel panel-default"><div class="panel-body"><form id="frm_add_module" onSubmit="return false">'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Nama Module</label></div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" class="form-control" id="txt_module" name="txt_module" />'+ '<input type="hidden" name="hid_module" id="hid_module" />'+ '</div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><input type="Submit" value="Simpan" onClick="edit_module()" /><input type="Reset" value="Reset"/></div>'+ '</div>'+ '</form></div></div>'; set_content(str); $.getJSON('<?php echo base_url('training/detail_module')?>/'+id_module,{}).done(function(response){ $('#txt_module').val(response[0].MODULE_NAME); $('#hid_module').val(response[0].MODULE_ID); }); } function edit_module(){ var data = $('#frm_add_module').serialize(); $.getJSON('<?php echo base_url('training/edit_module')?>',data).done(function(response){ list_module(); }); } function delete_module(id_module){ $.getJSON('<?php echo base_url('training/delete_module')?>/',id_module).done(function(response){ list_module(); }); } /* End Module Function */ /**************************************************************************************************/ /* Event Function */ function display_content_event(){ var no,str = '<div class="panel panel-default"><div class="panel-heading"><span style="font-size:14px;font-weight:bold;">Pelatihan Hari Ini</span></div><div class="panel-body"><table class="table" id="dataTables-example1"><thead><tr><th>NO</th><th>NAMA PELATIHAN</th><th>JUMLAH PESERTA</th><th>ROOM/FLOOR/LOCATION</th><th>TGL MULAI</th><th>TGL SELESAI</th></tr></thead><tbody>'; $.get('<?php echo site_url('training/today')?>',{}).done(function(response){ no=1; $.each(response,function(index,value){ str = str + '<tr>'+ '<td>'+ no +'</td>'+ '<td>'+ value['TRAINING'] +'</td>'+ '<td style="text-align:center;">'+ value['TOTAL_LEARNER'] +'</td>'; if(value['LOKASI']){ str = str + '<td>'+ value['LOKASI'] +'</td>'; //alert('Test1'); }else{ str = str + '<td>'+ value['ROOM_NAME'] +'/'+ value['ROOM_FLOOR'] +'/'+ value['ROOM_LOCATION_NAME'] +'</td>'; //alert('Test1'); } str = str +'<td style="text-align:center;">'+ value['TGLMULAI'] +'</td>'+ '<td style="text-align:center;">'+ value['TGLAKHIR'] +'</td>'+ '</tr>'; no++; }); str = str + '</tbody></table></div></div>'; str = str + '<div class="panel panel-default"><div class="panel-heading"><span style="font-size:14px;font-weight:bold;">Pelatihan yang Akan Datang</span></div><div class="panel-body"><table class="table" id="dataTables-example2"><thead><tr><th>NO</th><th>NAMA PELATIHAN</th><th>JUMLAH PESERTA</th><th>ROOM/FLOOR/LOCATION</th><th>TGL MULAI</th><th>TGL SELESAI</th></tr></thead><tbody>'; $.get('<?php echo site_url('training/next')?>',{}).done(function(response){ no=1; $.each(response,function(index,value){ str = str + '<tr>'+ '<td>'+ no +'</td>'+ '<td>'+ value['TRAINING'] +'</td>'+ '<td style="text-align:center;">'+ value['TOTAL_LEARNER'] +'</td>'; if(value['LOKASI']){ str = str + '<td>'+ value['LOKASI'] +'</td>'; //alert('Test1'); }else{ str = str + '<td>'+ value['ROOM_NAME'] +'/'+ value['ROOM_FLOOR'] +'/'+ value['ROOM_LOCATION_NAME'] +'</td>'; //alert('Test1'); } str = str + '<td style="text-align:center;">'+ value['TGLMULAI'] +'</td>'+ '<td style="text-align:center;">'+ value['TGLAKHIR'] +'</td>'+ '</tr>'; no++; }); str = str + '</tbody></table></div></div>'; set_content(str); }); }); } /* CRUD Event Function */ function display_content_crud_event(){ var no,str = '<div class="panel panel-default"><div class="panel-body"><form id="frm_add_event" onSubmit="return false">'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Nama Pelatihan</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_nama_pelatihan" name="txt_nama_pelatihan" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Jumlah Peserta</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_jml_peserta" name="txt_jml_peserta" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Room/Floor/Location</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_room" name="txt_room" /></div>'+ '</div>'+ '<div class="row">'+ '<div class="col-xs-12 col-sm-4"><div id="room-container"></div></div>'+ '</div>'+ '<div class="row">'+ '<div class="col-xs-12 col-sm-4"><input type="hidden" id="hid_room" name="hid_room" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Tanggal Mulai</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_tgl_mulai" name="txt_tgl_mulai" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Tanggal Selesai</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_tgl_selesai" name="txt_tgl_selesai" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><input type="Submit" value="Simpan" onClick="add_event()" /><input type="Reset" value="Reset"/></div>'+ '</div>'+ '</form></div></div>'; $.get('<?php echo site_url('training/all')?>',{}).done(function(response){ str = str + '<div class="panel panel-default"><div class="panel-heading"><span style="font-size:14px;font-weight:bold;">Daftar Pelatihan</span></div><div class="panel-body"><table class="table" id="dataEvent"><thead><tr><th>NO</th><th style="text-align:center;">NAMA PELATIHAN</th><th style="text-align:center;">JUMLAH PESERTA</th><th style="text-align:center;">ROOM/FLOOR/LOCATION</th><th style="text-align:center;">TGL MULAI</th><th style="text-align:center;">TGL SELESAI</th><th style="text-align:center;">Action</th></tr></thead><tbody>'; no=1; $.each(response,function(index,value){ str = str + '<tr>'+ '<td>'+ no +'</td><td>'+ value['TRAINING'] +'</td>'+ '<td style="text-align:center;">'+ value['TOTAL_LEARNER'] +'</td>'; if(value['LOKASI']){ str = str + '<td>'+ value['LOKASI'] +'</td>'; //alert('Test1'); }else{ str = str + '<td>'+ value['ROOM_NAME'] +'/'+ value['ROOM_FLOOR'] +'/'+ value['ROOM_LOCATION_NAME'] +'</td>'; //alert('Test1'); } str = str + '<td style="text-align:center;">'+ value['TGLMULAI'] +'</td>'+ '<td style="text-align:center;">'+ value['TGLAKHIR'] +'</td>'+ '<td><button onClick="edit_form_event('+ value['FRAMETEXT_ID'] +')"><span class="glyphicon glyphicon-edit" ></span></button><button onClick="delete_event('+ value['FRAMETEXT_ID'] +')"><span class="glyphicon glyphicon-trash"></span></button></td>'+ '</tr>'; no++; }); str = str + '</tbody></table></div></div>'; set_content(str); $( "#txt_tgl_mulai" ).datepicker({dateFormat: "yy-mm-dd"}); $( "#txt_tgl_selesai" ).datepicker({dateFormat: "yy-mm-dd"}); set_autocomplete_room(); $("#dataEvent").dataTable(); }); } function set_autocomplete_room(){ var i,room_id=[],room_name=[],result=[]; $.getJSON('<?php echo base_url('training/room');?>',{}).done(function(response){ i=0; $.each(response,function(idx,val){ room_id[i] = val.ROOM_ID; room_name[i] = val.ROOM_NAME; i++; }); $('#txt_room').autocomplete({ source: room_name, appendTo: '#room-container', select: function(event,ui){ i = $.inArray(ui.item.value,room_name); $('#hid_room').val(room_id[i]); $('#txt_room').val(room_name[i]); $('.ui-helper-hidden-accessible').empty(); return false; } }); }); } function add_event(){ var data = $('#frm_add_event').serialize(); $.get('<?php echo base_url('training/add_event');?>',data).done(function(response){ display_content_crud_event(); }) } function edit_form_event(frametext_id){ var str = '<div class="panel panel-default"><div class="panel-body"><form id="frm_edit_event" onSubmit="return false">'+ '<input type="hidden" name="hid_id_pelatihan" id="hid_id_pelatihan" value="'+ frametext_id +'" />'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Nama Pelatihan</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_nama_pelatihan" name="txt_nama_pelatihan" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Jumlah Peserta</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_jml_peserta" name="txt_jml_peserta" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Room/Floor/Location</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_room" name="txt_room" /></div>'+ '</div>'+ '<div class="row">'+ '<div class="col-xs-12 col-sm-4"><div id="room-container"></div></div>'+ '</div>'+ '<div class="row">'+ '<div class="col-xs-12 col-sm-4"><input type="hidden" id="hid_room" name="hid_room" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Tanggal Mulai</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_tgl_mulai" name="txt_tgl_mulai" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><label>Tanggal Selesai</label></div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" id="txt_tgl_selesai" name="txt_tgl_selesai" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-2 col-sm-2"><input type="Submit" value="Simpan" onClick="edit_event()" /><button onClick="display_content_crud_event()">Back</button></div>'+ '</div>'+ '</form></div></div>'; set_content(str); $( "#txt_tgl_mulai" ).datepicker({dateFormat: "yy-mm-dd"}); $( "#txt_tgl_selesai" ).datepicker({dateFormat: "yy-mm-dd"}); $.getJSON('<?php echo base_url('training/detail_event')?>/'+ frametext_id,{}).done(function(response){ $('#txt_nama_pelatihan').val(response[0].TRAINING); $('#txt_jml_peserta').val(response[0].TOTAL_LEARNER); if(response[0].LOKASI){ $('#txt_room').val(response[0].LOKASI); }else{ $('#txt_room').val(response[0].ROOM_NAME); $('#hid_room').val(response[0].ROOM_ID); } $('#txt_tgl_mulai').val(response[0].TGLMULAI); $('#txt_tgl_selesai').val(response[0].TGLAKHIR); $('#txt_room').keydown(function(){ $('#hid_room').val(''); }); set_autocomplete_room(); }); } function edit_event(){ var data = $('#frm_edit_event').serialize(); $.getJSON('<?php echo base_url('training/edit_event')?>',data).done(function(response){ display_content_crud_event(); }); } function delete_event(frametext_id){ $.post('<?php echo base_url('training/hapus_event')?>/',{id:frametext_id}).done(function(response){ display_content_crud_event(); }); } /* End CRUD Event Function */ /* End Event Function */ /*************************************************************************************************/ /* Instructor Function */ //Kumpulan Master_Instructor_Function function display_content_instructor(){ var str = '<div class="panel panel-default">'+ '<div class="panel-heading">'+ '<span style="font-size:14px;font-weight:bold;">&nbsp;Monitoring Instruktur</span></div>'+ '<div class="panel-body" role="tabpanel">'+ '<ul class="nav nav-tabs" role="tablist">'+ '<li role="presentation" class="active"><a data-target="#internal" aria-controls="internal" role="tab" data-toggle="tab" onClick="display_internal_instructor()"><small>Internal</small></a></li>'+ '<li role="presentation"><a data-target="#eksternal" aria-controls="eksternal" role="tab" data-toggle="tab" onClick="display_eksternal_instructor()"><small>Eksternal</small></a></li>'+ '<li role="presentation"><a data-target="#presensi" aria-controls="presensi" role="tab" data-toggle="tab" onClick="display_presensi_instructor()"><small>Presensi</small></a></li>'+ '<li role="presentation"><a data-target="#edit-presensi" aria-controls="edit-presensi" role="tab" data-toggle="tab" onClick="display_edit_presensi_instructor()"><small>Edit Presensi</small></a></li>'+ '</ul>'+ '<div class="tab-content" style="padding-top:5px;">'+ '<div role="tabpanel" class="tab-pane active" id="internal"></div>'+ '<div role="tabpanel" class="tab-pane" id="eksternal"></div>'+ '<div role="tabpanel" class="tab-pane" id="presensi"></div>'+ '<div role="tabpanel" class="tab-pane" id="edit-presensi"></div>'+ '</div></div></div>'; set_content(str); display_internal_instructor(); } //Add instruktur baru function display_instruktur_add_form(tipe){ var str = '<div class="panel panel-default"><div class="panel-body"><form id="frm_add_instruktur" onSubmit="return false">'; if(parseInt(tipe) == 1){ str = str + '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">NPP</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_npp" id="txt_npp" value=""></div>'+ '</div>'; } str = str + '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Nama Instruktur</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_nama" id="txt_nama" value=""></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Tempat Lahir</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_tmp_lahir" id="txt_tmp_lahir" value=""></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Tanggal Lahir</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_tgl_lahir" id="txt_tgl_lahir" value=""></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Alamat</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_alamat" id="txt_alamat" value=""></div>'+ '</div>'; if(parseInt(tipe) == 2){ str = str + '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Vendor Asal</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_vendor" id="txt_vendor" value=""><input type="hidden" name="hid_id_vendor" id="hid_id_vendor" value="" /></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2"><div id="vendor-container"></div></div>'+ '</div>'; } str = str + '<div class="row">'+ '<div class="col-xs-12 col-sm-12">'+ '<input type="submit" value="Simpan" onClick="add_master_instructor('+ tipe +')">'+ '<input type="button" value="Back" onClick="display_content_instructor()" />'+ '</div>'+ '</div>'; str = str + '</form></div></div>'; if(parseInt(tipe) == 1){ str = str + '<div id="internal"></div>'; }else{ if(parseInt(tipe) == 2){ str = str + '<div id="eksternal"></div>'; } } set_content(str); $( "#txt_tgl_lahir" ).datepicker({dateFormat: "yy-mm-dd"}); if(parseInt(tipe) == 1){ display_internal_instructor(); }else{ if(parseInt(tipe) == 2){ display_eksternal_instructor(); set_autocomplete_vendor(); } } } function set_autocomplete_vendor(){ var i,vendor_id=[],vendor_name=[]; $.getJSON('<?php echo base_url('training/vendor');?>',{}).done(function(response){ i=0; $.each(response,function(idx,val){ vendor_id[i] = val.VENDOR_ID; vendor_name[i] = val.VENDOR_NAME; i++; }); $('#txt_vendor').autocomplete({ source: vendor_name, appendTo: '#vendor-container', select: function(event,ui){ i = $.inArray(ui.item.value,vendor_name); $('#hid_id_vendor').val(vendor_id[i]); $('#txt_vendor').val(vendor_name[i]); $('.ui-helper-hidden-accessible').empty(); return false; } }); }); } function add_master_instructor(tipe){ var data = $('#frm_add_instruktur').serialize(); $.get('<?php echo site_url('training/add_instruktur')?>/',data).done(function(response){ document.getElementById('frm_add_instruktur').reset(); if(parseInt(tipe) == 1){ display_internal_instructor(); }else{ if(parseInt(tipe) == 2){ display_eksternal_instructor(); } } }); } function display_internal_instructor(){ var no,str = '<div class="panel panel-default"><div class="panel-body">'+ '<table class="table" id="dataTables-example">'+ '<thead><tr><th>No</th><th>NPP</th><th>Nama Instruktur</th><th style="text-align:center;">Action</th></tr></thead><tbody>'; $.get('<?php echo site_url('training/internal')?>',{}).done(function(response){ no = 1; $.each(response,function(index,value){ str = str + '<tr><td>'+ no +'</td><td>'+ value['INSTRUCTOR_NPP'] +'</td><td>'+ value['INSTRUCTOR_NAME'] +'</td><td style="text-align:center;"><button onClick="display_detail_instructor('+value['INSTRUCTOR_ID']+',1)"><span class="glyphicon glyphicon-edit"></span><button onClick="delete_instuktur('+ value['INSTRUCTOR_ID'] +',1)"><span class="glyphicon glyphicon-trash"></span></button></td></tr>'; no++; }); str = str + '</tbody></table></div></div>'; $('#eksternal').empty(); $('#internal').html(str); $('#dataTables-example').dataTable(); str = '<button type="button" class="btn btn-primary btn-sm" onClick="display_instruktur_add_form(1)"><span class="glyphicon glyphicon-plus"></span></button>&nbsp;&nbsp;'; $('#dataTables-example_length').prepend(str); }); } function delete_instuktur(id,tipe){ $.get('<?php echo site_url('training/delete_instruktur');?>/'+id,{}).done(function(response){ switch(parseInt(tipe)){ case 1: display_internal_instructor(); break; case 2: display_eksternal_instructor(); break; } }); } function display_eksternal_instructor(){ var no,str = '<div class="panel panel-default"><div class="panel-body">'+ '<table class="table" id="dataTables-example">'+ '<thead>'+ '<tr><th>No</th><th>Nama Instruktur</th><th>Vendor Asal</th><th style="text-align:center;">Action</th></tr>'+ '</thead>'+ '<tbody>'; $.get('<?php echo site_url('training/eksternal')?>',{}).done(function(response){ no = 1; $.each(response,function(index,value){ str = str + '<tr><td>'+ no +'</td><td>'+ value['INSTRUCTOR_NAME'] +'</td><td>'+ value['VENDOR_NAME'] +'</td><td style="text-align:center;"><button onClick="display_detail_instructor('+value['INSTRUCTOR_ID']+',2)"><span class="glyphicon glyphicon-edit"></span><button><span class="glyphicon glyphicon-trash"></span></button></td></td></tr>'; no++; }); str = str + '</tbody></table></div></div>'; $('#internal').empty(); $('#eksternal').html(str); $('#dataTables-example').dataTable(); str = '<button type="button" class="btn btn-primary btn-sm" onClick="display_instruktur_add_form(2)"><span class="glyphicon glyphicon-plus"></span></button>&nbsp;&nbsp;'; $('#dataTables-example_length').prepend(str); }); } //edit data instruktur function display_detail_instructor(id,tipe){ var str = '<div class="panel panel-default"><div class="panel-body"><form id="frm_edit_instruktur" onSubmit="return false">'; $.get('<?php echo site_url("training/instructor");?>/'+id,{}).done(function(response){ str = str + '<input type="hidden" name="hid_id_instructor" value="'+ id +'"/>'; if(parseInt(tipe) == 1){ str = str + '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">NPP</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_npp" id="txt_npp" value="'+ response[0].INSTRUCTOR_NPP +'"></div>'+ '</div>'; } str = str + '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Nama Instruktur</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_nama" id="txt_nama" value="'+ response[0].INSTRUCTOR_NAME +'"></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Tempat Lahir</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_tmp_lahir" id="txt_tmp_lahir" value="'+ response[0].TEMPAT_LAHIR +'"></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Tanggal Lahir</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_tgl_lahir" id="txt_tgl_lahir" value="'+ response[0].TANGGAL_LAHIR +'"></div>'+ '</div>'+ '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Alamat Instruktur</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_alamat" id="txt_alamat" value="'+ response[0].INSTRUCTOR_ADDRESS +'"></div>'+ '</div>'; if(parseInt(tipe) == 2){ str = str + '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">Vendor Asal</div>'+ '<div class="col-xs-12 col-sm-4"><input type="text" class="form-control" name="txt_vendor" id="txt_vendor" value="'+ response[0].VENDOR_ID+'"><input type="hidden" name="hid_id_vendor" id="hid_id_vendor" value="'+ response[0].VENDOR_ID +'"></div>'+ '</div>'; } str = str + '<div class="row" style="padding:5px;">'+ '<div class="col-xs-12 col-sm-2">'+ '<input type="submit" value="Simpan" onClick="edit_master_instruktur()">'+ '<input type="button" value="Back" onClick="display_content_instructor()" />'+ '</div>'+ '</div>'; str = str + '</form></div></div>'; switch(parseInt(tipe)){ case 1: $('#internal').empty(); $('#eksternal').empty(); $('#internal').html(str); break; case 2: $('#internal').empty(); $('#eksternal').empty(); $('#eksternal').html(str); break; } $( "#txt_tgl_lahir" ).datepicker({dateFormat: "yy-mm-dd"}); }); } function edit_master_instruktur(){ var data = $('#frm_edit_instruktur').serialize(); $.get('<?php echo site_url('training/edit_instruktur');?>',data).done(function(response){ display_content_instructor(); }); } // End Master_Instructor_Function // Kumpulan Presensi_Instructor_Function function display_presensi_instructor(){ var instruktur,kelas,materi,tipe,index,instruktur_id,kelas_id,materi_id,str = '<br /><div class="panel panel-default"><div class="panel-body">'+ '<form id="frm_presensi" onSubmit="return false">'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-2 col-sm-2">Tipe Instruktur</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<label class="radio-inline">'+ '<input type="radio" name="rad_tipe" id="rad_tipe1" value="Internal" checked>Internal</label>'+ '<label class="radio-inline">'+ '<input type="radio" name="rad_tipe" id="rad_tipe2" value="External">External</label>'+ '</div>'+ '</div>'+ '<div id="pil_instruktur_data" style="padding:2px;">'; str = str + '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-2 col-sm-2">Kelas</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_kelas" id="txt_kelas" class="form-control" placeholder="Nama Kelas"/>'+ '<input type="hidden" name="hid_id_kelas" id="hid_id_kelas" value="" />'+ '</div>'+ '<div class="cols-xs-12 col-sm-2"><div id="kelas-container"></div></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-2 col-sm-2">Materi</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_materi" id="txt_materi" class="form-control" placeholder="Materi Ajar"/>'+ '<input type="hidden" name="hid_id_materi" id="hid_id_materi" value="" />'+ '</div>'+ '<div class="cols-xs-12 col-sm-2"><div id="materi-container"></div></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-2 col-sm-2"><input type="submit" value="Simpan" onClick="add_presensi_instruktur()"></div>'+ '</div>'+ '</form>'+ '<div class="panel panel-default"><div class="panel-body" id="data_content_presensi"></div></div>'; str = str + '</div></div>'; $('#presensi').empty(); $('#presensi').html(str); tipe = $('input[type=radio][name=rad_tipe]').val(); display_input_name_presensi(tipe); display_data_content_presensi(); instruktur = get_data_instruktur(tipe); kelas = get_data_kelas(); materi = get_data_materi(); set_autocomplete_presensi(tipe,instruktur,kelas,materi); $('input[type=radio][name=rad_tipe]').change(function(){ tipe = $(this).val(); display_input_name_presensi(tipe); instruktur = get_data_instruktur(tipe); kelas = get_data_kelas(); materi = get_data_materi(); set_autocomplete_presensi(tipe,instruktur,kelas,materi); }); } function display_edit_presensi_instructor(){ var no,str = '<div class="panel panel-default"><div class="panel-body">Test<table class="table" id="table-edit-presensi-content"><thead><tr><th>NO</th><th>NAMA PELATIHAN</th><th>TGL MULAI</th><th>TGL SELESAI</th><th>NAMA INSTRUKTUR</th><th>MATERI</th><th>ACTION</th></tr></thead><tbody id="edit-presensi-content"></tbody></table></div></div>'; $('#edit-presensi').empty(); $('#edit-presensi').html(str); $.getJSON('<?php echo base_url('training/get_all_absen_instructor');?>',{}).done(function(response){ str = '';no = 1; $.each(response,function(index,value){ str = str + '<tr><td>'+ no +'</td>'+ '<td>'+ value['TRAINING']+'</td>'+ '<td>'+value['TGLMULAI']+'</td>'+ '<td>'+value['TGLAKHIR']+'</td>'+ '<td>'+value['INSTRUCTOR_NAME']+'</td>'+ '<td>'+value['MODULE_NAME']+'</td>'+ '<td><button onCLick="form_edit_presensi_instruktur('+value['t_absen_instructor_id']+')"><span class="glyphicon glyphicon-edit"></span></button></td></tr>'; no++; }) $('#edit-presensi-content').empty(); $('#edit-presensi-content').html(str); $('#table-edit-presensi-content').dataTable(); }); } function form_edit_presensi_instruktur(id_absen){ var tipe,instruktur,kelas,materi,str = '<div class="panel panel-default"><div class="panel-body">'+ '<form id="frm-detail-edit-presensi-content" onSubmit="return false">'+ '<input type="hidden" name="hid_id_presensi" value="'+ id_absen +'" />'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-2 col-sm-2">Tipe Instruktur</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<label class="radio-inline">'+ '<input type="radio" name="rad_tipe" id="rad_tipe1" value="Internal">Internal</label>'+ '<label class="radio-inline">'+ '<input type="radio" name="rad_tipe" id="rad_tipe2" value="External">External</label>'+ '</div>'+ '</div><div id="pil_instruktur_data" style="padding:2px;"></div>'; str = str + '<div class="row" style="padding:2px;">'+ '<div class="col-xs-2 col-sm-2">Kelas</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_kelas" id="txt_kelas" class="form-control" placeholder="Nama Kelas"/>'+ '<input type="hidden" name="hid_id_kelas" id="hid_id_kelas" value="" />'+ '</div>'+ '<div class="cols-xs-12 col-sm-2"><div id="kelas-container"></div></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-2 col-sm-2">Materi</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_materi" id="txt_materi" class="form-control" placeholder="Materi Ajar"/>'+ '<input type="hidden" name="hid_id_materi" id="hid_id_materi" value="" />'+ '</div>'+ '<div class="cols-xs-12 col-sm-2"><div id="materi-container"></div></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-2">Waktu Mulai</div>'+ '<div class="col-xs-12 col-sm-4"><input id="spinner_jam_mulai" name="jam_mulai" size="3" value="0" placeholder="Jam" class="spinner" />&nbsp;:&nbsp;<input id="spinner_menit_mulai" name="menit_mulai" size="3" value="0" class="spinner" placeholder="Menit" /></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-2">Waktu Selesai</div>'+ '<div class="col-xs-12 col-sm-4"><input id="spinner_jam_selesai" name="jam_selesai" size="3" value="0" placeholder="Jam" class="spinner" />&nbsp;:&nbsp;<input id="spinner_menit_selesai" name="menit_selesai" size="3" value="0" class="spinner" placeholder="Menit" /></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="Submit" value="Simpan" onClick="edit_presensi_instruktur_last()" />'+ '<button onClick="display_edit_presensi_instructor()">Back</button>'+ '</div>'+ '</div>'+ '</form>'+ '</div></div>'; $('#edit-presensi').empty(); $('#edit-presensi').html(str); //Spinner jam_awal = $( "#spinner_jam_mulai" ).spinner({max:23,min:0,numberFormat:'n'}); jam_selesai = $( "#spinner_menit_mulai" ).spinner({max:59,min:0,numberFormat:'n'}); menit_awal = $( "#spinner_jam_selesai" ).spinner({max:23,min:0,numberFormat:'n'}); menit_selesai = $( "#spinner_menit_selesai" ).spinner({max:59,min:0,numberFormat:'n'}); //$(".spinner").bind("keydown", function (event) { //event.preventDefault(); // }); //Get Value $.get('<?php echo site_url('training/detail_presensi')?>/' + id_absen,{}).done(function(response){ //alert(JSON.stringify(response)); switch(response[0].INSTRUCTOR_TYPE.toLowerCase()){ case 'internal' : $('#rad_tipe1').attr('checked',true); tipe = $('input[type=radio][name=rad_tipe]').val(); display_input_name_presensi(tipe); $('#txt_npp').val(response[0].INSTRUCTOR_NPP); $('#instruktur_presensi_input').html(response[0].INSTRUCTOR_NAME); $('#hid_id_instruktur').val(response[0].m_instructor_id); break; case 'external' : $('#rad_tipe2').attr('checked'); tipe = $('input[type=radio][name=rad_tipe]').val(); display_input_name_presensi(tipe); $('#txt_nama').val(response[0].INSTRUCTOR_NAME); $('#instruktur_presensi_input').html(response[0].VENDOR_ID); $('#hid_id_instruktur').val(response[0].m_instructor_id); break; } $('#txt_kelas').val(response[0].TRAINING); $('#hid_id_kelas').val(response[0].frametext_id); $('#txt_materi').val(response[0].MODULE_NAME); $('#hid_id_materi').val(response[0].m_module_id); $('#spinner_jam_mulai').val(response[0].jam_mulai.substring(0,2)); $('#spinner_menit_selesai').val(response[0].jam_mulai.substring(3,5)); $('#spinner_jam_selesai').val(response[0].jam_selesai.substring(0,2)); $('#spinner_menit_mulai').val(response[0].jam_selesai.substring(3,5)); instruktur = get_data_instruktur(tipe); kelas = get_data_kelas_all(); materi = get_data_materi(); set_autocomplete_presensi(tipe,instruktur,kelas,materi); $('input[type=radio][name=rad_tipe]').change(function(){ tipe = $(this).val(); display_input_name_presensi(tipe); instruktur = get_data_instruktur(tipe); kelas = get_data_kelas_all(); materi = get_data_materi(); set_autocomplete_presensi(tipe,instruktur,kelas,materi); }); }); } function display_input_name_presensi(tipe){ var str; switch(tipe.toLowerCase()){ case 'internal': str = '<div class="row"><div class="col-xs-2 col-sm-2">NPP</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_npp" id="txt_npp" class="form-control" placeholder="NPP Instruktur"/>'+ '<input type="hidden" name="hid_id_instruktur" id="hid_id_instruktur" value="" />'+ '</div></div>'+ '<div class="row"><div class="col-xs-2 col-sm-2">Nama</div>'+ '<div class="col-xs-12 col-sm-4" id="instruktur_presensi_input"></div></div>'; break; case 'external': str = '<div class="row"><div class="col-xs-2 col-sm-2">Nama Instruktur</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_nama" id="txt_nama" class="form-control" placeholder="Nama Instruktur"/>'+ '<input type="hidden" name="hid_id_instruktur" id="hid_id_instruktur" value="" />'+ '</div></div>'+ '<div class="row"><div class="col-xs-2 col-sm-2">Vendor</div>'+ '<div class="col-xs-12 col-sm-4" id="instruktur_presensi_input"></div></div>'; break; } str = str + '<div id="instruktur-container"></div>'; $('#pil_instruktur_data').empty(); $('#pil_instruktur_data').html(str); } function set_autocomplete_presensi(tipe,instruktur,kelas,materi){ $('#instruktur_presensi_input').empty(); switch(tipe.toLowerCase()){ case 'internal' : $('#txt_npp').autocomplete({ source:instruktur[1], appendTo: '#instruktur-container', select: function(event,ui){ index = $.inArray(ui.item.value,instruktur[1]); $('#hid_id_instruktur').val(instruktur[0][index]); $('#instruktur_presensi_input').html(instruktur[2][index]); $('#txt_npp').val(instruktur[1][index]); $('.ui-helper-hidden-accessible').empty(); return false; } }); $('#txt_kelas').autocomplete({ source:kelas[1], appendTo: '#kelas-container', open: function(){ $(this).autocomplete('widget').css('z-index', 30); return false; }, select: function(event,ui){ index = $.inArray(ui.item.value,kelas[1]); $('#hid_id_kelas').val(kelas[0][index]); $('#txt_kelas').val(kelas[1][index]); $('.ui-helper-hidden-accessible').empty(); return false; } }); $('#txt_materi').autocomplete({ source:materi[1], appendTo: '#materi-container', select: function(event,ui){ index = $.inArray(ui.item.value,materi[1]); $('#hid_id_materi').val(materi[0][index]); $('#txt_materi').val(materi[1][index]); $('.ui-helper-hidden-accessible').empty(); return false; } }); break; case 'external' : $('#txt_nama').autocomplete({ source:instruktur[2], appendTo: '#instruktur-container', select: function(event,ui){ index = $.inArray(ui.item.value,instruktur[2]); $('#hid_id_instruktur').val(instruktur[0][index]); $('#instruktur_presensi_input').html(instruktur[3][index]); $('#txt_nama').val(instruktur[2][index]); $('.ui-helper-hidden-accessible').empty(); return false; } }); $('#txt_kelas').autocomplete({ source:kelas[1], appendTo: '#kelas-container', select: function(event,ui){ index = $.inArray(ui.item.value,kelas[1]); $('#hid_id_kelas').val(kelas[0][index]); $('#txt_kelas').val(kelas[1][index]); $('.ui-helper-hidden-accessible').empty(); return false; } }); $('#txt_materi').autocomplete({ source:materi[1], appendTo: '#materi-container', select: function(event,ui){ index = $.inArray(ui.item.value,materi[1]); $('#hid_id_materi').val(materi[0][index]); $('#txt_materi').val(materi[1][index]); $('.ui-helper-hidden-accessible').empty(); return false; } }); break; } } function get_data_instruktur(tipe){ var i,result = [],instruktur_id=[],instruktur_name=[],instructor_npp=[],instruktur_vendor=[]; $.ajaxSetup({ async: false }); switch(tipe.toLowerCase()){ case 'internal' : $.get('<?php echo site_url('training/internal');?>',{}).done(function(response){ i = 0; $.each(response,function(index,value){ instruktur_id[i]=value['INSTRUCTOR_ID']; instructor_npp[i]=value['INSTRUCTOR_NPP']; instruktur_name[i]=value['INSTRUCTOR_NAME']; i++; }); }); $.ajaxSetup({ async: true }); break; case 'external' : $.get('<?php echo site_url('training/eksternal');?>',{}).done(function(response){ i = 0; $.each(response,function(index,value){ instruktur_id[i]=value['INSTRUCTOR_ID']; instruktur_name[i]=value['INSTRUCTOR_NAME']; instruktur_vendor[i]=value['VENDOR_NAME']; i++; }); }); break; } $.ajaxSetup({ async: true }); result[0]=instruktur_id; result[1]=instructor_npp; result[2]=instruktur_name; result[3]=instruktur_vendor; return result; } function get_data_kelas(){ var i,result = [],kelas_id=[],kelas_name=[]; $.ajaxSetup({ async: false }); $.get('<?php echo site_url('training/kelas');?>',{}).done(function(response){ i=0; $.each(response,function(index,value){ kelas_id[i] = value['FRAMETEXT_ID']; kelas_name[i] = value['TRAINING']; i++; }); }); $.ajaxSetup({ async: true }); result[0] = kelas_id; result[1] = kelas_name; return result; } function get_data_kelas_all(){ var i,result = [],kelas_id=[],kelas_name=[]; $.ajaxSetup({ async: false }); $.get('<?php echo site_url('training/kelas_all');?>',{}).done(function(response){ i=0; $.each(response,function(index,value){ kelas_id[i] = value['FRAMETEXT_ID']; kelas_name[i] = value['TRAINING']; i++; }); }); $.ajaxSetup({ async: true }); result[0] = kelas_id; result[1] = kelas_name; return result; } function get_data_materi(){ var i,result = [],module_name = [],module_id=[]; $.ajaxSetup({ async: false }); $.get('<?php echo site_url('training/materi');?>',{}).done(function(response){ i=0; $.each(response,function(index,value){ module_id[i] = value['MODULE_ID']; module_name[i] = value['MODULE_NAME']; i++; }); }); $.ajaxSetup({ async: true }); result[0] = module_id; result[1] = module_name; return result; } function display_data_content_presensi(){ var no,str = '<table class="table table-striped table-hover" id="dataTables-example"><tr><thead><tr><th>No</th><th>Kelas</th><th>Mulai</th><th>Akhir</th><th>Instructor</th><th>Type</th><th>Materi</th><th>Jumlah Jam</th>'; <?php ################### For Priviledge by Session echo "str = str + '<th>Action</th>';"; ?> str = str + '</tr></thead></tr><tbody>'; $.get('<?php echo site_url("training/presensi");?>',{}).done(function(response){ no = 1; $.each(response,function(index,value){ str = str + '<tr><td>'+ no +'</td><td>'+ value['TRAINING'] +'</td><td>'+ value['TGLMULAI'] +'</td><td>'+ value['TGLAKHIR'] +'</td><td>'+ value['INSTRUCTOR_NAME'] +'</td><td>'+ value['INSTRUCTOR_TYPE'] +'</td><td>'+ value['MODULE_NAME']+'</td><td>'+ value['jumlah_jam']; <?php ################## For Priviledge by Session echo "str = str + '<td><button onClick=\"display_edit_presensi_instruktur('+value['t_absen_instructor_id']+')\"><span class=\"glyphicon glyphicon-edit\"></span></button></td>';"; ?> str = str + '</tr>'; no++; }); str = str + '</tbody></table>'; $('#data_content_presensi').empty(); $('#data_content_presensi').html(str); //$('#table-data-content-presensi').dataTable(); }); } function add_presensi_instruktur(){ var data = $('#frm_presensi').serialize(); $.get('<?php echo site_url('training/add_presensi/');?>',data).done(function(response){ document.getElementById('frm_presensi').reset(); $('#instruktur_presensi_input').empty(); display_data_content_presensi(); }); } function display_edit_presensi_instruktur(id_presensi){ var instruktur,kelas,materi,jam_awal,jam_selesai,menit_awal,menit_selesai,str = '<div class="panel panel-default"><div class="panel-body">'+ '<form id="frm_edit_presensi" onSubmit="return false">'+ '<input type="hidden" name="hid_id_presensi" value="'+ id_presensi +'" />'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-2">Tipe Instruktur</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<label class="radio-inline">'+ '<input type="radio" name="rad_tipe" id="rad_tipe1" value="Internal">Internal</label>'+ '<label class="radio-inline">'+ '<input type="radio" name="rad_tipe" id="rad_tipe2" value="External">External</label>'+ '</div>'+ '</div>'+ '<div id="pil_instruktur_data"></div>'; str = str + '<div class="row" style="padding:2px;">' + '<div class="col-xs-12 col-sm-2">Kelas</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_kelas" id="txt_kelas" class="form-control" placeholder="Nama Kelas"/>'+ '<input type="hidden" name="hid_id_kelas" id="hid_id_kelas" value="" />'+ '</div>'+ '</div>'+ '<div class="row" ><div class="cols-xs-12 col-sm-2"><div id="kelas-container"></div></div></div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-2">Materi</div>'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="text" name="txt_materi" id="txt_materi" class="form-control" placeholder="Materi Ajar"/>'+ '<input type="hidden" name="hid_id_materi" id="hid_id_materi" value="" />'+ '</div>'+ '</div>'+ '<div class="row" ><div class="cols-xs-12 col-sm-2"><div id="materi-container"></div></div></div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-2">Waktu Mulai</div>'+ '<div class="col-xs-12 col-sm-4"><input id="spinner_jam_mulai" name="jam_mulai" size="3" value="0" placeholder="Jam" class="spinner" />&nbsp;:&nbsp;<input id="spinner_menit_mulai" name="menit_mulai" size="3" value="0" class="spinner" placeholder="Menit" /></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-2">Waktu Selesai</div>'+ '<div class="col-xs-12 col-sm-4"><input id="spinner_jam_selesai" name="jam_selesai" size="3" value="0" placeholder="Jam" class="spinner" />&nbsp;:&nbsp;<input id="spinner_menit_selesai" name="menit_selesai" size="3" value="0" class="spinner" placeholder="Menit" /></div>'+ '</div>'+ '<div class="row" style="padding:2px;">'+ '<div class="col-xs-12 col-sm-4">'+ '<input type="Submit" value="Simpan" onClick="edit_presensi_instruktur()" />'+ '<button onClick="display_presensi_instructor()">Back</button>'+ '</div>'+ '</div>'+ '</form></div></div>'; $('#presensi').empty(); $('#presensi').html(str); //Spinner jam_awal = $( "#spinner_jam_mulai" ).spinner({max:23,min:0,numberFormat:'n'}); jam_selesai = $( "#spinner_menit_mulai" ).spinner({max:59,min:0,numberFormat:'n'}); menit_awal = $( "#spinner_jam_selesai" ).spinner({max:23,min:0,numberFormat:'n'}); menit_selesai = $( "#spinner_menit_selesai" ).spinner({max:59,min:0,numberFormat:'n'}); //$(".spinner").bind("keydown", function (event) { //event.preventDefault(); // }); //Get Value $.get('<?php echo site_url('training/detail_presensi')?>/' + id_presensi,{}).done(function(response){ switch(response[0].INSTRUCTOR_TYPE.toLowerCase()){ case 'internal' : $('#rad_tipe1').attr('checked',true); tipe = $('input[type=radio][name=rad_tipe]').val(); display_input_name_presensi(tipe); $('#txt_npp').val(response[0].INSTRUCTOR_NPP); $('#instruktur_presensi_input').html(response[0].INSTRUCTOR_NAME); $('#hid_id_instruktur').val(response[0].m_instructor_id); break; case 'external' : $('#rad_tipe2').attr('checked'); tipe = $('input[type=radio][name=rad_tipe]').val(); display_input_name_presensi(tipe); $('#txt_nama').val(response[0].INSTRUCTOR_NAME); $('#instruktur_presensi_input').html(response[0].VENDOR_ID); $('#hid_id_instruktur').val(response[0].m_instructor_id); break; } $('#txt_kelas').val(response[0].TRAINING); $('#hid_id_kelas').val(response[0].frametext_id); $('#txt_materi').val(response[0].MODULE_NAME); $('#hid_id_materi').val(response[0].m_module_id); $('#spinner_jam_mulai').val(response[0].jam_mulai.substring(0,2)); $('#spinner_menit_selesai').val(response[0].jam_mulai.substring(3,5)); $('#spinner_jam_selesai').val(response[0].jam_selesai.substring(0,2)); $('#spinner_menit_mulai').val(response[0].jam_selesai.substring(3,5)); instruktur = get_data_instruktur(tipe); kelas = get_data_kelas(); materi = get_data_materi(); set_autocomplete_presensi(tipe,instruktur,kelas,materi); $('input[type=radio][name=rad_tipe]').change(function(){ tipe = $(this).val(); display_input_name_presensi(tipe); instruktur = get_data_instruktur(tipe); kelas = get_data_kelas(); materi = get_data_materi(); set_autocomplete_presensi(tipe,instruktur,kelas,materi); }); }); } function edit_presensi_instruktur(){ var data = $('#frm_edit_presensi').serialize(); $.get('<?php echo site_url('training/edit_presensi');?>/',data).done(function(response){ display_presensi_instructor(); }); } function edit_presensi_instruktur_last(){ var data = $('#frm-detail-edit-presensi-content').serialize(); $.get('<?php echo site_url('training/edit_presensi');?>/',data).done(function(response){ display_edit_presensi_instructor(); }); } // End Presensi_Instructor_Function /* End Instructor Function */ </script>
{ "content_hash": "1c686f3dcecc674fcb11d944dcf07a4c", "timestamp": "", "source": "github", "line_count": 1115, "max_line_length": 547, "avg_line_length": 45.19820627802691, "alnum_prop": 0.5956226684657513, "repo_name": "dodolangus/rep_bnv_app", "id": "d9936d74d837696efb03c55eccd7248dc85241e2", "size": "50396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/training/v_homepage.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "213" }, { "name": "CSS", "bytes": "557405" }, { "name": "HTML", "bytes": "192884" }, { "name": "JavaScript", "bytes": "1067600" }, { "name": "PHP", "bytes": "7468052" }, { "name": "Shell", "bytes": "5724" } ], "symlink_target": "" }
package gw.internal.xml.ws.http.fragment; import gw.internal.xml.ws.http.HttpException; import gw.internal.xml.ws.http.HttpParseContext; import java.io.UnsupportedEncodingException; import java.util.Collections; import java.util.HashSet; import java.util.Set; public abstract class HttpFragment { private static final Set<Byte> _separators = makeCharacterSet( "()<>@,;:\\\"/[]?={} \t" ); protected void consumeOptionalWhitespace( HttpParseContext context ) { Byte ch = context.get(); if ( ch != null ) { // first, consume optional leading CRLF if ( ch == 13 ) { context.next(); consumeChar( context, (byte) 10 ); } while ( true ) { ch = context.get(); if ( ch == null || ( ch != '\t' && ch != ' ' ) ) { break; } context.next(); } } } protected void consumeChar( HttpParseContext context, byte c ) { if ( context.get() != c ) { throw new HttpException( "Expected " + c + " but found " + context.get() ); } context.next(); } protected boolean consumeOptionalChar( HttpParseContext context, byte c ) { Byte ch = context.get(); if ( ch == null || ch != c ) { // ch != c would throw an NPE if ch is null due to unboxing, which is why the null check is needed separately return false; } context.next(); return true; } protected boolean isSeparator( byte ch ) { return _separators.contains( ch ); } protected boolean isCtl( byte ch ) { return ch < 32 || ch == 127; } private static Set<Byte> makeCharacterSet( String chars ) { byte[] bytes; try { bytes = chars.getBytes( "US-ASCII" ); } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException( ex ); // should never happen with US-ASCII } Set<Byte> ret = new HashSet<Byte>(); for ( byte b : bytes ) { ret.add( b ); } return Collections.unmodifiableSet( ret ); } }
{ "content_hash": "df0cad1f9a9a20381291cd7e9a89c221", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 144, "avg_line_length": 26.594594594594593, "alnum_prop": 0.6026422764227642, "repo_name": "gosu-lang/old-gosu-repo", "id": "72f9df49a075cfc77af7c1ff55a4deaebcf6fc73", "size": "2017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gosu-webservices/src/main/java/gw/internal/xml/ws/http/fragment/HttpFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1793" }, { "name": "Gosu", "bytes": "977856" }, { "name": "Java", "bytes": "15187915" }, { "name": "JavaScript", "bytes": "27526" }, { "name": "Objective-C", "bytes": "56237" }, { "name": "Shell", "bytes": "1423" } ], "symlink_target": "" }
// // Created by XinghuiQuan on 8/5/15. // #include <jni.h> #include <sys/socket.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/un.h> #include <sys/signal.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include "Common.h" #define BUFFSIZE 32 #define FP fprintf #include <android/log.h> //#define TAG "daemon.c" #define TAG "xinghui" // some phone can't print INFO Log #define LOGI(...) __android_log_print(ANDROID_LOG_ERROR,TAG, "--------INFO--" __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG, "--------ERROR---" __VA_ARGS__) #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, "--------ERROR---" __VA_ARGS__) int main(int argc) { } typedef struct _JNI_THREAD_OBJ { // int connectfd; int socketfd; const char *user; const char *packageName; } JNI_THREAD_OBJ; void *fun_in_thread(void *args) { JNI_THREAD_OBJ *jniThreadObj = (JNI_THREAD_OBJ *) args; // int connectfd = jniThreadObj->connectfd;; const char *user = jniThreadObj->user; const char *packageName = jniThreadObj->packageName; LOGI("fun_in_thread()11 packageName = %s, user = %s", packageName, user); // LOGI("fun_in_thread()22 socketfd = %d, packageName = %s, user = %s", jniThreadObj->socketfd, jniThreadObj->packageName, jniThreadObj->user); int connectfd; int socketfd; sockaddr_un addr; // Local Communication if ((socketfd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) { return 0; } // unlink(filePath);// method 1 addr.sun_family = PF_LOCAL; strcpy(addr.sun_path, SERVER_NAME);// method 1 unlink(SERVER_NAME); // memset(&addr, 0, sizeof(addr)); // addr.sun_path[0] = 0;// method 2 // strcpy(addr.sun_path + 1, SERVER_NAME);// method 2 // int server_addr_length = sizeof(addr); // method 1 // int server_addr_length = strlen(SERVER_NAME) + offsetof(struct sockaddr_un, sun_path);// method 2 int server_addr_length = sizeof(addr.sun_family) + sizeof(SERVER_NAME); LOGI("sun_path is %s, server_addr_length = %d, sun_path = %s", SERVER_NAME, server_addr_length, &addr.sun_path); LOGI("bind start"); if (bind(socketfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) // if(bind(socketfd, (struct sockaddr*) &addr, server_addr_length) < 0) { LOGE("bind socket error : %d", errno); unlink(SERVER_NAME); return 0; } LOGI("bind ok"); LOGI("listen start"); if (listen(socketfd, 10) == -1) { LOGI("listen socket error : %d", errno); unlink(SERVER_NAME); return 0; } LOGI("listen ok"); sockaddr_un client_addr; socklen_t client_addr_len; client_addr_len = sizeof(client_addr); while (1) { LOGE("while!!!!!!!!"); connectfd = accept(socketfd, (struct sockaddr *) NULL, NULL); LOGE("while!!!!!!!! %d", connectfd); if (connectfd < 0) { LOGE("accept!!!!!!!!"); if (errno == EINTR) { LOGE("accept error == EINTR (EINTR = %d)", EINTR); // continue; return 0; } else { LOGI("accept error : %d", errno); return 0; } } else { LOGI("sss"); char buff[1024]; int n = recv(connectfd, buff, sizeof(buff), 0); LOGI("xinghui recv n = %d", n); if (n < 0) { LOGI("xinghui recv n < 0, n = %d", n); LOGI("ead failed (%s), n = %d ", strerror(errno), n); } else if (n == 0) { int user_len = strlen(user); LOGI("1channel detached remotely, user_len = %d", user_len); close(connectfd); char c[128]; if (user_len >= 0) { // sprintf(c, "am startservice --user 0 -n %s/.daemon.RestartService", packageName); sprintf(c, "am startservice --user 0 -n com.xinghui.nativedaemonprocess/.daemon.RestartService"); } else { sprintf(c, "am startservice -n %s/.daemon.RestartService", packageName); } LOGI("str length: %d, %s", strlen(c), c); LOGI("xinghui recv n == 0"); system(c); // return 0;//break; } char *cp = buff; LOGI("cp----- %s", cp); // kill(getpid(), SIGQUIT); } } } int create_socket(/*const char* filePath, */const char *packageName, const char *user) { pthread_t pt; JNI_THREAD_OBJ *jniThreadObj = new JNI_THREAD_OBJ; // jniThreadObj->connectfd = connectfd; // jniThreadObj->socketfd = socketfd; jniThreadObj->packageName = packageName; jniThreadObj->user = user; // LOGI("create_socket()11 socketfd = %d, packageName = %s, user = %s", socketfd, packageName, user); // LOGI("create_socket()22 socketfd = %d, packageName = %s, user = %s", jniThreadObj->socketfd, jniThreadObj->packageName, jniThreadObj->user); pthread_create(&pt, NULL, fun_in_thread, jniThreadObj); return 0; } extern "C" { JNIEXPORT jint JNICALL Java_com_xinghui_nativedaemonprocess_DaemonNativeUtils_start(JNIEnv *env, jclass cls, jstring packageName, jstring user) { const char *packageName_char = env->GetStringUTFChars(packageName, NULL); env->ReleaseStringUTFChars(packageName, packageName_char); // const char* path_char = env->GetStringUTFChars(path, NULL); // env->ReleaseStringUTFChars(path, path_char); const char *user_char = NULL; if (user != NULL) { user_char = env->GetStringUTFChars(user, NULL); env->ReleaseStringUTFChars(user, user_char); } pid_t pid; pid_t sid; LOGI("fork"); pid = fork(); if (pid == 0) { LOGI("daemon process"); const char *new_name; new_name = "xinghui";// TODO for test prctl(PR_SET_NAME, new_name, 0, 0, 0); // LOGI("daemon process group id = %d", getpgrp()); sid = setsid(); // LOGI("daemon process group id = %d, sid = %d, pid = %d", getpgrp(), sid, getpid()); if (sid < 0) { LOGI("setsid sid = %d ", sid); } // signal(SIGINT, SIG_IGN); // signal(SIGHUP, SIG_IGN); // signal(SIGQUIT, SIG_IGN); // signal(SIGPIPE, SIG_IGN); // signal(SIGTTOU, SIG_IGN); // signal(SIGTTIN, SIG_IGN); // signal(SIGCHLD, SIG_IGN); // signal(SIGTERM, SIG_IGN); // // signal(SIGSEGV, SIG_IGN); // struct sigaction sig; // sig.sa_handler = SIG_IGN; // sig.sa_flags = 0; // sigemptyset(&sig.sa_mask); // sigaction(SIGPIPE, &sig, NULL);// TODO check chdir("/"); umask(0); create_socket(packageName_char, user_char); } else if (pid > 0) { LOGI("main process pid = %d", pid); } return pid; } } extern "C" { jstring Java_com_xinghui_nativedaemonprocess_DaemonNativeUtils_stringFromJNI(JNIEnv *env, jclass thiz) { #if defined(__arm__) #if defined(__ARM_ARCH_7A__) #if defined(__ARM_NEON__) #if defined(__ARM_PCS_VFP) #define ABI "armeabi-v7a/NEON (hard-float)" #else #define ABI "armeabi-v7a/NEON" #endif #else #if defined(__ARM_PCS_VFP) #define ABI "armeabi-v7a (hard-float)" #else #define ABI "armeabi-v7a" #endif #endif #else #define ABI "armeabi" #endif #elif defined(__i386__) #define ABI "x86" #elif defined(__x86_64__) #define ABI "x86_64" #elif defined(__mips64) /* mips64el-* toolchain defines __mips__ too */ #define ABI "mips64" #elif defined(__mips__) #define ABI "mips" #elif defined(__aarch64__) #define ABI "arm64-v8a" #else #define ABI "unknown" #endif LOGV("------"); jstring str = env->NewStringUTF("Hello from JNI! Compiled with ABI " ABI "."); return str; } } extern "C" { JNIEXPORT jint JNICALL Java_com_xinghui_nativedaemonprocess_DaemonNativeUtils_connectToDaemonSocketServer( JNIEnv *env, jclass cls) { struct sockaddr_un addr; int retry_time = 5; int result = -1; size_t namelen = strlen(SERVER_NAME); while (retry_time) { retry_time--; sleep(2); // memset(&addr, 0, sizeof(addr)); // addr.sun_family = PF_LOCAL; // addr.sun_path[0] = 0; // memcpy(addr.sun_path + 1, SERVER_NAME, namelen); // // socklen_t alen = namelen + offsetof(struct sockaddr_un, sun_path) + 1; //// strcpy(addr.sun_path + 1, SERVER_NAME); int socketfd = socket(PF_LOCAL, SOCK_STREAM, 0); if (socketfd == -1) { LOGV("main process create socket error: %d", errno); continue; } addr.sun_family = PF_LOCAL; strcpy(addr.sun_path, SERVER_NAME); // int server_addr_length = strlen(SERVER_NAME) + offsetof(struct sockaddr_un, sun_path); // int server_addr_length = sizeof(addr.sun_family) + sizeof(SERVER_NAME); if (connect(socketfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { LOGV("connect socket failed retry_time = %d, errorno = %d", retry_time, errno); close(socketfd); continue; } else { result = 0; LOGV("connect socket success_____________ retry_time = %d", retry_time); return result; } } return result; } }
{ "content_hash": "c1bf9409aedeaf0b350977eeb0b11593", "timestamp": "", "source": "github", "line_count": 333, "max_line_length": 147, "avg_line_length": 29.73273273273273, "alnum_prop": 0.5386324613675386, "repo_name": "xinghui/AndroidNativeDaemon", "id": "74ebe95b858648711cf827566f085561466aad5d", "size": "9901", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/jni/daemon.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "991" }, { "name": "C++", "bytes": "9901" }, { "name": "Java", "bytes": "9082" } ], "symlink_target": "" }
Router.configure({ layoutTemplate: 'main', loadingTemplate: 'loading' }); if(Meteor.isClient){ // client code goes here // Meteor.subscribe('lists'); // Meteor.subscribe('todos'); Template.lists.onCreated(function () { this.subscribe('lists'); }); $.validator.setDefaults({ rules: { email: { required: true, email: true }, password: { required: true, minlength: 6 } }, messages: { email: { required: "You must enter an email address.", email: "You've entered an invalid email address." }, password: { required: "You must enter a password.", minlength: "Your password must be at least {0} characters." } } }); Template.login.onCreated(function(){ console.log("The 'login' template was just created."); }); Template.login.onRendered(function(){ var validator = $('.login').validate({ submitHandler: function(event){ var email = $('[name=email]').val(); var password = $('[name=password]').val(); Meteor.loginWithPassword(email, password, function(error){ if(error){ if(error.reason == "User not found"){ validator.showErrors({ email: "That email doesn't belong to a registered user." }); } if(error.reason == "Incorrect password"){ validator.showErrors({ password: "You entered an incorrect password." }); } } else { var currentRoute = Router.current().route.getName(); if(currentRoute == "login"){ Router.go("home"); } } }); } }); }); Template.login.onDestroyed(function(){ console.log("The 'login' template was just destroyed."); }); Template.register.onRendered(function(){ var validator = $('.register').validate({ submitHandler: function(event){ var email = $('[name=email]').val(); var password = $('[name=password]').val(); Accounts.createUser({ email: email, password: password }, function(error){ if(error){ if(error){ if(error.reason == "Email already exists."){ validator.showErrors({ email: "That email already belongs to a registered user." }); } } } else { Router.go("home"); } }); } }); }); // Helpers Template.todos.helpers({ 'todo': function(){ var currentList = this._id; var currentUser = Meteor.userId(); return Todos.find({ listId: currentList, createdBy: currentUser }, {sort: {createdAt: -1}}) } }); Template.todoItem.helpers({ 'checked': function(){ var isCompleted = this.completed; if(isCompleted){ return "checked"; } else { return ""; } } }); Template.todosCount.helpers({ // helpers go here 'totalTodos': function(){ var currentList = this._id; return Todos.find({ listId: currentList }).count(); }, 'completedTodos': function(){ var currentList = this._id; return Todos.find({ listId: currentList, completed: true }).count(); } }); Template.lists.helpers({ 'list': function(){ var currentUser = Meteor.userId(); return Lists.find({ createdBy: currentUser }, {sort: {name: 1}}) } }); Template.home.helpers({ 'loggedUser': function(){ var loggedUser = Meteor.user(); // Taken from http://stackoverflow.com/questions/14346422/how-to-get-logged-in-user-email-in-publish-functions-in-meteor return loggedUser.emails[0].address; } }); //Events Template.addTodo.events({ // events go here 'submit form': function(event){ event.preventDefault(); // uso de jQuery para recuperar el valor del nombre, ver página 18 var todoName = $('[name="todoName"]').val(); var currentUser = Meteor.userId(); var currentList = this._id; Meteor.call('createListItem', todoName, currentList, function(error){ if(error){ console.log(error.reason); } else { $('[name="todoName"]').val(''); } }); } }); Template.todoItem.events({ // events go here 'click .delete-todo': function(event){ event.preventDefault(); var documentId = this._id; var confirm = window.confirm("Delete this task?"); if(confirm){ Meteor.call('removeListItem', documentId); } }, 'keyup [name=todoItem]': function(event){ if(event.which == 13 || event.which == 27){ $(event.target).blur(); } else { var documentId = this._id; var todoItem = $(event.target).val(); Meteor.call('updateListItem', documentId, todoItem); } }, 'change [type=checkbox]': function(){ var documentId = this._id; var isCompleted = this.completed; if(isCompleted){ Meteor.call('changeItemStatus', documentId, false); } else { Meteor.call('changeItemStatus', documentId, true); } } }); Template.addList.events({ 'submit form': function(event){ event.preventDefault(); var listName = $('[name=listName]').val(); Meteor.call('createNewList', listName, function(error, results){ if(error) { console.log(error.reason); } else { Router.go('listPage', { _id: results }); $('[name=listName]').val(''); } }); } }); Template.register.events({ 'submit form': function(event){ event.preventDefault(); } }); Template.register.onRendered(function(){ $('.register').validate(); }); Template.navigation.events({ 'click .logout': function(event){ event.preventDefault(); Meteor.logout(); Router.go('login'); } }); Template.login.events({ 'submit form': function(event){ event.preventDefault(); } }); Template.lists.events({ 'click .delete-list': function(event){ event.preventDefault(); var documentId = this._id; var confirm = window.confirm("Delete this list?"); if(confirm){ Meteor.call('removeList', documentId); } } }); } if(Meteor.isServer){ // server code goes here function defaultName(currentUser) { var nextLetter = 'A' var nextName = 'List ' + nextLetter; while (Lists.findOne({ name: nextName, createdBy: currentUser })) { nextLetter = String.fromCharCode(nextLetter.charCodeAt(0) + 1); nextName = 'List ' + nextLetter; } return nextName; } Meteor.methods({ 'createNewList': function(listName){ // code goes here var currentUser = Meteor.userId(); check(listName, String); if(listName == ""){ listName = defaultName(currentUser); } var data = { name: listName, createdBy: currentUser } if(!currentUser){ throw new Meteor.Error("not-logged-in", "You're not logged-in."); } else { return Lists.insert(data); } }, 'createListItem': function(todoName, currentList){ check(todoName, String); check(currentList, String); var currentUser = Meteor.userId(); var data = { name: todoName, completed: false, createdAt: new Date(), createdBy: currentUser, listId: currentList } if(!currentUser){ throw new Meteor.Error("not-logged-in", "You're not logged-in."); } var currentList = Lists.findOne(currentList); if(currentList.createdBy != currentUser){ throw new Meteor.Error("invalid-user", "You don't own that list."); } return Todos.insert(data); }, 'updateListItem': function(documentId, todoItem){ check(todoItem, String); var currentUser = Meteor.userId(); var data = { _id: documentId, createdBy: currentUser } if(!currentUser){ throw new Meteor.Error("not-logged-in", "You're not logged-in."); } Todos.update(data, {$set: { name: todoItem }}); }, 'changeItemStatus': function(documentId, status){ check(status, Boolean); var currentUser = Meteor.userId(); var data = { _id: documentId, createdBy: currentUser } if(!currentUser){ throw new Meteor.Error("not-logged-in", "You're not logged-in."); } Todos.update(data, {$set: { completed: status }}); }, 'removeListItem': function(documentId){ var currentUser = Meteor.userId(); var data = { _id: documentId, createdBy: currentUser } if(!currentUser){ throw new Meteor.Error("not-logged-in", "You're not logged-in."); } Todos.remove(data); }, 'removeList': function(documentId){ var currentUser = Meteor.userId(); var data = { _id: documentId, createdBy: currentUser } if(!currentUser){ throw new Meteor.Error("not-logged-in", "You're not logged-in."); } Lists.remove(data); } }); Meteor.publish('lists', function(){ var currentUser = this.userId; return Lists.find({ createdBy: currentUser }); }); Meteor.publish('todos', function(currentList){ var currentUser = this.userId; return Todos.find({ createdBy: currentUser, listId: currentList }) }); } Todos = new Meteor.Collection('todos'); Lists = new Meteor.Collection('lists'); Router.route('/register'); Router.route('/login'); Router.route('/', { name: 'home', template: 'home' }); Router.route('/list/:_id', { name: 'listPage', template: 'listPage', data: function(){ var currentList = this.params._id; var currentUser = Meteor.userId(); return Lists.findOne({ _id: currentList, createdBy: currentUser }); }, onBeforeAction: function(){ var currentUser = Meteor.userId(); if(currentUser){ this.next(); } else { this.render("login"); } }, waitOn: function(){ var currentList = this.params._id; return Meteor.subscribe('todos', currentList); } }); //Router.route('/', { // name: 'home', // template: 'home', // subscriptions: function(){ // var currentList = this.params._id; // return [ Meteor.subscribe('lists'), Meteor.subscribe('todos', currentList) ] // } //}); //Router.route('/list/:_id', { // name: 'listPage', // template: 'listPage', // data: function(){ // // console.log(this.params._id); // var currentList = this.params._id; // var currentUser = Meteor.userId(); // return Lists.findOne({ _id: currentList, createdBy: currentUser }); // }, // onRun: function(){ // console.log("You triggered 'onRun' for 'listPage' route."); // this.next(); // }, // onRerun: function(){ // console.log("You triggered 'onRerun' for 'listPage' route."); // }, // onBeforeAction: function(){ // var currentUser = Meteor.userId(); if(currentUser){ // this.next(); // } else { // this.render("login"); // } // }, // onAfterAction: function(){ // console.log("You triggered 'onAfterAction' for 'listPage' route."); // }, // onStop: function(){ // console.log("You triggered 'onStop' for 'listPage' route."); // }, // subscriptions: function(){ // var currentList = this.params._id; // return Meteor.subscribe('todos', currentList) // } //});
{ "content_hash": "5832eebc90a3f75b0a7ff519d06c7cdb", "timestamp": "", "source": "github", "line_count": 513, "max_line_length": 123, "avg_line_length": 21.327485380116958, "alnum_prop": 0.600402157024038, "repo_name": "garduino/meteor-todos", "id": "ecbe9538e0b7663d9fe98e4862e19a05969efef5", "size": "10943", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "todos.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "32651" }, { "name": "HTML", "bytes": "2529" }, { "name": "JavaScript", "bytes": "10943" } ], "symlink_target": "" }
package packets import ( ob "github.com/bnch/lan/osubinary" ) // BanchoProtocolVersion is the version of the bancho protocol, which is sent to // the client at login. type BanchoProtocolVersion struct { Version int32 } // Packetify encodes a BanchoProtocolVersion into // a byte slice. func (p BanchoProtocolVersion) Packetify() ([]byte, error) { w := ob.NewWriter() w.Int32(p.Version) data := w.Bytes() _, err := w.End() if err != nil { return nil, err } return data, nil } // Depacketify decodes a BanchoProtocolVersion. func (p *BanchoProtocolVersion) Depacketify(b []byte) error { r := ob.NewReaderFromBytes(b) p.Version = r.Int32() _, err := r.End() return err }
{ "content_hash": "107925845d125b5bb2f195bf7df006d4", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 80, "avg_line_length": 19.194444444444443, "alnum_prop": 0.6975397973950795, "repo_name": "bnch/lan", "id": "2f3f9e9089046b094418a0c09dec884965baacc6", "size": "818", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packets/075_bancho_protocol_version.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "94998" } ], "symlink_target": "" }
/** * Render entity expungement as a modal */ define([ "underscore", "jquery", "backbone", "text!tpl/apps/expunge-modal.html" ], function(_, $, Backbone, ExpungeModalHtml) { return Backbone.View.extend({ template: _.template(ExpungeModalHtml), events: { "click .invoke-expunge": "invokeExpunge", "hide": "hide" }, render: function() { this.$el.html(this.template(this.model)); return this; }, invokeExpunge: function() { var self = this; var release = this.$("#release").is(":checked"); var url = this.model.links.expunge + "?release=" + release + "&timeout=0:"; $.ajax({ type: "POST", url: url, contentType: "application/json", success: function() { self.trigger("entity.expunged") }, error: function(data) { self.$el.fadeTo(100,1).delay(200).fadeTo(200,0.2).delay(200).fadeTo(200,1); // TODO render the error better than poor-man's flashing // (would just be connection error -- with timeout=0 we get a task even for invalid input) log("ERROR invoking effector"); log(data) } }); this.$el.fadeTo(500, 0.5); this.$el.modal("hide"); }, hide: function() { this.undelegateEvents(); } }); });
{ "content_hash": "e15c1fd4bb55e2f0443850ffb0bfcc8d", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 110, "avg_line_length": 33.84782608695652, "alnum_prop": 0.4797687861271676, "repo_name": "neykov/incubator-brooklyn", "id": "e9fe3a07930d5081e6596bad93411ecf65ab6b02", "size": "2362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "usage/jsgui/src/main/webapp/assets/js/view/expunge-invoke.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "105605" }, { "name": "Groovy", "bytes": "356057" }, { "name": "Java", "bytes": "11248156" }, { "name": "JavaScript", "bytes": "2102964" }, { "name": "PHP", "bytes": "6084" }, { "name": "Perl", "bytes": "8072" }, { "name": "PowerShell", "bytes": "4962" }, { "name": "Ruby", "bytes": "10571" }, { "name": "Shell", "bytes": "49871" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <!-- Sigit Purwadi's Official Blog versi 1.0 Created by Sigit Purwadi Powered by 4rt Cyber Tech on Sunday, 12/12/2015 1:42:54 AM in Yogyakarta, Indonesia *He! Ngapain lu liat-liat pake source viewer segala? Pasti mau nyontek ya? heuheu :D --> <head> {% include head.html %} </head> <body class="home-template" itemscope itemtype="http://schema.org/WebPage"> {% include header.html %} <div id="main" class="content" role="main" itemprop="mainContentOfPage"> <div class="container"> <div class="row"> <div class="page-body col-md-10 col-md-offset-1" itemprop="description"> {{ content }} </div> </div> </div> </div> {% include footer.html %} {% include scripts.html %} </body> </html>
{ "content_hash": "29d521d1bf29c46df8977db14cc89191", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 84, "avg_line_length": 23.727272727272727, "alnum_prop": 0.6309067688378033, "repo_name": "spurwadi2/spurwadi2.github.io", "id": "369d586f8d940e4703aef4d6d02fb509a1f6bef6", "size": "783", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_layouts/pageminimal.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "74938" }, { "name": "HTML", "bytes": "104925" }, { "name": "JavaScript", "bytes": "52215" }, { "name": "Ruby", "bytes": "5472" } ], "symlink_target": "" }
<?php namespace Grid\Share\Model\Service; use Grid\Share\Model\Service\AdapterDefault as ServiceAdapterShare; /** * Share service adapter * * @author Kristof Matos <kristof.matos@megaweb.hu> */ class Facebook extends ServiceAdapterShare { /** * Name of helper of display * * @var string $_helper */ protected $_helper = 'shareButtonFacebook'; /** * Facebook default locale * * @var string */ protected $_fbDefaultLocale = 'en_GB'; /** * Actual system locale * * @var string main system locale */ protected $_systemLocale = null; /** * Sets facebook locale by system locale * * @return string facebook locale */ public function setLocale($systemLocal) { if( $systemLocal != $this->_systemLocale ) { $this->_systemLocale = $systemLocal; $serviceLocator = $this->_view->getHelperPluginManager() ->getServiceLocator(); $config = $serviceLocator->get('Config'); $fbLocales = $config['modules']['Grid\Share']['facebook']['languages']; $localeConverted = substr($systemLocal,0,2) .'_' .strtoupper( substr($systemLocal,0,2)); if( in_array($systemLocal,$fbLocales) ) { $this->_locale = $systemLocal; } elseif( in_array( $localeConverted ,$fbLocales )) { $this->_locale = $localeConverted; } else { $this->_locale = $this->_fbDefaultLocale; } } return $this->_locale; } }
{ "content_hash": "4d07a70618a9298827481f25bb14a54c", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 83, "avg_line_length": 25.887323943661972, "alnum_prop": 0.48694232861806314, "repo_name": "webriq/share", "id": "0aae7f6e2cc8f317b57e7ec2362adf26fe2d0679", "size": "1838", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Grid/Share/Model/Service/Facebook.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "5335" }, { "name": "HTML", "bytes": "1385" }, { "name": "JavaScript", "bytes": "29909" }, { "name": "PHP", "bytes": "55333" }, { "name": "SQLPL", "bytes": "236" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nl" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About CharityCoinHelps</source> <translation>Over CharityCoinHelps</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;CharityCoinHelps&lt;/b&gt; version</source> <translation>&lt;b&gt;CharityCoinHelps&lt;/b&gt; versie</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Dit is experimentele software. Gedistribueerd onder de MIT/X11 software licentie, zie het bijgevoegde bestand COPYING of http://www.opensource.org/licenses/mit-license.php. Dit product bevat software ontwikkeld door het OpenSSL Project voor gebruik in de OpenSSL Toolkit (http://www.openssl.org/) en cryptografische software gemaakt door Eric Young (eay@cryptsoft.com) en UPnP software geschreven door Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Auteursrecht</translation> </message> <message> <location line="+0"/> <source>The CharityCoinHelps developers</source> <translation>De CharityCoinHelps-ontwikkelaars</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresboek</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dubbelklik om adres of label te wijzigen</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Maak een nieuw adres aan</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopieer het huidig geselecteerde adres naar het klembord</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nieuw Adres</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your CharityCoinHelps addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Dit zijn uw Charitycoinhelpsadressen om betalingen mee te ontvangen. U kunt er voor kiezen om een uniek adres aan te maken voor elke afzender. Op deze manier kunt u bijhouden wie al aan u betaald heeft.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopiëer Adres</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Toon &amp;QR-Code</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a CharityCoinHelps address</source> <translation>Onderteken een bericht om te bewijzen dat u een bepaald Charitycoinhelpsadres bezit</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Onderteken Bericht</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Verwijder het geselecteerde adres van de lijst</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exporteer de data in de huidige tab naar een bestand</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exporteer</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified CharityCoinHelps address</source> <translation>Controleer een bericht om te verifiëren dat het gespecificeerde Charitycoinhelpsadres het bericht heeft ondertekend.</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiëer Bericht</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Verwijder</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your CharityCoinHelps addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Dit zijn uw Charitycoinhelpsadressen om betalingen mee te verzenden. Check altijd het bedrag en het ontvangende adres voordat u uw charitycoinhelpss verzendt.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopiëer &amp;Label</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Bewerk</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Verstuur &amp;Coins</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exporteer Gegevens van het Adresboek</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(geen label)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Wachtwoorddialoogscherm</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Voer wachtwoord in</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nieuw wachtwoord</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Herhaal wachtwoord</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Vul een nieuw wachtwoord in voor uw portemonnee. &lt;br/&gt; Gebruik een wachtwoord van &lt;b&gt;10 of meer lukrake karakters&lt;/b&gt;, of &lt;b&gt; acht of meer woorden&lt;/b&gt; . </translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Versleutel portemonnee</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te openen.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Open portemonnee</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te ontsleutelen</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Ontsleutel portemonnee</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Wijzig wachtwoord</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Vul uw oude en nieuwe portemonneewachtwoord in.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bevestig versleuteling van de portemonnee</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR CHARITYCOINHELPS&lt;/b&gt;!</source> <translation>Waarschuwing: Als u uw portemonnee versleutelt en uw wachtwoord vergeet, zult u &lt;b&gt;AL UW CHARITYCOINHELPS VERLIEZEN&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Weet u zeker dat u uw portemonnee wilt versleutelen?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>BELANGRIJK: Elke eerder gemaakte backup van uw portemonneebestand dient u te vervangen door het nieuw gegenereerde, versleutelde portemonneebestand. Om veiligheidsredenen zullen eerdere backups van het niet-versleutelde portemonneebestand onbruikbaar worden zodra u uw nieuwe, versleutelde, portemonnee begint te gebruiken.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Waarschuwing: De Caps-Lock-toets staat aan!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portemonnee versleuteld</translation> </message> <message> <location line="-56"/> <source>CharityCoinHelps will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your charitycoinhelpss from being stolen by malware infecting your computer.</source> <translation>CharityCoinHelps zal nu afsluiten om het versleutelingsproces te voltooien. Onthoud dat het versleutelen van uw portemonnee u niet volledig kan beschermen: Malware kan uw computer infecteren en uw charitycoinhelpss stelen.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Portemonneeversleuteling mislukt</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Portemonneeversleuteling mislukt door een interne fout. Uw portemonnee is niet versleuteld.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>De opgegeven wachtwoorden komen niet overeen</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Portemonnee openen mislukt</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Het opgegeven wachtwoord voor de portemonnee-ontsleuteling is niet correct.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Portemonnee-ontsleuteling mislukt</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Portemonneewachtwoord is met succes gewijzigd.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Onderteken bericht...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synchroniseren met netwerk...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Overzicht</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Toon algemeen overzicht van de portemonnee</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transacties</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Blader door transactieverleden</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Bewerk de lijst van opgeslagen adressen en labels</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Toon lijst van adressen om betalingen mee te ontvangen</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Afsluiten</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Programma afsluiten</translation> </message> <message> <location line="+4"/> <source>Show information about CharityCoinHelps</source> <translation>Laat informatie zien over CharityCoinHelps</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Over &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Toon informatie over Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>O&amp;pties...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Versleutel Portemonnee...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portemonnee...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Wijzig Wachtwoord</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Blokken aan het importeren vanaf harde schijf...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Bezig met herindexeren van blokken op harde schijf...</translation> </message> <message> <location line="-347"/> <source>Send coins to a CharityCoinHelps address</source> <translation>Verstuur munten naar een Charitycoinhelpsadres</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for CharityCoinHelps</source> <translation>Wijzig instellingen van CharityCoinHelps</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>&amp;Backup portemonnee naar een andere locatie</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Wijzig het wachtwoord voor uw portemonneversleuteling</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Debugscherm</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Open debugging en diagnostische console</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifiëer bericht...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>CharityCoinHelps</source> <translation>CharityCoinHelps</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portemonnee</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Versturen</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Ontvangen</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adressen</translation> </message> <message> <location line="+22"/> <source>&amp;About CharityCoinHelps</source> <translation>&amp;Over CharityCoinHelps</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Toon / Verberg</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Toon of verberg het hoofdvenster</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Versleutel de geheime sleutels die bij uw portemonnee horen</translation> </message> <message> <location line="+7"/> <source>Sign messages with your CharityCoinHelps addresses to prove you own them</source> <translation>Onderteken berichten met uw Charitycoinhelpsadressen om te bewijzen dat u deze adressen bezit</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified CharityCoinHelps addresses</source> <translation>Verifiëer handtekeningen om zeker te zijn dat de berichten zijn ondertekend met de gespecificeerde Charitycoinhelpsadressen</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Bestand</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Instellingen</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Hulp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Tab-werkbalk</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> <message> <location line="+47"/> <source>CharityCoinHelps client</source> <translation>CharityCoinHelps client</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to CharityCoinHelps network</source> <translation><numerusform>%n actieve connectie naar Charitycoinhelpsnetwerk</numerusform><numerusform>%n actieve connecties naar Charitycoinhelpsnetwerk</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Geen bron van blokken beschikbaar...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>%1 van %2 (geschat) blokken van de transactiehistorie verwerkt.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>%1 blokken van transactiehistorie verwerkt.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n uur</numerusform><numerusform>%n uur</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dag</numerusform><numerusform>%n dagen</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n week</numerusform><numerusform>%n weken</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 achter</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Laatst ontvangen blok was %1 geleden gegenereerd.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transacties na dit moment zullen nu nog niet zichtbaar zijn.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informatie</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Deze transactie overschrijdt de groottelimiet. Om de transactie alsnog te versturen kunt u transactiekosten betalen van %1. Deze transactiekosten gaan naar de nodes die uw transactie verwerken en het helpt op deze manier bij het ondersteunen van het Charitycoinhelpsnetwerk. Wilt u de transactiekosten betalen?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Bijgewerkt</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Aan het bijwerken...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Bevestig transactiekosten</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Verzonden transactie</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Binnenkomende transactie</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Bedrag: %2 Type: %3 Adres: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI-behandeling</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid CharityCoinHelps address or malformed URI parameters.</source> <translation>URI kan niet worden geïnterpreteerd. Dit kan komen door een ongeldig Charitycoinhelpsadres of misvormde URI-parameters.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;geopend&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;gesloten&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. CharityCoinHelps can no longer continue safely and will quit.</source> <translation>Er is een fatale fout opgetreden. CharityCoinHelps kan niet meer veilig doorgaan en zal nu afgesloten worden.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Netwerkwaarschuwing</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Bewerk Adres</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Label</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Het label dat geassocieerd is met dit adres</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Het adres dat geassocieerd is met deze inschrijving in het adresboek. Dit kan alleen worden veranderd voor zend-adressen.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nieuw ontvangstadres</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nieuw adres om naar te verzenden</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Bewerk ontvangstadres</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Bewerk adres om naar te verzenden</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Het opgegeven adres &quot;%1&quot; bestaat al in uw adresboek.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid CharityCoinHelps address.</source> <translation>Het opgegeven adres &quot;%1&quot; is een ongeldig Charitycoinhelpsadres</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kon de portemonnee niet openen.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Genereren nieuwe sleutel mislukt.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>CharityCoinHelps-Qt</source> <translation>CharityCoinHelps-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versie</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>commandoregel-opties</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>gebruikersinterfaceopties</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Stel taal in, bijvoorbeeld &apos;&apos;de_DE&quot; (standaard: systeeminstellingen)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Geminimaliseerd starten</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Laat laadscherm zien bij het opstarten. (standaard: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opties</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Algemeen</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Optionele transactiekosten per kB. Transactiekosten helpen ervoor te zorgen dat uw transacties snel verwerkt worden. De meeste transacties zijn 1kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betaal &amp;transactiekosten</translation> </message> <message> <location line="+31"/> <source>Automatically start CharityCoinHelps after logging in to the system.</source> <translation>Start CharityCoinHelps automatisch na inloggen in het systeem</translation> </message> <message> <location line="+3"/> <source>&amp;Start CharityCoinHelps on system login</source> <translation>Start &amp;CharityCoinHelps bij het inloggen in het systeem</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Reset alle clientopties naar de standaardinstellingen.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Reset Opties</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Netwerk</translation> </message> <message> <location line="+6"/> <source>Automatically open the CharityCoinHelps client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Open de CharityCoinHelps-poort automatisch op de router. Dit werkt alleen als de router UPnP ondersteunt en het aanstaat.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portmapping via &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the CharityCoinHelps network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Verbind met het CharityCoinHelps-netwerk via een SOCKS-proxy (bijv. wanneer u via Tor wilt verbinden)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Verbind via een SOCKS-proxy</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-adres van de proxy (bijv. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Poort:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Poort van de proxy (bijv. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS-&amp;Versie:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS-versie van de proxy (bijv. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Scherm</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Laat alleen een systeemvak-icoon zien wanneer het venster geminimaliseerd is</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimaliseer naar het systeemvak in plaats van de taakbalk</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimaliseer het venster in de plaats van de applicatie af te sluiten als het venster gesloten wordt. Wanneer deze optie aan staan, kan de applicatie alleen worden afgesloten door Afsluiten te kiezen in het menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Minimaliseer bij sluiten van het &amp;venster</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Interface</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Taal &amp;Gebruikersinterface:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting CharityCoinHelps.</source> <translation>De taal van de gebruikersinterface kan hier ingesteld worden. Deze instelling zal pas van kracht worden nadat CharityCoinHelps herstart wordt.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Eenheid om bedrag in te tonen:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Kies de standaard onderverdelingseenheid om weer te geven in uw programma, en voor het versturen van munten</translation> </message> <message> <location line="+9"/> <source>Whether to show CharityCoinHelps addresses in the transaction list or not.</source> <translation>Of Charitycoinhelpsadressen getoond worden in de transactielijst</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Toon a&amp;dressen in de transactielijst</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>Ann&amp;uleren</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Toepassen</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>standaard</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Bevestig reset opties</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Sommige instellingen vereisen het herstarten van de client voordat ze in werking treden.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation> Wilt u doorgaan?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting CharityCoinHelps.</source> <translation>Deze instelling zal pas van kracht worden na het herstarten van CharityCoinHelps.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Het opgegeven proxyadres is ongeldig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Vorm</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the CharityCoinHelps network after a connection is established, but this process has not completed yet.</source> <translation>De weergegeven informatie kan verouderd zijn. Uw portemonnee synchroniseert automaticsh met het Charitycoinhelpsnetwerk nadat een verbinding is gelegd, maar dit proces is nog niet voltooid.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Onbevestigd:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portemonnee</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Immatuur:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Gedolven saldo dat nog niet tot wasdom is gekomen</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Recente transacties&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Uw huidige saldo</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totaal van de transacties die nog moeten worden bevestigd en nog niet zijn meegeteld in uw huidige saldo </translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>niet gesynchroniseerd</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start charitycoinhelps: click-to-pay handler</source> <translation>Kan charitycoinhelps niet starten: click-to-pay handler</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-codescherm</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Vraag betaling aan</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Label:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Bericht:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Opslaan Als...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Fout tijdens encoderen URI in QR-code</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Het opgegeven bedrag is ongeldig, controleer het s.v.p.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulterende URI te lang, probeer de tekst korter te maken voor het label/bericht.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Sla QR-code op</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-Afbeeldingen (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Clientnaam</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N.v.t.</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Clientversie</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informatie</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Gebruikt OpenSSL versie</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Opstarttijd</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Netwerk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Aantal connecties</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Op testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokketen</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Huidig aantal blokken</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Geschat totaal aantal blokken</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tijd laatste blok</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Open</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Commandoregel-opties</translation> </message> <message> <location line="+7"/> <source>Show the CharityCoinHelps-Qt help message to get a list with possible CharityCoinHelps command-line options.</source> <translation>Toon het CharitycoinhelpsQt-hulpbericht voor een lijst met mogelijke CharityCoinHelps commandoregel-opties.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Toon</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Bouwdatum</translation> </message> <message> <location line="-104"/> <source>CharityCoinHelps - Debug window</source> <translation>CharityCoinHelps-debugscherm</translation> </message> <message> <location line="+25"/> <source>CharityCoinHelps Core</source> <translation>CharityCoinHelps Kern</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debug-logbestand</translation> </message> <message> <location line="+7"/> <source>Open the CharityCoinHelps debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Open het Charitycoinhelpsdebug-logbestand van de huidige datamap. Dit kan een aantal seconden duren voor grote logbestanden.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Maak console leeg</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the CharityCoinHelps RPC console.</source> <translation>Welkom bij de CharityCoinHelps RPC-console.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Gebruik de pijltjestoetsen om door de geschiedenis te navigeren, en &lt;b&gt;Ctrl-L&lt;/b&gt; om het scherm leeg te maken.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Typ &lt;b&gt;help&lt;/b&gt; voor een overzicht van de beschikbare commando&apos;s.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Verstuur munten</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Verstuur aan verschillende ontvangers ineens</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Voeg &amp;Ontvanger Toe</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Verwijder alle transactievelden</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Verwijder &amp;Alles</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Bevestig de verstuuractie</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Verstuur</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; aan %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bevestig versturen munten</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Weet u zeker dat u %1 wil versturen?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> en </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Het ontvangstadres is niet geldig, controleer uw invoer.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Het ingevoerde bedrag moet groter zijn dan 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Bedrag is hoger dan uw huidige saldo</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totaal overschrijdt uw huidige saldo wanneer de %1 transactiekosten worden meegerekend</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Dubbel adres gevonden, u kunt slechts eenmaal naar een bepaald adres verzenden per verstuurtransactie</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Fout: Aanmaak transactie mislukt!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fout: De transactie was afgewezen. Dit kan gebeuren als u eerder uitgegeven munten opnieuw wilt versturen, zoals wanneer u een kopie van uw portemonneebestand (wallet.dat) heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in de huidige portemonnee deze nog niet als zodanig zijn gemarkeerd.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Vorm</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Bedra&amp;g:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betaal &amp;Aan:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres waaraan u wilt betalen (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Vul een label in voor dit adres om het toe te voegen aan uw adresboek</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Kies adres uit adresboek</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Verwijder deze ontvanger</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a CharityCoinHelps address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Vul een Charitycoinhelpsadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Handtekeningen - Onderteken een bericht / Verifiëer een handtekening</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>O&amp;nderteken Bericht</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>U kunt berichten ondertekenen met een van uw adressen om te bewijzen dat u dit adres bezit. Pas op dat u geen onduidelijke dingen ondertekent, want phishingaanvallen zouden u kunnen misleiden om zo uw identiteit te stelen. Onderteken alleen berichten waarmee u het volledig eens bent.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres om het bericht mee te ondertekenen (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Kies een adres uit het adresboek</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Typ hier het bericht dat u wilt ondertekenen</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Handtekening</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopieer de huidige handtekening naar het systeemklembord</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this CharityCoinHelps address</source> <translation>Onderteken een bericht om te bewijzen dat u een bepaald Charitycoinhelpsadres bezit</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Onderteken &amp;Bericht</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Verwijder alles in de invulvelden</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Verwijder &amp;Alles</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiëer Bericht</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Voer het ondertekenende adres, bericht en handtekening hieronder in (let erop dat u nieuwe regels, spaties en tabs juist overneemt) om de handtekening te verifiëren. Let erop dat u niet meer uit het bericht interpreteert dan er daadwerkelijk staat, om te voorkomen dat u wordt misleid in een man-in-the-middle-aanval.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres waarmee bet bericht was ondertekend (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified CharityCoinHelps address</source> <translation>Controleer een bericht om te verifiëren dat het gespecificeerde Charitycoinhelpsadres het bericht heeft ondertekend.</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verifiëer &amp;Bericht</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Verwijder alles in de invulvelden</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a CharityCoinHelps address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Vul een Charitycoinhelpsadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klik &quot;Onderteken Bericht&quot; om de handtekening te genereren</translation> </message> <message> <location line="+3"/> <source>Enter CharityCoinHelps signature</source> <translation>Voer CharityCoinHelps-handtekening in</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Het opgegeven adres is ongeldig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Controleer s.v.p. het adres en probeer het opnieuw.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Het opgegeven adres verwijst niet naar een sleutel.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Portemonnee-ontsleuteling is geannuleerd</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Geheime sleutel voor het ingevoerde adres is niet beschikbaar.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Ondertekenen van het bericht is mislukt.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Bericht ondertekend.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>De handtekening kon niet worden gedecodeerd.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Controleer s.v.p. de handtekening en probeer het opnieuw.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>De handtekening hoort niet bij het bericht.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Berichtverificatie mislukt.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Bericht correct geverifiëerd.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The CharityCoinHelps developers</source> <translation>De CharityCoinHelps-ontwikkelaars</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Openen totdat %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/onbevestigd</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bevestigingen</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, uitgezonden naar %n node</numerusform><numerusform>, uitgezonden naar %n nodes</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Bron</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gegenereerd</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Van</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Aan</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>eigen adres</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>label</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>komt tot wasdom na %n nieuw blok</numerusform><numerusform>komt tot wasdom na %n nieuwe blokken</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>niet geaccepteerd</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transactiekosten</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto bedrag</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Bericht</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Opmerking</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transactie-ID:</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Gegeneerde munten moeten 120 blokken wachten voordat ze tot wasdom komen en kunnen worden uitgegeven. Uw net gegenereerde blok is uitgezonden aan het netwerk om te worden toegevoegd aan de blokketen. Als het niet wordt geaccepteerd in de keten, zal het blok als &quot;niet geaccepteerd&quot; worden aangemerkt en kan het niet worden uitgegeven. Dit kan soms gebeuren als een andere node net iets sneller een blok heeft gegenereerd; een paar seconden voor het uwe.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Debug-informatie</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transactie</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Inputs</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>waar</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>onwaar</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, is nog niet met succes uitgezonden</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>onbekend</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transactiedetails</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Dit venster laat een uitgebreide beschrijving van de transactie zien</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Open tot %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Niet verbonden (%1 bevestigingen)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Onbevestigd (%1 van %2 bevestigd)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Bevestigd (%1 bevestigingen)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blok</numerusform><numerusform>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blokken</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Dit blok is niet ontvangen bij andere nodes en zal waarschijnlijk niet worden geaccepteerd!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gegenereerd maar niet geaccepteerd</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ontvangen van</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betaling aan uzelf</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Gedolven</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(nvt)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transactiestatus. Houd de muiscursor boven dit veld om het aantal bevestigingen te laten zien.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum en tijd waarop deze transactie is ontvangen.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Type transactie.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Ontvangend adres van transactie.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Bedrag verwijderd van of toegevoegd aan saldo</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alles</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Vandaag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Deze week</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Deze maand</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Vorige maand</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Dit jaar</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Bereik...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Aan uzelf</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Gedolven</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Anders</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Vul adres of label in om te zoeken</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min. bedrag</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopieer adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopieer label</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopieer transactie-ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Bewerk label</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Toon transactiedetails</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exporteer transactiegegevens</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bevestigd</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Bereik:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>naar</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Verstuur munten</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exporteer</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exporteer de data in de huidige tab naar een bestand</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Portomonnee backuppen</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Portemonnee-data (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Backup Mislukt</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Er is een fout opgetreden bij het wegschrijven van de portemonnee-data naar de nieuwe locatie.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Backup Succesvol</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>De portemonneedata is succesvol opgeslagen op de nieuwe locatie.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>CharityCoinHelps version</source> <translation>Charitycoinhelpsversie</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or charitycoinhelpsd</source> <translation>Stuur commando naar -server of charitycoinhelpsd</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lijst van commando&apos;s</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Toon hulp voor een commando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opties:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: charitycoinhelps.conf)</source> <translation>Specificeer configuratiebestand (standaard: charitycoinhelps.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: charitycoinhelpsd.pid)</source> <translation>Specificeer pid-bestand (standaard: charitycoinhelpsd.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Stel datamap in</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Stel databankcachegrootte in in megabytes (standaard: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9793 or testnet: 19793)</source> <translation>Luister voor verbindingen op &lt;poort&gt; (standaard: 9793 of testnet: 19793)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Onderhoud maximaal &lt;n&gt; verbindingen naar peers (standaard: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Verbind naar een node om adressen van anderen op te halen, en verbreek vervolgens de verbinding</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specificeer uw eigen publieke adres</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Drempel om verbinding te verbreken naar zich misdragende peers (standaard: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Aantal seconden dat zich misdragende peers niet opnieuw mogen verbinden (standaard: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9792 or testnet: 19792)</source> <translation>Wacht op JSON-RPC-connecties op poort &lt;port&gt; (standaard: 9792 of testnet: 19792)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aanvaard commandoregel- en JSON-RPC-commando&apos;s</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Draai in de achtergrond als daemon en aanvaard commando&apos;s</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Gebruik het testnetwerk</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepteer verbindingen van buitenaf (standaard: 1 als geen -proxy of -connect is opgegeven)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=charitycoinhelpsrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;CharityCoinHelps Alert&quot; admin@foo.com </source> <translation>%s, u moet een RPC-wachtwoord instellen in het configuratiebestand: %s U wordt aangeraden het volgende willekeurige wachtwoord te gebruiken: rpcuser=charitycoinhelpsrpc rpcpassword=%s (u hoeft dit wachtwoord niet te onthouden) De gebruikersnaam en wachtwoord mogen niet hetzelfde zijn. Als het bestand niet bestaat, make hem dan aan met leesrechten voor enkel de eigenaar. Het is ook aan te bevelen &quot;alertnotify&quot; in te stellen zodat u op de hoogte gesteld wordt van problemen; for example: alertnotify=echo %%s | mail -s &quot;CharityCoinHelps Alert&quot; admin@foo.com</translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv6, terugval naar IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind aan opgegeven adres en luister er altijd op. Gebruik [host]:port notatie voor IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. CharityCoinHelps is probably already running.</source> <translation>Kan geen lock op de datamap %s verkrijgen. CharityCoinHelps draait vermoedelijk reeds.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fout: De transactie was afgewezen! Dit kan gebeuren als sommige munten in uw portemonnee al eerder uitgegeven zijn, zoals wanneer u een kopie van uw wallet.dat heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in deze portemonnee die munten nog niet als zodanig zijn gemarkeerd.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Fout: Deze transactie vereist transactiekosten van tenminste %s, vanwege zijn grootte, complexiteit, of het gebruik van onlangs ontvangen munten!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Voer opdracht uit zodra een relevante melding ontvangen is (%s wordt in cmd vervangen door het bericht)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Voer opdracht uit zodra een portemonneetransactie verandert (%s in cmd wordt vervangen door TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Stel maximumgrootte in in bytes voor hoge-prioriteits-/lage-transactiekosten-transacties (standaard: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Dit is een pre-release testversie - gebruik op eigen risico! Gebruik deze niet voor het delven van munten of handelsdoeleinden</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Waarschuwing: -paytxfee is zeer hoog ingesteld. Dit zijn de transactiekosten die u betaalt bij het versturen van een transactie.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Waarschuwing: Weergegeven transacties zijn mogelijk niet correct! Mogelijk dient u te upgraden, of andere nodes dienen te upgraden.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong CharityCoinHelps will not work properly.</source> <translation>Waarschuwing: Controleer dat de datum en tijd op uw computer correct zijn ingesteld. Als uw klok fout staat zal CharityCoinHelps niet correct werken.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Waarschuwing: Fout bij het lezen van wallet.dat! Alle sleutels zijn in goede orde uitgelezen, maar transactiedata of adresboeklemma&apos;s zouden kunnen ontbreken of fouten bevatten.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Waarschuwing: wallet.dat is corrupt, data is veiliggesteld! Originele wallet.dat is opgeslagen als wallet.{tijdstip}.bak in %s; als uw balans of transacties incorrect zijn dient u een backup terug te zetten.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Poog de geheime sleutels uit een corrupt wallet.dat bestand terug te halen</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Blokcreatie-opties:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Verbind alleen naar de gespecificeerde node(s)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Corrupte blokkendatabase gedetecteerd</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Ontdek eigen IP-adres (standaard: 1 als er wordt geluisterd en geen -externalip is opgegeven)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Wilt u de blokkendatabase nu herbouwen?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Fout bij intialisatie blokkendatabase</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Probleem met initializeren van de database-omgeving %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Fout bij het laden van blokkendatabase</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Fout bij openen blokkendatabase</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Fout: Weinig vrije diskruimte!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Fout: Portemonnee vergrendeld, aanmaak transactie niet mogelijk!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Fout: Systeemfout:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Mislukt om op welke poort dan ook te luisteren. Gebruik -listen=0 as u dit wilt.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Lezen van blokinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Lezen van blok mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Synchroniseren van blokindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Schrijven van blokindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Schrijven van blokinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Schrijven van blok mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Schrijven van bestandsinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Schrijven naar coindatabase mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Schrijven van transactieindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Schrijven van undo-data mislukt</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Vind andere nodes d.m.v. DNS-naslag (standaard: 1 tenzij -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Genereer munten (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Aantal te checken blokken bij het opstarten (standaard: 288, 0 = allemaal)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Hoe grondig de blokverificatie is (0-4, standaard: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Niet genoeg file descriptors beschikbaar.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Blokketen opnieuw opbouwen van huidige blk000??.dat-bestanden</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Stel het aantal threads in om RPC-aanvragen mee te bedienen (standaard: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Blokken aan het controleren...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Portomonnee aan het controleren...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importeert blokken van extern blk000??.dat bestand</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Stel het aantal threads voor scriptverificatie in (max 16, 0 = auto, &lt;0 = laat zoveel cores vrij, standaard: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informatie</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Ongeldig -tor adres: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -minrelaytxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -mintxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Onderhoud een volledige transactieindex (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximum per-connectie ontvangstbuffer, &lt;n&gt;*1000 bytes (standaard: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximum per-connectie zendbuffer, &lt;n&gt;*1000 bytes (standaard: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Accepteer alleen blokketen die overeenkomt met de ingebouwde checkpoints (standaard: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Verbind alleen naar nodes in netwerk &lt;net&gt; (IPv4, IPv6 of Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Output extra debugginginformatie. Impliceert alle andere -debug* opties</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Output extra netwerk-debugginginformatie</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Voorzie de debuggingsuitvoer van een tijdsaanduiding</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the CharityCoinHelps Wiki for SSL setup instructions)</source> <translation>SSL-opties: (zie de CharityCoinHelps wiki voor SSL-instructies)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecteer de versie van de SOCKS-proxy om te gebruiken (4 of 5, standaard is 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Stuur trace/debug-info naar de console in plaats van het debug.log bestand</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Stuur trace/debug-info naar debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Stel maximum blokgrootte in in bytes (standaard: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Stel minimum blokgrootte in in bytes (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Verklein debug.log-bestand bij het opstarten van de client (standaard: 1 als geen -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Ondertekenen van transactie mislukt</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specificeer de time-outtijd in milliseconden (standaard: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Systeemfout:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Transactiebedrag te klein</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Transactiebedragen moeten positief zijn</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transactie te groot</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 1 als er wordt geluisterd)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Gebruik proxy om &apos;tor hidden services&apos; te bereiken (standaard: hetzelfde als -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Gebruikersnaam voor JSON-RPC-verbindingen</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Waarschuwing: Deze versie is verouderd, een upgrade is vereist!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>U moet de databases herbouwen met behulp van -reindex om -txindex te kunnen veranderen</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupt, veiligstellen mislukt</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Wachtwoord voor JSON-RPC-verbindingen</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Sta JSON-RPC verbindingen van opgegeven IP-adres toe</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Verstuur commando&apos;s naar proces dat op &lt;ip&gt; draait (standaard: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Voer commando uit zodra het beste blok verandert (%s in cmd wordt vervangen door blockhash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Vernieuw portemonnee naar nieuwste versie</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Stel sleutelpoelgrootte in op &lt;n&gt; (standaard: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Doorzoek de blokketen op ontbrekende portemonnee-transacties</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Gebruik OpenSSL (https) voor JSON-RPC-verbindingen</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Certificaat-bestand voor server (standaard: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Geheime sleutel voor server (standaard: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Aanvaardbare ciphers (standaard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Dit helpbericht</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Niet in staat om aan %s te binden op deze computer (bind gaf error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Verbind via een socks-proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Sta DNS-naslag toe voor -addnode, -seednode en -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Adressen aan het laden...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fout bij laden wallet.dat: Portemonnee corrupt</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of CharityCoinHelps</source> <translation>Fout bij laden wallet.dat: Portemonnee vereist een nieuwere versie van CharityCoinHelps</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart CharityCoinHelps to complete</source> <translation>Portemonnee moest herschreven worden: Herstart CharityCoinHelps om te voltooien</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Fout bij laden wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ongeldig -proxy adres: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Onbekend netwerk gespecificeerd in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Onbekende -socks proxyversie aangegeven: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kan -bind adres niet herleiden: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kan -externlip adres niet herleiden: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -paytxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Ongeldig bedrag</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Ontoereikend saldo</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Blokindex aan het laden...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Voeg een node om naar te verbinden toe en probeer de verbinding open te houden</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. CharityCoinHelps is probably already running.</source> <translation>Niet in staat om aan %s te binden op deze computer. CharityCoinHelps draait vermoedelijk reeds.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Kosten per KB om aan transacties toe te voegen die u verstuurt</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Portemonnee aan het laden...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Kan portemonnee niet downgraden</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Kan standaardadres niet schrijven</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Blokketen aan het doorzoeken...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Klaar met laden</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Om de %s optie te gebruiken</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>U dient rpcpassword=&lt;wachtwoord&gt; in te stellen in het configuratiebestand: %s Als het bestand niet bestaat, maak het dan aan, met een alleen-lezen-permissie.</translation> </message> </context> </TS>
{ "content_hash": "a26e8f386199f3f41db80a4ac9ccb84c", "timestamp": "", "source": "github", "line_count": 2938, "max_line_length": 498, "avg_line_length": 40.62695711368278, "alnum_prop": 0.6401032154286959, "repo_name": "CharityCoinHelps/charitycoinhelps-master-0.8", "id": "503d7346899e00176fe381c0c94c89033783d36c", "size": "119375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_nl.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "103297" }, { "name": "C++", "bytes": "2523098" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14728" }, { "name": "Objective-C", "bytes": "5864" }, { "name": "Python", "bytes": "37296" }, { "name": "Shell", "bytes": "2527" }, { "name": "TypeScript", "bytes": "5270041" } ], "symlink_target": "" }
<?php namespace Rs\Issues\Exception; /** * NotFoundException. * * @author Robert Schönthal <robert.schoenthal@gmail.com> */ class NotFoundException extends \InvalidArgumentException { }
{ "content_hash": "dc4d326a3ffc8611f49dd69d6d47512e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 57, "avg_line_length": 16, "alnum_prop": 0.75, "repo_name": "digitalkaoz/issues", "id": "e230a351a2ec3df77498d55f7732035d8b08c193", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Exception/NotFoundException.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "75924" } ], "symlink_target": "" }
package com.autotest.extension; import com.csvreader.CsvWriter; import com.autotest.base.AutoTestBase; import com.autotest.utils.ProcessObject; import com.autotest.utils.StringUtils; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterResolutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by huairen on 2017/7/14. */ public class DataDeal { private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create("AutoTestExtension", "DataDeal"); protected static final Logger logger = LoggerFactory.getLogger(DataDeal.class); public static List<Object> getParams(ExtensionContext context, String file) { if (null == file || file.isEmpty()) { throw new IllegalArgumentException("csv文件路径file的值不能为空"); } if (file.startsWith("/")) { file = file.substring(1); } Method m = context.getTestMethod().get(); List<Parame> args = getVariables(context); URL url = Thread.currentThread().getContextClassLoader() .getResource("autotest/" + file); if (null == url) { String filep = context.getTestClass().get().getClassLoader().getResource(".").getFile(); String fileDir = filep.replace("target/test-classes/", "src/test/resources/autotest/") + file; createCsvFile(args, fileDir); throw new IllegalArgumentException("找不到csv文件,创建文件成功:" + fileDir); } String filePath = Thread.currentThread().getContextClassLoader() .getResource("autotest/" + file).getPath(); File fl = new File(filePath); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(fl)); List<String> result = new ArrayList<>(); String[] pars; int lineNo = 0; String[] header = null; String line = null; List<Object> obs = new ArrayList<>(); while ((line = reader.readLine()) != null) { ++lineNo; if (lineNo == 1) { header = splitContent(line); } else { if (line.contains("~")) { line = line.replace("~", ""); } List<String> list = new ArrayList<>(); HashMap<String, Object> map = parseLine(header, line, lineNo); obs.add(map); for (int n = 0; n < args.size(); n++) { String name = args.get(n).getName(); if (null != map.get(name)) { String val = map.get(name).toString().trim(); list.add(val); } else { String type = args.get(n).getType().getSimpleName(); if ("String".equals(type)) { list.add(""); continue; } else if ("int".equals(type) || "Integer".equals(type) || "long".equals(type) || "Long".equals(type) || "short".equals(type) || "Short".equals(type) || "byte".equals(type) || "Byte".equals(type) || "float".equals(type) || "Float".equals(type) || "double".equals(type) || "Double".equals(type) || "char".equals(type) || "Character".equals(type) ) { list.add("0"); continue; } else if ("boolean".equals(type)) { list.add("false"); continue; } else { list.add(""); } } } StringBuffer str = new StringBuffer(); Iterator iterator = list.iterator(); while (iterator.hasNext()) { str.append(iterator.next() + ","); } if (0 != str.length()) { result.add(str.deleteCharAt(str.length() - 1).toString()); } } } int times = result.size(); String methodName = context.getTestMethod().get().getName(); context.getStore(NAMESPACE).put("methodName", methodName); context.getStore(NAMESPACE).put("times", times); // return result.toArray(new String[result.size()]); return obs; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private static Pattern pattern = Pattern.compile("\\{[^}]*\\}"); public static String[] splitContent(String input) { //过滤所有的json字符串 Matcher match = pattern.matcher(input); while (match.find()) { if (!StringUtils.isBlank(match.group())) { throw new ParameterResolutionException("参数转换出错: " + match.group()); } } ArrayList<String> result = new ArrayList(); char character = 0; StringBuilder value = new StringBuilder(); for (int i = 0; i < input.length(); ++i) { char previousCharacter = character; character = input.charAt(i); if (character != 44 && character != 124) { value.append(character); } else if (previousCharacter == 92) { value.setCharAt(value.length() - 1, character); } else { result.add(value.toString().trim()); value = new StringBuilder(); } } result.add(value.toString().trim()); return (String[]) result.toArray(new String[0]); } public static String replace(String text, String repl, String with) { return replace(text, repl, with, -1); } public static String replace(String text, String repl, String with, int max) { if ((text == null) || (repl == null) || (with == null) || (repl.length() == 0) || (max == 0)) { return text; } StringBuffer buf = new StringBuffer(text.length()); int start = 0; int end = 0; while ((end = text.indexOf(repl, start)) != -1) { buf.append(text.substring(start, end)).append(with); start = end + repl.length(); if (--max == 0) { break; } } buf.append(text.substring(start)); return buf.toString(); } private static HashMap<String, Object> parseLine(String[] header, String line, int lineNo) { HashMap<String, Object> parMap = new HashMap<>(); String[] params = splitContent(line); if (params.length != header.length) { throw new RuntimeException("数据文件:" + " 第" + lineNo + "行格式错误"); } else { for (int i = 0; i < header.length; ++i) { parMap.put(header[i], StringUtils.isBlank(params[i]) ? null : params[i]); } } return parMap; } /** * 获取方法的参数 * * @param context * @return */ public static List<Parame> getVariables(ExtensionContext context) { List<Parame> list = new ArrayList<Parame>(); Parameter[] parameters = context.getTestMethod().get().getParameters(); LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); String[] params = u.getParameterNames(context.getTestMethod().get()); for (int i = 0; i < parameters.length; i++) { Parame p = new Parame(); p.setName(params[i].trim()); p.setType(parameters[i].getType()); list.add(p); } return list; } public static void createCsvFile(List<Parame> list, String filePath) { File excelfile = new File(filePath); if (!excelfile.exists()) { try { String dir = filePath.substring(0, filePath.lastIndexOf("/")); File dirFile = new File(dir); if (!dirFile.exists()) { dirFile.mkdir(); } List<String> strs = new ArrayList<>(); CsvWriter cwriter = new CsvWriter(filePath); for (Iterator<Parame> it = list.iterator(); it.hasNext(); ) { Parame p = (Parame) it.next(); Class clz = p.getType(); if (DataDeal.isJavaClass(clz) || clz.isEnum()) { if (!strs.contains(p.getName())) { strs.add(p.getName()); } } else { strs = getFieldFromClass(clz, strs, p.getName()); } } for (String s : strs) { cwriter.write(s, true); } cwriter.endRecord(); for (String s : strs) { String value = ""; if ("testId".equals(s)) { value = "1001"; } else { value = ""; } cwriter.write(value, true); } cwriter.flush();// 刷新数据 } catch (IOException e) { e.printStackTrace(); } } else { logger.info("csv文件已存在!"); } } public static Object mapToObject(Map<String, String> map, Class<?> clz, String name) throws Exception { if (map == null) { return null; } Object obj = clz.newInstance(); List<Field> fields = new ArrayList<>(); fields = getClassAllFields(clz, fields); for (Field field : fields) { int mod = field.getModifiers(); if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { continue; } field.setAccessible(true); char ch = name.charAt(name.length() - 1); String str1 = field.getName() + ch + "_" + name.substring(0, name.length() - 1); String str2 = field.getName() + ch; String str3 = field.getName() + "_" + name; String str = null; if (Character.isDigit(ch)) { if (map.containsKey(str1)) { str = map.get(str1); } else if (map.containsKey(str2)) { str = map.get(str2); } field.set(obj, ProcessObject.processing(field.getType(), str)); continue; } else if (map.containsKey(str3)) { str = map.get(str3); field.set(obj, ProcessObject.processing(field.getType(), str)); continue; } field.set(obj, ProcessObject.processing(field.getType(), map.get(field.getName()))); } return obj; } public static List<String> getFieldFromClass(Class clz, List<String> strs, String name) { List<Field> fields = new ArrayList<>(); fields = getClassAllFields(clz, fields); for (Field field : fields) { if ("serialVersionUID".equals(field.getName())) { continue; } field.setAccessible(true); char ch = name.charAt(name.length() - 1); String str1 = field.getName() + ch + "_" + name.substring(0, name.length() - 1); String str2 = field.getName() + ch; String str3 = field.getName() + "_" + name; if (!strs.contains(field.getName())) { strs.add(field.getName()); } else if (Character.isDigit(ch)) { if (!strs.contains(str2)) { strs.add(str2); } else if (!strs.contains(str1)) { strs.add(str1); } } else if (!strs.contains(str3)) { strs.add(str3); } } return strs; } /** * 循环向上转型, 获取对象的 DeclaredField * * @param * @param * @return */ public static List<Field> getClassAllFields(Class<?> clazz, List<Field> allGenericFields) { // 如果clazz为空则直接返回 if (clazz == null) { return allGenericFields; } Object parent = clazz.getGenericSuperclass(); // 如果有父类并且父类不是Object 则递归调用 if (parent != null && !((Class<?>) parent).getName().equals("Object")) { getClassAllFields((Class<?>) parent, allGenericFields); } Field[] fields = clazz.getDeclaredFields(); if (fields != null) {// 如果clazz存在声明的属性 for (int i = 0; i < fields.length; i++) allGenericFields.add(fields[i]); } return allGenericFields; } public static boolean isJavaClass(Class<?> clz) { return clz != null && clz.getClassLoader() == null; } public static String toLowerCaseFirstOne(String s) { if (Character.isLowerCase(s.charAt(0))) { return s; } else { return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString(); } } }
{ "content_hash": "10f7f4bf389cb98d76fe6629fdadb4aa", "timestamp": "", "source": "github", "line_count": 379, "max_line_length": 115, "avg_line_length": 30.12928759894459, "alnum_prop": 0.6074087047902619, "repo_name": "ychaoyang/autotest", "id": "713afb7873a49a3e545631f194c7b61c84c147e4", "size": "11631", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/autotest/extension/DataDeal.java", "mode": "33188", "license": "mit", "language": [ { "name": "FreeMarker", "bytes": "15615" }, { "name": "Java", "bytes": "137542" } ], "symlink_target": "" }
class PythonController; class Scene : public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT PythonController *_pyController; int _prevMouseX; int _prevMouseY; public: Scene(QWidget *parent = 0); void initializeGL(); void resizeGL(int w, int h); void paintGL(); void setPyController(PythonController *pyController) { _pyController = pyController; } void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); void contextMenuEvent(QContextMenuEvent*); }; #endif // SCENE_H
{ "content_hash": "ab6323a882713b05a0ac402fcbb4d68a", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 90, "avg_line_length": 22.40740740740741, "alnum_prop": 0.715702479338843, "repo_name": "stes/it4kids", "id": "e7a3a265353cedefbca0699a943766fbe9bd1c81", "size": "715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scene.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "133759" }, { "name": "CMake", "bytes": "3822" }, { "name": "Python", "bytes": "21407" }, { "name": "QMake", "bytes": "5556" } ], "symlink_target": "" }
module Api module V2 class ApiApplicationController < ActionController::Metal abstract! include AbstractController::Callbacks include ActionController::RackDelegation include ActionController::StrongParameters include ActionController::Helpers include ActionController::RequestForgeryProtection include ActionController::MimeResponds include ActionController::ParamsWrapper include ActionController::Instrumentation protect_from_forgery with: :null_session before_filter :restrict_access before_filter :check_version_code private def restrict_access api_key = ApiKey.find_by_access_token(params[:access_token]) render status: :unauthorized unless api_key end def check_version_code if params[:version_code] render status: :upgrade_required unless params[:version_code].to_i >= Settings.minimum_android_version_code end end def render(options={}) self.status = options[:status] || 200 self.content_type = 'application/json' body = Oj.dump(options[:json], mode: :compat) self.headers['Content-Length'] = body.bytesize.to_s self.response_body = body end ActiveSupport.run_load_hooks(:action_controller, self) end end end
{ "content_hash": "90d449f04ab7c04c74f2c20ec7f147b4", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 117, "avg_line_length": 31.833333333333332, "alnum_prop": 0.6851159311892296, "repo_name": "DukeMobileTech/participant_tracker", "id": "f51d1a481bbe4dd592b9a10d565e07be5f257799", "size": "1337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/api/v2/api_application_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4308" }, { "name": "CoffeeScript", "bytes": "29" }, { "name": "HTML", "bytes": "38184" }, { "name": "JavaScript", "bytes": "701" }, { "name": "Ruby", "bytes": "127630" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('librarian', '0102_relink_apps'), ] operations = [ migrations.AddField( model_name='dataset', name='last_time_checked', field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date-time of last (external) dataset existence check.'), ), ]
{ "content_hash": "3ecd4e15c17349abb3f8b17c01930485", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 141, "avg_line_length": 26.473684210526315, "alnum_prop": 0.6461232604373758, "repo_name": "cfe-lab/Kive", "id": "7b6c0b2ec87299c50fbd291de6e186773a7ed162", "size": "575", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kive/librarian/migrations/0103_dataset_last_time_checked.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "26511" }, { "name": "HTML", "bytes": "81400" }, { "name": "JavaScript", "bytes": "121951" }, { "name": "Jinja", "bytes": "15965" }, { "name": "Makefile", "bytes": "1957" }, { "name": "Python", "bytes": "1453355" }, { "name": "Sass", "bytes": "15929" }, { "name": "Shell", "bytes": "37562" }, { "name": "Singularity", "bytes": "2941" }, { "name": "TypeScript", "bytes": "356365" } ], "symlink_target": "" }
<HTML><HEAD> <TITLE>Review for Bowfinger (1999)</TITLE> <LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0131325">Bowfinger (1999)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Scott+Renshaw">Scott Renshaw</A></H3><HR WIDTH="40%" SIZE="4"> <PRE>BOWFINGER (Universal) Starring: Steve Martin, Eddie Murphy, Heather Graham, Jamie Kennedy, Christine Baranski, Terrence Stamp. Screenplay: Steve Martin. Producer: Brian Grazer. Director: Frank Oz. MPAA Rating: PG-13 (profanity, adult themes, adult humor) Running Time: 93 minutes. Reviewed by Scott Renshaw.</PRE> <P> Movie people love making movies about movie people -- they validate film-making as the most fascinating of all pursuits, even as they allow Tinseltown to tweak its own inflated image. It's a wonderful mystery of the film industry that so much self-absorption and self-loathing can co-exist without some sort of matter/anti-matter explosion. Too often, though, the tweak doesn't take. Steven Seagal playing himself in MY GIANT was unconvincing as a pompous, difficult star playing a pompous, difficult star; BURN HOLLYWOOD BURN was as brainless and misguided as the films it intended to satirize. For every THE PLAYER, there are half a dozen attempts at insider humor too self-congratulatory to tap into what's truly goofy about Hollywood.</P> <P> Steve Martin is one of the guys who gets it, and in BOWFINGER he finds an unlikely partner in Eddie Murphy. Martin plays Bobby Bowfinger, a never-was producer convinced that he's finally found a project that will launch him into the big time. The science-fiction/action project needs only one thing to guarantee studio support: the participation of Kit Ramsey (Murphy), action star extraordinaire. Ramsey has no interest in the project, but Bowfinger has a creative solution. He plans to send his cast and crew wherever Ramsey happens to be, throwing him into the film without his knowledge. Little does Bowfinger know that the strange things happening around Kit are sending the already-edgy celebrity into a full-fledged paranoia.</P> <P> Martin, who also wrote the script, has previously demonstrated his fondness for skewering Los Angeles (L.A. STORY) and classic cinema (DEAD MEN DON'T WEAR PLAID); he even played a soulless studio suit himself in GRAND CANYON. The key is that he knows how to do it with affection, finding the absurdity in film culture and conventions while still recognizing their magical appeal. In a sense, BOWFINGER is a broad, contemporary re-working of ED WOOD, the story of a guy so determined to make his mark that he'll go to bizarre lengths to do it. Martin the actor lets go of his recent flustered Everyman persona to find a guy willing to look ridiculous to be a player. Martin the writer, meanwhile, takes broad aim at every possible industry target -- producers with short attention spans, action films, the casting couch, Scientology (thinly disguised as an organization called Mindhead), even former girlfriend Anne Heche. While some of the barbs are caustic, they all come back to a group of people trying to make magic ... even if the magic is an alien adventure called "Chubby Rain."</P> <P> The scattershot approach to Hollywood satire should have fallen flat, and on occasion it does feel somewhat forced. Director Frank Oz certainly deserves some credit for his deft touch, but the real anchor of BOWFINGER is Eddie Murphy. Unlike Seagal, Murphy appears genuinely willing to poke fun at his history as holy terror. His Kit Ramsey is a borderline psychotic, surrounded by yes-men who validate his demented conspiracy theories and a Mindhead guru (Terrence Stamp) who gets rich off of them. It's a wild, wired performance, complemented by his second role as Jiff, the geeky Kit Ramsey look-alike Bowfinger hires as a stand-in. Jiff not only lets Murphy subtly satirize his fondness for playing multiple roles; he provides a sympathetic face for an innocent's sense of wonder at the world of the movies. Murphy should always be this loose and entertaining.</P> <P> BOWFINGER isn't a perfect comedy, at times pushing its thin premise farther than it can sustain. Heather Graham's secretly Machiavellian ingenue grows a bit tiresome, and the Mindhead gags often feel timid and blunted. When the set pieces work, however -- Jiff's terrified journey across a freeway, or an attempt to spook Kit in a parking garage, or gathering a "crew" at the Mexican border -- they're wonderfully funny stuff. It's also a movie about movies that doesn't get caught up in its own hipness. When Steve Martin wants you to laugh at something about Hollywood, you know it's out of authentic whimsy, not a movie star's hypocritical attempt to cozy up to the laypeople. As a result, BOWFINGER feels relaxed and honest, a satire with enough wisdom to recognize there's still something delightful about being a film-maker.</P> <PRE> On the Renshaw scale of 0 to 10 Hollywood chuckles: 7.</PRE> <PRE><HR> Visit Scott Renshaw's Screening Room <A HREF="http://www.inconnect.com/~renshaw/">http://www.inconnect.com/~renshaw/</A> *** Subscribe to receive new reviews directly by email! See the Screening Room for details, or reply to this message with subject "Subscribe".<HR></PRE> <HR><P CLASS=flush><SMALL>The review above was posted to the <A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR> The Internet Movie Database accepts no responsibility for the contents of the review and has no editorial control. Unless stated otherwise, the copyright belongs to the author.<BR> Please direct comments/criticisms of the review to relevant newsgroups.<BR> Broken URLs inthe reviews are the responsibility of the author.<BR> The formatting of the review is likely to differ from the original due to ASCII to HTML conversion. </SMALL></P> <P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P> </P></BODY></HTML>
{ "content_hash": "d025dac2a22b87536e9ca0aa8587df31", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 197, "avg_line_length": 63.85, "alnum_prop": 0.7505090054815975, "repo_name": "xianjunzhengbackup/code", "id": "3e29d0a4d9a82103dafaaf0a425022c20b10cc3f", "size": "6385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data science/machine_learning_for_the_web/chapter_4/movie/19921.html", "mode": "33261", "license": "mit", "language": [ { "name": "BitBake", "bytes": "113" }, { "name": "BlitzBasic", "bytes": "256" }, { "name": "CSS", "bytes": "49827" }, { "name": "HTML", "bytes": "157006325" }, { "name": "JavaScript", "bytes": "14029" }, { "name": "Jupyter Notebook", "bytes": "4875399" }, { "name": "Mako", "bytes": "2060" }, { "name": "Perl", "bytes": "716" }, { "name": "Python", "bytes": "874414" }, { "name": "R", "bytes": "454" }, { "name": "Shell", "bytes": "3984" } ], "symlink_target": "" }
git subsplit init git@github.com:RocketPropelledTortoise/Core.git git subsplit publish src/Taxonomy:git@github.com:RocketPropelledTortoise/Taxonomy.git git subsplit publish src/Translation:git@github.com:RocketPropelledTortoise/Translation.git git subsplit publish src/Utilities:git@github.com:RocketPropelledTortoise/Utilities.git rm -rf .subsplit/
{ "content_hash": "496bf0d9c0a06834e9b73902762b44cb", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 91, "avg_line_length": 70, "alnum_prop": 0.8628571428571429, "repo_name": "RocketPropelledTortoise/Core", "id": "b4ca35b1bf19f98c994db2ec7bec79ab3f70c3df", "size": "421", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "subsplit.sh", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "158844" }, { "name": "Shell", "bytes": "1051" } ], "symlink_target": "" }
npm version major
{ "content_hash": "50b4d6effd80d20433d21209b455fc1d", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 17, "avg_line_length": 18, "alnum_prop": 0.8333333333333334, "repo_name": "hg42/uxregexp", "id": "1085af6121683b3358b1eb951731807c03036fbb", "size": "18", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "version-major.zsh", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "40493" }, { "name": "Shell", "bytes": "366" } ], "symlink_target": "" }
Middleware pattern in PHP ================================ A short presentation on Middleware pattern in PHP
{ "content_hash": "f75da6cba2d200a1a83193bbad677213", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 49, "avg_line_length": 27.5, "alnum_prop": 0.5818181818181818, "repo_name": "ojhaujjwal/ojhaujjwal.github.io", "id": "d2c78a6a56f6ca968e0b461c09e988a745c46dc9", "size": "110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "middleware-php-presentation/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "14265" } ], "symlink_target": "" }
#ifndef GLIBCEMU_SYS_ENDIAN_H #define GLIBCEMU_SYS_ENDIAN_H 1 #include <machine/endian.h> /* At the moment NaCl only runs on little-endian machines. */ #define BYTE_ORDER LITTLE_ENDIAN #define htole16(x) (x) #define htole32(x) (x) #define letoh16(x) (x) #define letoh32(x) (x) #endif
{ "content_hash": "da369555e6d7fea8bf1c811a255a77c5", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 61, "avg_line_length": 18.125, "alnum_prop": 0.7137931034482758, "repo_name": "dtkav/naclports", "id": "56fcb9a95de0ab65266385a4da2f5b64a6cf4a65", "size": "470", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ports/glibc-compat/include/sys/endian.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "554317" }, { "name": "C++", "bytes": "67196" }, { "name": "CSS", "bytes": "1787" }, { "name": "JavaScript", "bytes": "219625" }, { "name": "Python", "bytes": "166424" }, { "name": "Shell", "bytes": "303512" } ], "symlink_target": "" }
class CreateFeedTwitterBotTwitterAccounts < ActiveRecord::Migration def change create_table :feed_twitter_bot_twitter_accounts do |t| t.string :name t.string :app_id t.boolean :publication t.boolean :adquisition t.timestamps end end end
{ "content_hash": "69b412f1cdba5faeddcb12f07b3b02da", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 67, "avg_line_length": 23.333333333333332, "alnum_prop": 0.6928571428571428, "repo_name": "camumino/feed_twitter_bot", "id": "196c0798a803150ba076e3f01ff8a7400aa836e1", "size": "280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20160130125432_create_feed_twitter_bot_twitter_accounts.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2666" }, { "name": "HTML", "bytes": "13881" }, { "name": "JavaScript", "bytes": "1627" }, { "name": "Ruby", "bytes": "73965" } ], "symlink_target": "" }
"""BBOB noiseless testbed. The optimisation test functions are represented as classes :py:class:`F1` to :py:class:`F24` and :py:class:`F101` to :py:class:`F130`. Each of these classes has an _evalfull method which expects as argument an array of row vectors and returns a 'noisy' and a 'noiseless' float values. This module implements the class :py:class:`BBOBFunction` and sub-classes: * :py:class:`BBOBNfreeFunction` which have all the methods common to the classes :py:class:`F1` to :py:class:`F24` * :py:class:`BBOBGaussFunction`, :py:class:`BBOBCauchyFunction`, :py:class:`BBOBUniformFunction` which have methods in classes from :py:class:`F101` to :py:class:`F130` Module attributes: * :py:data:`dictbbob` is a dictionary such that dictbbob[2] contains the test function class F2 and f2 = dictbbob[2]() returns the instance 0 of the test function that can be called as f2([1,2,3]). * :py:data:`nfreeIDs` == range(1,25) indices for the noiseless functions that can be found in dictbbob * :py:data:`noisyIDs` == range(101, 131) indices for the noisy functions that can be found in dictbbob. We have nfreeIDs + noisyIDs == sorted(dictbbob.keys()) * :py:data:`nfreeinfos` function infos Examples: >>> from cocopp.eaf import bbobbenchmarks as bn >>> for s in bn.nfreeinfos: ... print s 1: Noise-free Sphere function 2: Separable ellipsoid with monotone transformation <BLANKLINE> Parameter: condition number (default 1e6) <BLANKLINE> <BLANKLINE> 3: Rastrigin with monotone transformation separable "condition" 10 4: skew Rastrigin-Bueche, condition 10, skew-"condition" 100 5: Linear slope 6: Attractive sector function 7: Step-ellipsoid, condition 100, noise-free 8: Rosenbrock noise-free 9: Rosenbrock, rotated 10: Ellipsoid with monotone transformation, condition 1e6 11: Discus (tablet) with monotone transformation, condition 1e6 12: Bent cigar with asymmetric space distortion, condition 1e6 13: Sharp ridge 14: Sum of different powers, between x^2 and x^6, noise-free 15: Rastrigin with asymmetric non-linear distortion, "condition" 10 16: Weierstrass, condition 100 17: Schaffers F7 with asymmetric non-linear transformation, condition 10 18: Schaffers F7 with asymmetric non-linear transformation, condition 1000 19: F8F2 sum of Griewank-Rosenbrock 2-D blocks, noise-free 20: Schwefel with tridiagonal variable transformation 21: Gallagher with 101 Gaussian peaks, condition up to 1000, one global rotation, noise-free 22: Gallagher with 21 Gaussian peaks, condition up to 1000, one global rotation 23: Katsuura function 24: Lunacek bi-Rastrigin, condition 100 <BLANKLINE> in PPSN 2008, Rastrigin part rotated and scaled <BLANKLINE> <BLANKLINE> >>> f3 = bn.F3(13) # instantiate function 3 on instance 13 >>> f3.evaluate([0, 1, 2]) # also: f3([0, 1, 2]) # doctest: +ELLIPSIS 59.8733529... >>> f3.evaluate([[0, 1, 2], [3, 4, 5]]) array([ 59.87335291, 441.17409304]) >>> print bn.instantiate(5)[1] # returns evaluation function and target 51.53 >>> print bn.nfreeIDs # list noise-free functions [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] >>> for i in bn.nfreeIDs: # evaluate all noiseless functions once ... print bn.instantiate(i)[0]([0., 0., 0., 0.]), -77.27454592 6180022.82173 92.9877507529 92.9877507529 140.510117618 70877.9554128 -72.5505202195 33355.7924722 -339.94 4374717.49343 15631566.3487 4715481.0865 550.599783901 -17.2991756229 27.3633128519 -227.827833529 -24.3305918781 131.420159348 40.7103737427 6160.81782924 376.746889545 107.830426761 220.482266557 106.094767386 """ # TODO: define interface for this module. # TODO: funId is expected to be a number since it is used as rseed. import warnings from pdb import set_trace import numpy as np from math import floor as floor from numpy import dot, linspace, diag, tile, zeros, sign, resize from numpy.random import standard_normal as _randn # TODO: may bring confusion from numpy.random import random as _rand # TODO: may bring confusion import sys sys.path.insert(0, '../../../') """ % VAL = BENCHMARKS(X, FUNCID) % VAL = BENCHMARKS(X, STRFUNC) % Input: % X -- solution column vector or matrix of column vectors % FUNCID -- number of function to be executed with X as input, % by default 8. % STRFUNC -- function as string to be executed with X as input % Output: function value(s) of solution(s) % Examples: % F = BENCHMARKS([1 2 3]', 17); % F = BENCHMARKS([1 2 3]', 'f1'); % % NBS = BENCHMARKS() % NBS = BENCHMARKS('FunctionIndices') % Output: % NBS -- array of valid benchmark function numbers, % presumably 1:24 % % FHS = BENCHMARKS('handles') % Output: % FHS -- cell array of function handles % Examples: % FHS = BENCHMARKS('handles'); % f = FHS{1}(x); % evaluates x on the sphere function f1 % f = feval(FHS{1}, x); % ditto % % see also: functions FGENERIC, BENCHMARKINFOS, BENCHMARKSNOISY % Authors (copyright 2009): Nikolaus Hansen, Raymond Ros, Steffen Finck % Version = 'Revision: $Revision: 1115 $' % Last Modified: $Date: 2009-02-09 19:22:42 +0100 (Mon, 09 Feb 2009) $ % INTERFACE OF BENCHMARK FUNCTIONS % FHS = BENCHMARKS('handles'); % FUNC = FHS{1}; % % [FVALUE, FTRUE] = FUNC(X) % [FVALUE, FTRUE] = FUNC(X, [], IINSTANCE) % Input: X -- matrix of column vectors % IINSTANCE -- instance number of the function, sets function % instance (XOPT, FOPT, rotation matrices,...) % up until a new number is set, or the function is % cleared. Default is zero. % Output: row vectors with function value for each input column % FVALUE -- function value % FTRUE -- noise-less, deterministic function value % [FOPT STRFUNCTION] = FUNC('any_even_empty_string', ...) % Output: % FOPT -- function value at optimum % STRFUNCTION -- not yet implemented: function description string, ID before first whitespace % [FOPT STRFUNCTION] = FUNC('any_even_empty_string', DIM, NTRIAL) % Sets rotation matrices and xopt depending on NTRIAL (by changing the random seed). % Output: % FOPT -- function value at optimum % STRFUNCTION -- not yet implemented: function description string, ID before first whitespace % [FOPT, XOPT] = FUNC('xopt', DIM) % Output: % FOPT -- function value at optimum XOPT % XOPT -- optimal solution vector in DIM-D % [FOPT, MATRIX] = FUNC('linearTF', DIM) % might vanish in future % Output: % FOPT -- function value at optimum XOPT % MATRIX -- used transformation matrix """ ### FUNCTION DEFINITION ### def compute_xopt(rseed, dim): """Generate a random vector used as optimum argument. Rounded by four digits, but never to zero. """ xopt = 8 * np.floor(1e4 * unif(dim, rseed))/1e4 - 4 idx = (xopt == 0) xopt[idx] = -1e-5 return xopt def compute_rotation(seed, dim): """Returns an orthogonal basis. The rotation is used in several ways and in combination with non-linear transformations. Search space rotation invariant algorithms are not expected to be invariant under this rotation. """ B = np.reshape(gauss(dim * dim, seed), (dim, dim)) for i in range(dim): for j in range(0, i): B[i] = B[i] - dot(B[i], B[j]) * B[j] B[i] = B[i] / (np.sum(B[i]**2) ** .5) return B def monotoneTFosc(f): """Maps [-inf,inf] to [-inf,inf] with different constants for positive and negative part. """ if np.isscalar(f): if f > 0.: f = np.log(f) / 0.1 f = np.exp(f + 0.49*(np.sin(f) + np.sin(0.79*f))) ** 0.1 elif f < 0.: f = np.log(-f) / 0.1 f = -np.exp(f + 0.49*(np.sin(0.55*f) + np.sin(0.31*f))) ** 0.1 return f else: f = np.asarray(f) g = f.copy() idx = (f > 0) g[idx] = np.log(f[idx]) / 0.1 g[idx] = np.exp(g[idx] + 0.49*(np.sin(g[idx]) + np.sin(0.79*g[idx]))) ** 0.1 idx = (f < 0) g[idx] = np.log(-f[idx]) / 0.1 g[idx] = -np.exp(g[idx] + 0.49*(np.sin(0.55*g[idx]) + np.sin(0.31*g[idx]))) ** 0.1 return g def defaultboundaryhandling(x, fac): """Returns a float penalty for being outside of boundaries [-5, 5]""" xoutside = np.maximum(0., np.abs(x) - 5) * sign(x) fpen = fac * np.sum(xoutside**2, -1) # penalty return fpen def gauss(N, seed): """Samples N standard normally distributed numbers being the same for a given seed """ r = unif(2*N, seed) g = np.sqrt(-2 * np.log(r[:N])) * np.cos(2 * np.pi * r[N:2*N]) if np.any(g == 0.): g[g == 0] = 1e-99 return g def unif(N, inseed): """Generates N uniform numbers with starting seed.""" # initialization inseed = np.abs(inseed) if inseed < 1.: inseed = 1. rgrand = 32 * [0.] aktseed = inseed for i in xrange(39, -1, -1): tmp = floor(aktseed/127773.) aktseed = 16807. * (aktseed - tmp * 127773.) - 2836. * tmp if aktseed < 0: aktseed = aktseed + 2147483647. if i < 32: rgrand[i] = aktseed aktrand = rgrand[0] # sample numbers r = int(N) * [0.] for i in xrange(int(N)): tmp = floor(aktseed/127773.) aktseed = 16807. * (aktseed - tmp * 127773.) - 2836. * tmp if aktseed < 0: aktseed = aktseed + 2147483647. tmp = int(floor(aktrand / 67108865.)) aktrand = rgrand[tmp] rgrand[tmp] = aktseed r[i] = aktrand / 2.147483647e9 r = np.asarray(r) if (r == 0).any(): warning.warn('zero sampled(?), set to 1e-99') r[r == 0] = 1e-99 return r # for testing and comparing to other implementations, # myrand and myrandn are used only for sampling the noise # Rename to myrand and myrandn to rand and randn and # comment lines 24 and 25. _randomnseed = 30. # warning this is a global variable... def _myrandn(size): """Normal random distribution sampling. For testing and comparing purpose. """ global _randomnseed _randomnseed = _randomnseed + 1. if _randomnseed > 1e9: _randomnseed = 1. res = np.reshape(gauss(np.prod(size), _randomnseed), size) return res _randomseed = 30. # warning this is a global variable... def _myrand(size): """Uniform random distribution sampling. For testing and comparing purpose. """ global _randomseed _randomseed = _randomseed + 1 if _randomseed > 1e9: _randomseed = 1 res = np.reshape(unif(np.prod(size), _randomseed), size) return res def fGauss(ftrue, beta): """Returns Gaussian model noisy value.""" # expects ftrue to be a np.array popsi = np.shape(ftrue) fval = ftrue * np.exp(beta * _randn(popsi)) # with gauss noise tol = 1e-8 fval = fval + 1.01 * tol idx = ftrue < tol try: fval[idx] = ftrue[idx] except IndexError: # fval is a scalar if idx: fval = ftrue return fval def fUniform(ftrue, alpha, beta): """Returns uniform model noisy value.""" # expects ftrue to be a np.array popsi = np.shape(ftrue) fval = (_rand(popsi) ** beta * ftrue * np.maximum(1., (1e9 / (ftrue + 1e-99)) ** (alpha * _rand(popsi)))) tol = 1e-8 fval = fval + 1.01 * tol idx = ftrue < tol try: fval[idx] = ftrue[idx] except IndexError: # fval is a scalar if idx: fval = ftrue return fval def fCauchy(ftrue, alpha, p): """Returns Cauchy model noisy value Cauchy with median 1e3*alpha and with p=0.2, zero otherwise P(Cauchy > 1,10,100,1000) = 0.25, 0.032, 0.0032, 0.00032 """ # expects ftrue to be a np.array popsi = np.shape(ftrue) fval = ftrue + alpha * np.maximum(0., 1e3 + (_rand(popsi) < p) * _randn(popsi) / (np.abs(_randn(popsi)) + 1e-199)) tol = 1e-8 fval = fval + 1.01 * tol idx = ftrue < tol try: fval[idx] = ftrue[idx] except IndexError: # fval is a scalar if idx: fval = ftrue return fval ### CLASS DEFINITION ### class AbstractTestFunction(): """Abstract class for test functions. Defines methods to be implemented in test functions which are to be provided to method setfun of class Logger. In particular, (a) the attribute fopt and (b) the method _evalfull. The _evalfull method returns two values, the possibly noisy value and the noise-free value. The latter is only meant to be for recording purpose. """ def __call__(self, x): # makes the instances callable """Returns the objective function value of argument x. Example: >>> from cocopp.eaf import bbobbenchmarks as bn >>> f3 = bn.F3(13) # instantiate function 3 on instance 13 >>> f3([0, 1, 2]) # call f3, same as f3.evaluate([0, 1, 2]) # doctest: +ELLIPSIS 59.8733529... """ return self.evaluate(x) def evaluate(self, x): """Returns the objective function value (in case noisy). """ return self._evalfull(x)[0] # TODO: is it better to leave evaluate out and check for hasattr('evaluate') in ExpLogger? def _evalfull(self, x): """return noisy and noise-free value, the latter for recording purpose. """ raise NotImplementedError def getfopt(self): """Returns the best function value of this instance of the function.""" # TODO: getfopt error: # import bbobbenchmarks as bb # bb.instantiate(1)[0].getfopt() # AttributeError: F1 instance has no attribute '_fopt' if not hasattr(self, 'iinstance'): raise Exception('This function class has not been instantiated yet.') return self._fopt def setfopt(self, fopt): try: self._fopt = float(fopt) except ValueError: raise Exception('Optimal function value must be cast-able to a float.') fopt = property(getfopt, setfopt) class BBOBFunction(AbstractTestFunction): """Abstract class of BBOB test functions. Implements some base functions that are used by the test functions of BBOB such as initialisations of class attributes. """ def __init__(self, iinstance=0, zerox=False, zerof=False, param=None, **kwargs): """Common initialisation. Keyword arguments: iinstance -- instance of the function (int) zerox -- sets xopt to [0, ..., 0] zerof -- sets fopt to 0 param -- parameter of the function (if applicable) kwargs -- additional attributes """ # Either self.rrseed or self.funId have to be defined for BBOBFunctions # TODO: enforce try: rrseed = self.rrseed except AttributeError: rrseed = self.funId try: self.rseed = rrseed + 1e4 * iinstance except TypeError: # rrseed AND iinstance have to be float warnings.warn('self.rseed could not be set, reset to 1 instead.') self.rseed = 1 self.zerox = zerox if zerof: self.fopt = 0. else: self.fopt = min(1000, max(-1000, (np.round(100*100*gauss(1, self.rseed)[0]/gauss(1, self.rseed+1)[0])/100))) self.iinstance = iinstance self.dim = None self.lastshape = None self.param = param for i, v in kwargs.iteritems(): setattr(self, i, v) self._xopt = None def shape_(self, x): # this part is common to all evaluate function # it is assumed x are row vectors curshape = np.shape(x) dim = np.shape(x)[-1] return curshape, dim def getiinstance(self): """Designates the instance of the function class. An instance in this case means a given target function value, a given optimal argument x, and given transformations for the function. It needs to have a string representation. Preferably it should be a number or a string. """ return self._iinstance def setiinstance(self, iinstance): self._iinstance = iinstance iinstance = property(getiinstance, setiinstance) def shortstr(self): """Gives a short string self representation (shorter than str(self)).""" res = 'F%s' % str(self.funId) if hasattr(self, 'param'): res += '_p%s' % str(self.param) # NH param -> self.param return res def __eq__(self, obj): return (self.funId == obj.funId and (not hasattr(self, 'param') or self.param == obj.param)) # TODO: make this test on other attributes than param? # def dimensionality(self, dim): # """Return the availability of dimensionality dim.""" # return True # GETTERS # def getfopt(self): # """Optimal Function Value.""" # return self._fopt # fopt = property(getfopt) def _setxopt(self, xopt): """Return the argument of the optimum of the function.""" self._xopt = xopt def _getxopt(self): """Return the argument of the optimum of the function.""" if self._xopt is None: warnings.warn('You need to evaluate object to set dimension first.') return self._xopt xopt = property(_getxopt, _setxopt) # def getrange(self): # """Return the domain of the function.""" # #TODO: could depend on the dimension # # TODO: return exception NotImplemented yet # pass # range = property(getrange) # def getparam(self): # """Optional parameter value.""" # return self._param # param = property(getparam) # def getitrial(self): # """Instance id number.""" # return self._itrial # itrial = property(getitrial) # def getlinearTf(self): # return self._linearTf # linearTf = property(getlinearTf) # def getrotation(self): # return self._rotation # rotation = property(getrotation) class BBOBNfreeFunction(BBOBFunction): """Class of the noise-free functions of BBOB.""" def noise(self, ftrue): """Returns the noise-free function values.""" return ftrue.copy() class BBOBGaussFunction(BBOBFunction): """Class of the Gauss noise functions of BBOB. Attribute gaussbeta needs to be defined by inheriting classes. """ # gaussbeta = None def noise(self, ftrue): """Returns the noisy function values.""" return fGauss(ftrue, self.gaussbeta) def boundaryhandling(self, x): return defaultboundaryhandling(x, 100.) class BBOBUniformFunction(BBOBFunction, object): """Class of the uniform noise functions of BBOB. Attributes unifalphafac and unifbeta need to be defined by inheriting classes. """ # unifalphafac = None # unifbeta = None def noise(self, ftrue): """Returns the noisy function values.""" return fUniform(ftrue, self.unifalphafac * (0.49 + 1. / self.dim), self.unifbeta) def boundaryhandling(self, x): return defaultboundaryhandling(x, 100.) class BBOBCauchyFunction(BBOBFunction): """Class of the Cauchy noise functions of BBOB. Attributes cauchyalpha and cauchyp need to be defined by inheriting classes. """ # cauchyalpha = None # cauchyp = None def noise(self, ftrue): """Returns the noisy function values.""" return fCauchy(ftrue, self.cauchyalpha, self.cauchyp) def boundaryhandling(self, x): return defaultboundaryhandling(x, 100.) class _FSphere(BBOBFunction): """Abstract Sphere function. Method boundaryhandling needs to be defined. """ rrseed = 1 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! # COMPUTATION core ftrue = np.sum(x**2, -1) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F1(_FSphere, BBOBNfreeFunction): """Noise-free Sphere function""" funId = 1 def boundaryhandling(self, x): return 0. class F101(_FSphere, BBOBGaussFunction): """Sphere with moderate Gauss noise""" funId = 101 gaussbeta = 0.01 class F102(_FSphere, BBOBUniformFunction): """Sphere with moderate uniform noise""" funId = 102 unifalphafac = 0.01 unifbeta = 0.01 class F103(_FSphere, BBOBCauchyFunction): """Sphere with moderate Cauchy noise""" funId = 103 cauchyalpha = 0.01 cauchyp = 0.05 class F107(_FSphere, BBOBGaussFunction): """Sphere with Gauss noise""" funId = 107 gaussbeta = 1. class F108(_FSphere, BBOBUniformFunction): """Sphere with uniform noise""" funId = 108 unifalphafac = 1. unifbeta = 1. class F109(_FSphere, BBOBCauchyFunction): """Sphere with Cauchy noise""" funId = 109 cauchyalpha = 1. cauchyp = 0.2 class F2(BBOBNfreeFunction): """Separable ellipsoid with monotone transformation Parameter: condition number (default 1e6) """ funId = 2 paramValues = (1e0, 1e6) condition = 1e6 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) if hasattr(self, 'param') and self.param: # not self.param is None tmp = self.param else: tmp = self.condition self.scales = tmp ** linspace(0, 1, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! # COMPUTATION core ftrue = dot(monotoneTFosc(x)**2, self.scales) fval = self.noise(ftrue) # without noise # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F3(BBOBNfreeFunction): """Rastrigin with monotone transformation separable "condition" 10""" funId = 3 condition = 10. beta = 0.2 def initwithsize(self, curshape, dim): # DIM-dependent initialisation if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.scales = (self.condition ** .5) ** linspace(0, 1, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) self.arrscales = resize(self.scales, curshape) self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt x = monotoneTFosc(x) idx = (x > 0) x[idx] = x[idx] ** (1 + self.arrexpo[idx] * np.sqrt(x[idx])) x = self.arrscales * x # COMPUTATION core ftrue = 10 * (self.dim - np.sum(np.cos(2 * np.pi * x), -1)) + np.sum(x ** 2, -1) fval = self.noise(ftrue) # without noise # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F4(BBOBNfreeFunction): """skew Rastrigin-Bueche, condition 10, skew-"condition" 100""" funId = 4 condition = 10. alpha = 100. maxindex = np.inf # 1:2:min(DIM,maxindex) are the skew variables rrseed = 3 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.xopt[:min(dim, self.maxindex):2] = abs(self.xopt[:min(dim, self.maxindex):2]) self.scales = (self.condition ** .5) ** linspace(0, 1, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) self.arrscales = resize(self.scales, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING xoutside = np.maximum(0., np.abs(x) - 5) * sign(x) fpen = 1e2 * np.sum(xoutside**2, -1) # penalty fadd = fadd + fpen # self.fadd becomes an array # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # shift optimum to zero x = monotoneTFosc(x) try: tmpx = x[:, :min(self.dim, self.maxindex):2] # tmpx is a reference to a part of x except IndexError: tmpx = x[:min(self.dim, self.maxindex):2] # tmpx is a reference to a part of x tmpx[tmpx > 0] = self.alpha ** .5 * tmpx[tmpx > 0] # this modifies x x = self.arrscales * x # scale while assuming that Xopt == 0 # COMPUTATION core ftrue = 10 * (self.dim - np.sum(np.cos(2 * np.pi * x), -1)) + np.sum(x ** 2, -1) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F5(BBOBNfreeFunction): """Linear slope""" funId = 5 alpha = 100. def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) # TODO: what happens here? else: self.xopt = 5 * sign(compute_xopt(self.rseed, dim)) self.scales = -sign(self.xopt) * (self.alpha ** .5) ** linspace(0, 1, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) fadd = fadd + 5 * np.sum(np.abs(self.scales)) # BOUNDARY HANDLING # move "too" good coordinates back into domain x = np.array(x) # convert x and make a copy of x. #The following may modify x directly. idx_out_of_bounds = (x * self.arrxopt) > 25 # 25 == 5 * 5 x[idx_out_of_bounds] = sign(x[idx_out_of_bounds]) * 5 # TRANSFORMATION IN SEARCH SPACE # COMPUTATION core ftrue = dot(x, self.scales) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F6(BBOBNfreeFunction): """Attractive sector function""" funId = 6 condition = 10. alpha = 100. def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = (self.condition ** .5) ** linspace(0, 1, dim) self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales)) # decouple scaling from function definition self.linearTF = dot(self.linearTF, self.rotation) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.linearTF) # TODO: check # COMPUTATION core idx = (x * self.arrxopt) > 0 x[idx] = self.alpha * x[idx] ftrue = monotoneTFosc(np.sum(x**2, -1)) ** .9 fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class _FStepEllipsoid(BBOBFunction): """Abstract Step-ellipsoid, condition 100 Method boundaryhandling needs to be defined. """ rrseed = 7 condition = 100. alpha = 10. def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = self.condition ** linspace(0, 1, dim) self.linearTF = dot(compute_rotation(self.rseed, dim), diag(((self.condition/10.)**.5) ** linspace(0, 1, dim))) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.linearTF) try: x1 = x[:, 0] except IndexError: x1 = x[0] idx = np.abs(x) > .5 x[idx] = np.round(x[idx]) x[np.negative(idx)] = np.round(self.alpha * x[np.negative(idx)]) / self.alpha x = dot(x, self.rotation) # COMPUTATION core ftrue = .1 * np.maximum(1e-4 * np.abs(x1), dot(x ** 2, self.scales)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F7(_FStepEllipsoid, BBOBNfreeFunction): """Step-ellipsoid, condition 100, noise-free""" funId = 7 def boundaryhandling(self, x): return defaultboundaryhandling(x, 1.) class F113(_FStepEllipsoid, BBOBGaussFunction): """Step-ellipsoid with gauss noise, condition 100""" funId = 113 gaussbeta = 1. class F114(_FStepEllipsoid, BBOBUniformFunction): """Step-ellipsoid with uniform noise, condition 100""" funId = 114 unifalphafac = 1. unifbeta = 1. class F115(_FStepEllipsoid, BBOBCauchyFunction): """Step-ellipsoid with Cauchy noise, condition 100""" funId = 115 cauchyalpha = 1. cauchyp = 0.2 class _FRosenbrock(BBOBFunction): """Abstract Rosenbrock, non-rotated Method boundaryhandling needs to be defined. """ rrseed = 8 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = .75 * compute_xopt(self.rseed, dim) # different from all others self.scales = max(1, dim ** .5 / 8.) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= self.arrxopt! x = self.scales * x x = x + 1 # shift zero to factual optimum 1 # COMPUTATION core try: ftrue = (1e2 * np.sum((x[:, :-1] ** 2 - x[:, 1:]) ** 2, -1) + np.sum((x[:, :-1] - 1.) ** 2, -1)) except IndexError: ftrue = (1e2 * np.sum((x[:-1] ** 2 - x[1:]) ** 2) + np.sum((x[:-1] - 1.) ** 2)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F8(_FRosenbrock, BBOBNfreeFunction): """Rosenbrock noise-free""" funId = 8 def boundaryhandling(self, x): return 0. class F104(_FRosenbrock, BBOBGaussFunction): """Rosenbrock non-rotated with moderate Gauss noise""" funId = 104 gaussbeta = 0.01 class F105(_FRosenbrock, BBOBUniformFunction): """Rosenbrock non-rotated with moderate uniform noise""" funId = 105 unifalphafac = 0.01 unifbeta = 0.01 class F106(_FRosenbrock, BBOBCauchyFunction): """Rosenbrock non-rotated with moderate Cauchy noise""" funId = 106 cauchyalpha = 0.01 cauchyp = 0.05 class F110(_FRosenbrock, BBOBGaussFunction): """Rosenbrock non-rotated with Gauss noise""" funId = 110 gaussbeta = 1. class F111(_FRosenbrock, BBOBUniformFunction): """Rosenbrock non-rotated with uniform noise""" funId = 111 unifalphafac = 1. unifbeta = 1. class F112(_FRosenbrock, BBOBCauchyFunction): """Rosenbrock non-rotated with Cauchy noise""" funId = 112 cauchyalpha = 1. cauchyp = 0.2 class F9(BBOBNfreeFunction): """Rosenbrock, rotated""" funId = 9 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) scale = max(1, dim ** .5 / 8.) # nota: different from scales in F8 self.linearTF = scale * compute_rotation(self.rseed, dim) self.xopt = np.hstack(dot(.5 * np.ones((1, dim)), self.linearTF.T)) / scale ** 2 # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING # TRANSFORMATION IN SEARCH SPACE x = dot(x, self.linearTF) + 0.5 # different from F8 # COMPUTATION core try: ftrue = (1e2 * np.sum((x[:, :-1] ** 2 - x[:, 1:]) ** 2, -1) + np.sum((x[:, :-1] - 1.) ** 2, -1)) except IndexError: ftrue = (1e2 * np.sum((x[:-1] ** 2 - x[1:]) ** 2) + np.sum((x[:-1] - 1.) ** 2)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class _FEllipsoid(BBOBFunction): """Abstract Ellipsoid with monotone transformation. Method boundaryhandling needs to be defined. """ rrseed = 10 condition = 1e6 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = self.condition ** linspace(0, 1, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.rotation) x = monotoneTFosc(x) # COMPUTATION core ftrue = dot(x ** 2, self.scales) try: ftrue = np.hstack(ftrue) except TypeError: # argument 2 to map() must support iteration pass fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F10(_FEllipsoid, BBOBNfreeFunction): """Ellipsoid with monotone transformation, condition 1e6""" funId = 10 condition = 1e6 def boundaryhandling(self, x): return 0. class F116(_FEllipsoid, BBOBGaussFunction): """Ellipsoid with Gauss noise, monotone x-transformation, condition 1e4""" funId = 116 condition = 1e4 gaussbeta = 1. class F117(_FEllipsoid, BBOBUniformFunction): """Ellipsoid with uniform noise, monotone x-transformation, condition 1e4""" funId = 117 condition = 1e4 unifalphafac = 1. unifbeta = 1. class F118(_FEllipsoid, BBOBCauchyFunction): """Ellipsoid with Cauchy noise, monotone x-transformation, condition 1e4""" funId = 118 condition = 1e4 cauchyalpha = 1. cauchyp = 0.2 class F11(BBOBNfreeFunction): """Discus (tablet) with monotone transformation, condition 1e6""" funId = 11 condition = 1e6 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.rotation) x = monotoneTFosc(x) # COMPUTATION core try: ftrue = np.sum(x**2, -1) + (self.condition - 1.) * x[:, 0] ** 2 except IndexError: ftrue = np.sum(x**2) + (self.condition - 1.) * x[0] ** 2 fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F12(BBOBNfreeFunction): """Bent cigar with asymmetric space distortion, condition 1e6""" funId = 12 condition = 1e6 beta = .5 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed + 1e6, dim) # different from others self.rotation = compute_rotation(self.rseed + 1e6, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.rotation) # no scaling here, because it would go to the arrExpo idx = x > 0 x[idx] = x[idx] ** (1 + self.arrexpo[idx] * np.sqrt(x[idx])) x = dot(x, self.rotation) # COMPUTATION core try: ftrue = self.condition * np.sum(x**2, -1) + (1 - self.condition) * x[:, 0] ** 2 except IndexError: ftrue = self.condition * np.sum(x**2) + (1 - self.condition) * x[0] ** 2 fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F13(BBOBNfreeFunction): """Sharp ridge""" funId = 13 condition = 10. alpha = 100. # slope def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = (self.condition ** .5) ** linspace(0, 1, dim) self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales)) self.linearTF = dot(self.linearTF, self.rotation) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.linearTF) # COMPUTATION core try: ftrue = x[:, 0] ** 2 + self.alpha * np.sqrt(np.sum(x[:, 1:] ** 2, -1)) except IndexError: ftrue = x[0] ** 2 + self.alpha * np.sqrt(np.sum(x[1:] ** 2, -1)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class _FDiffPow(BBOBFunction): """Abstract Sum of different powers, between x^2 and x^6. Method boundaryhandling needs to be defined. """ alpha = 4. rrseed = 14 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) self.arrexpo = resize(2. + self.alpha * linspace(0, 1, dim), curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.rotation) # COMPUTATION core ftrue = np.sqrt(np.sum(np.abs(x) ** self.arrexpo, -1)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F14(_FDiffPow, BBOBNfreeFunction): """Sum of different powers, between x^2 and x^6, noise-free""" funId = 14 def boundaryhandling(self, x): return 0. class F119(_FDiffPow, BBOBGaussFunction): """Sum of different powers with Gauss noise, between x^2 and x^6""" funId = 119 gaussbeta = 1. class F120(_FDiffPow, BBOBUniformFunction): """Sum of different powers with uniform noise, between x^2 and x^6""" funId = 120 unifalphafac = 1. unifbeta = 1. class F121(_FDiffPow, BBOBCauchyFunction): """Sum of different powers with seldom Cauchy noise, between x^2 and x^6""" funId = 121 cauchyalpha = 1. cauchyp = 0.2 class F15(BBOBNfreeFunction): """Rastrigin with asymmetric non-linear distortion, "condition" 10""" funId = 15 condition = 10. beta = 0.2 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = (self.condition ** .5) ** linspace(0, 1, dim) self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales)) # decouple scaling from function definition self.linearTF = dot(self.linearTF, self.rotation) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.rotation) # no scaling here, because it would go to the arrexpo x = monotoneTFosc(x) idx = x > 0. x[idx] = x[idx] ** (1. + self.arrexpo[idx] * np.sqrt(x[idx])) # smooth in zero x = dot(x, self.linearTF) # COMPUTATION core ftrue = 10. * (dim - np.sum(np.cos(2 * np.pi * x), -1)) + np.sum(x ** 2, -1) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F16(BBOBNfreeFunction): """Weierstrass, condition 100""" funId = 16 condition = 100. def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = (1. / self.condition ** .5) ** linspace(0, 1, dim) # CAVE? self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales)) # decouple scaling from function definition self.linearTF = dot(self.linearTF, self.rotation) K = np.arange(0, 12) self.aK = np.reshape(0.5 ** K, (1, 12)) self.bK = np.reshape(3. ** K, (1, 12)) self.f0 = np.sum(self.aK * np.cos(2 * np.pi * self.bK * 0.5)) # optimal value # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING xoutside = np.maximum(0, np.abs(x) - 5.) * sign(x) fpen = (10. / dim) * np.sum(xoutside ** 2, -1) fadd = fadd + fpen # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.rotation) x = monotoneTFosc(x) x = dot(x, self.linearTF) # COMPUTATION core if len(curshape) < 2: # popsize is one ftrue = np.sum(dot(self.aK, np.cos(dot(self.bK.T, 2 * np.pi * (np.reshape(x, (1, len(x))) + 0.5))))) else: ftrue = np.zeros(curshape[0]) # curshape[0] is popsize for k, i in enumerate(x): # TODO: simplify next line ftrue[k] = np.sum(dot(self.aK, np.cos(dot(self.bK.T, 2 * np.pi * (np.reshape(i, (1, len(i))) + 0.5))))) ftrue = 10. * (ftrue / dim - self.f0) ** 3 try: ftrue = np.hstack(ftrue) except TypeError: pass fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class _FSchaffersF7(BBOBFunction): """Abstract Schaffers F7 with asymmetric non-linear transformation, condition 10 Class attribute condition and method boundaryhandling need to be defined. """ rrseed = 17 condition = None beta = 0.5 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = (self.condition ** .5) ** linspace(0, 1 , dim) self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales)) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.rotation) idx = x > 0 x[idx] = x[idx] ** (1 + self.arrexpo[idx] * np.sqrt(x[idx])) x = dot(x, self.linearTF) # COMPUTATION core try: s = x[:, :-1] ** 2 + x[:, 1:] ** 2 except IndexError: s = x[:-1] ** 2 + x[1:] ** 2 ftrue = np.mean(s ** .25 * (np.sin(50 * s ** .1) ** 2 + 1), -1) ** 2 fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F17(_FSchaffersF7, BBOBNfreeFunction): """Schaffers F7 with asymmetric non-linear transformation, condition 10""" funId = 17 condition = 10. def boundaryhandling(self, x): return defaultboundaryhandling(x, 10.) class F18(_FSchaffersF7, BBOBNfreeFunction): """Schaffers F7 with asymmetric non-linear transformation, condition 1000""" funId = 18 condition = 1000. def boundaryhandling(self, x): return defaultboundaryhandling(x, 10.) class F122(_FSchaffersF7, BBOBGaussFunction): """Schaffers F7 with Gauss noise, with asymmetric non-linear transformation, condition 10""" funId = 122 condition = 10. gaussbeta = 1. class F123(_FSchaffersF7, BBOBUniformFunction): """Schaffers F7 with uniform noise, asymmetric non-linear transformation, condition 10""" funId = 123 condition = 10. unifalphafac = 1. unifbeta = 1. class F124(_FSchaffersF7, BBOBCauchyFunction): # TODO: check boundary handling """Schaffers F7 with seldom Cauchy noise, asymmetric non-linear transformation, condition 10""" funId = 124 condition = 10. cauchyalpha = 1. cauchyp = 0.2 class _F8F2(BBOBFunction): """Abstract F8F2 sum of Griewank-Rosenbrock 2-D blocks Class attribute facftrue and method boundaryhandling need to be defined. """ facftrue = None rrseed = 19 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: scale = max(1, dim ** .5 / 8.) self.linearTF = scale * compute_rotation(self.rseed, dim) #if self.zerox: # self.xopt = zeros(dim) # does not work here #else: # TODO: clean this line self.xopt = np.hstack(dot(self.linearTF, 0.5 * np.ones((dim, 1)) / scale ** 2)) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = dot(x, self.linearTF) + 0.5 # cannot be replaced with x -= arrxopt! # COMPUTATION core try: f2 = 100. * (x[:, :-1] ** 2 - x[:, 1:]) ** 2 + (1. - x[:, :-1]) ** 2 except IndexError: f2 = 100. * (x[:-1] ** 2 - x[1:]) ** 2 + (1. - x[:-1]) ** 2 ftrue = self.facftrue + self.facftrue * np.sum(f2 / 4000. - np.cos(f2), -1) / (dim - 1.) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F19(_F8F2, BBOBNfreeFunction): """F8F2 sum of Griewank-Rosenbrock 2-D blocks, noise-free""" funId = 19 facftrue = 10. def boundaryhandling(self, x): return 0. class F125(_F8F2, BBOBGaussFunction): """F8F2 sum of Griewank-Rosenbrock 2-D blocks with Gauss noise""" funId = 125 facftrue = 1. gaussbeta = 1. class F126(_F8F2, BBOBUniformFunction): """F8F2 sum of Griewank-Rosenbrock 2-D blocks with uniform noise""" funId = 126 facftrue = 1. unifalphafac = 1. unifbeta = 1. class F127(_F8F2, BBOBCauchyFunction): """F8F2 sum of Griewank-Rosenbrock 2-D blocks with seldom Cauchy noise""" funId = 127 facftrue = 1. cauchyalpha = 1. cauchyp = 0.2 class F20(BBOBNfreeFunction): """Schwefel with tridiagonal variable transformation""" funId = 20 condition = 10. def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = 0.5 * sign(unif(dim, self.rseed) - 0.5) * 4.2096874633 self.scales = (self.condition ** .5) ** np.linspace(0, 1, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(2 * np.abs(self.xopt), curshape) self.arrscales = resize(self.scales, curshape) self.arrsigns = resize(sign(self.xopt), curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # TRANSFORMATION IN SEARCH SPACE x = 2 * self.arrsigns * x # makes the below boundary handling effective for coordinates try: x[:, 1:] = x[:, 1:] + .25 * (x[:, :-1] - self.arrxopt[:, :-1]) except IndexError: x[1:] = x[1:] + .25 * (x[:-1] - self.arrxopt[:-1]) x = 100. * (self.arrscales * (x - self.arrxopt) + self.arrxopt) # BOUNDARY HANDLING xoutside = np.maximum(0., np.abs(x) - 500.) * sign(x) # in [-500, 500] fpen = 0.01 * np.sum(xoutside ** 2, -1) fadd = fadd + fpen # COMPUTATION core ftrue = 0.01 * ((418.9828872724339) - np.mean(x * np.sin(np.sqrt(np.abs(x))), -1)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class _FGallagher(BBOBFunction): """Abstract Gallagher with nhighpeaks Gaussian peaks, condition up to 1000, one global rotation Attribute fac2, nhighpeaks, highpeakcond and method boundary handling need to be defined. """ rrseed = 21 maxcondition = 1000. fitvalues = (1.1, 9.1) fac2 = None # added: factor for xopt not too close to boundaries, used by F22 nhighpeaks = None highpeakcond = None def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: self.rotation = compute_rotation(self.rseed, dim) arrcondition = self.maxcondition ** linspace(0, 1, self.nhighpeaks - 1) idx = np.argsort(unif(self.nhighpeaks - 1, self.rseed)) # random permutation arrcondition = np.insert(arrcondition[idx], 0, self.highpeakcond) self.arrscales = [] for i, e in enumerate(arrcondition): s = e ** linspace(-.5, .5, dim) idx = np.argsort(unif(dim, self.rseed + 1e3 * i)) # permutation instead of rotation self.arrscales.append(s[idx]) # this is inverse Cov self.arrscales = np.vstack(self.arrscales) # compute peak values, 10 is global optimum self.peakvalues = np.insert(linspace(self.fitvalues[0], self.fitvalues[1], self.nhighpeaks - 1), 0, 10.) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.xlocal = dot(self.fac2 * np.reshape(10. * unif(dim * self.nhighpeaks, self.rseed) - 5., (self.nhighpeaks, dim)), self.rotation) if self.zerox: self.xlocal[0, :] = zeros(dim) else: # global optimum not too close to boundary self.xlocal[0, :] = 0.8 * self.xlocal[0, :] self.xopt = dot(self.xlocal[0, :], self.rotation.T) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING fadd = fadd + self.boundaryhandling(x) # TRANSFORMATION IN SEARCH SPACE x = dot(x, self.rotation) # COMPUTATION core fac = -0.5 / dim # f = NaN(nhighpeaks, popsi) # TODO: optimize if len(curshape) < 2: # popsize is 1 in this case f = np.zeros(self.nhighpeaks) xx = tile(x, (self.nhighpeaks, 1)) - self.xlocal f[:] = self.peakvalues * np.exp(fac * np.sum(self.arrscales * xx ** 2, 1)) elif curshape[0] < .5 * self.nhighpeaks: f = np.zeros((curshape[0], self.nhighpeaks)) for k, e in enumerate(x): xx = tile(e, (self.nhighpeaks, 1)) - self.xlocal f[k, :] = self.peakvalues * np.exp(fac * np.sum(self.arrscales * xx ** 2, 1)) else: f = np.zeros((curshape[0], self.nhighpeaks)) for i in range(self.nhighpeaks): xx = (x - tile(self.xlocal[i, :], (curshape[0], 1))) f[:, i] = self.peakvalues[i] * np.exp(fac * (dot(xx ** 2, self.arrscales[i, :]))) ftrue = monotoneTFosc(10 - np.max(f, -1)) ** 2 fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F21(_FGallagher, BBOBNfreeFunction): """Gallagher with 101 Gaussian peaks, condition up to 1000, one global rotation, noise-free""" funId = 21 nhighpeaks = 101 fac2 = 1. highpeakcond = 1000. ** .5 def boundaryhandling(self, x): return defaultboundaryhandling(x, 1.) class F22(_FGallagher, BBOBNfreeFunction): """Gallagher with 21 Gaussian peaks, condition up to 1000, one global rotation""" funId = 22 rrseed = 22 nhighpeaks = 21 fac2 = 0.98 highpeakcond = 1000. def boundaryhandling(self, x): return defaultboundaryhandling(x, 1.) class F128(_FGallagher, BBOBGaussFunction): # TODO: check boundary handling """Gallagher with 101 Gaussian peaks with Gauss noise, condition up to 1000, one global rotation""" funId = 128 nhighpeaks = 101 fac2 = 1. highpeakcond = 1000. ** .5 gaussbeta = 1. class F129(_FGallagher, BBOBUniformFunction): """Gallagher with 101 Gaussian peaks with uniform noise, condition up to 1000, one global rotation""" funId = 129 nhighpeaks = 101 fac2 = 1. highpeakcond = 1000. ** .5 unifalphafac = 1. unifbeta = 1. class F130(_FGallagher, BBOBCauchyFunction): """Gallagher with 101 Gaussian peaks with seldom Cauchy noise, condition up to 1000, one global rotation""" funId = 130 nhighpeaks = 101 fac2 = 1. highpeakcond = 1000. ** .5 cauchyalpha = 1. cauchyp = 0.2 class F23(BBOBNfreeFunction): """Katsuura function""" funId = 23 condition = 100. arr2k = np.reshape(2. ** (np.arange(1, 33)), (1, 32)) # bug-fix for 32-bit (NH): 2 -> 2. (relevance is minor) def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = (self.condition ** .5) ** linspace(0, 1, dim) self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales)) # decouple scaling from function definition self.linearTF = dot(self.linearTF, self.rotation) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING xoutside = np.maximum(0, np.abs(x) - 5.) * sign(x) fpen = np.sum(xoutside ** 2, -1) fadd = fadd + fpen # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! x = dot(x, self.linearTF) # COMPUTATION core if len(curshape) < 2: # popsize is 1 in this case arr = dot(np.reshape(x, (dim, 1)), self.arr2k) # dim times d array ftrue = (-10. / dim ** 2. + 10. / dim ** 2. * np.prod(1 + np.arange(1, dim + 1) * np.dot(np.abs(arr - np.round(arr)), self.arr2k.T ** -1.).T) ** (10. / dim ** 1.2)) else: ftrue = zeros(curshape[0]) for k, e in enumerate(x): arr = dot(np.reshape(e, (dim, 1)), self.arr2k) # dim times d array ftrue[k] = (-10. / dim ** 2. + 10. / dim ** 2. * np.prod(1 + np.arange(1, dim + 1) * np.dot(np.abs(arr - np.round(arr)), self.arr2k.T ** -1.).T) ** (10. / dim ** 1.2)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue class F24(BBOBNfreeFunction): """Lunacek bi-Rastrigin, condition 100 in PPSN 2008, Rastrigin part rotated and scaled """ funId = 24 condition = 100. _mu1 = 2.5 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = .5 * self._mu1 * sign(gauss(dim, self.rseed)) self.rotation = compute_rotation(self.rseed + 1e6, dim) self.scales = (self.condition ** .5) ** linspace(0, 1, dim) self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales)) # decouple scaling from function definition self.linearTF = dot(self.linearTF, self.rotation) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape #self.arrxopt = resize(self.xopt, curshape) self.arrscales = resize(2. * sign(self.xopt), curshape) # makes up for xopt def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING xoutside = np.maximum(0, np.abs(x) - 5.) * sign(x) fpen = 1e4 * np.sum(xoutside ** 2, -1) fadd = fadd + fpen # TRANSFORMATION IN SEARCH SPACE x = self.arrscales * x # COMPUTATION core s = 1 - .5 / ((dim + 20) ** .5 - 4.1) # tested up to DIM = 160 p in [0.25,0.33] d = 1 # shift [1,3], smaller is more difficult mu2 = -((self._mu1 ** 2 - d) / s) ** .5 ftrue = np.minimum(np.sum((x - self._mu1) ** 2, -1), d * dim + s * np.sum((x - mu2) ** 2, -1)) ftrue = ftrue + 10 * (dim - np.sum(np.cos(2 * np.pi * dot(x - self._mu1, self.linearTF)), -1)) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue #dictbbob = {'sphere': F1, 'ellipsoid': F2, 'Rastrigin': F3} nfreefunclasses = (F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24) # hard coded noisyfunclasses = (F101, F102, F103, F104, F105, F106, F107, F108, F109, F110, F111, F112, F113, F114, F115, F116, F117, F118, F119, F120, F121, F122, F123, F124, F125, F126, F127, F128, F129, F130) dictbbobnfree = dict((i.funId, i) for i in nfreefunclasses) nfreeIDs = sorted(dictbbobnfree.keys()) # was: "nfreenames" nfreeinfos = [str(i) + ': ' + dictbbobnfree[i].__doc__ for i in nfreeIDs] dictbbobnoisy = dict((i.funId, i) for i in noisyfunclasses) noisyIDs = sorted(dictbbobnoisy.keys()) # was noisynames funclasses = list(nfreefunclasses) + list(noisyfunclasses) dictbbob = dict((i.funId, i) for i in funclasses) #TODO: pb xopt f9, 21, 22 class _FTemplate(BBOBNfreeFunction): """Template based on F1""" funId = 421337 def initwithsize(self, curshape, dim): # DIM-dependent initialization if self.dim != dim: if self.zerox: self.xopt = zeros(dim) else: self.xopt = compute_xopt(self.rseed, dim) # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices if self.lastshape != curshape: self.dim = dim self.lastshape = curshape self.arrxopt = resize(self.xopt, curshape) self.linearTf = None self.rotation = None def _evalfull(self, x): fadd = self.fopt curshape, dim = self.shape_(x) # it is assumed x are row vectors if self.lastshape != curshape: self.initwithsize(curshape, dim) # BOUNDARY HANDLING # TRANSFORMATION IN SEARCH SPACE x = x - self.arrxopt # cannot be replaced with x -= arrxopt! # COMPUTATION core ftrue = np.sum(x**2, 1) fval = self.noise(ftrue) # FINALIZE ftrue += fadd fval += fadd return fval, ftrue def instantiate(ifun, iinstance=0, param=None, **kwargs): """Returns test function ifun, by default instance 0.""" res = dictbbob[ifun](iinstance=iinstance, param=param, **kwargs) # calling BBOBFunction.__init__(iinstance, param,...) return res, res.fopt def get_param(ifun): """Returns the parameter values of the function ifun.""" try: return dictbbob[ifun].paramValues except AttributeError: return (None, ) if __name__ == "__main__": import doctest doctest.testmod() # run all doctests in this module
{ "content_hash": "e2abd4f190acad382538903dfee7af34", "timestamp": "", "source": "github", "line_count": 2142, "max_line_length": 331, "avg_line_length": 32.968720821662, "alnum_prop": 0.5839221739192002, "repo_name": "PyQuake/earthquakemodels", "id": "eef9d7163d7930f13d7898155eba30cf2af9e6f2", "size": "70666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/cocobbob/coco/deapbbob/bbobbenchmarks.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/** \file TransitionResult.hh * * Auto generated C++ code started by /net/tawas/x/silkyar/570/gem5-stable/src/mem/slicc/symbols/Type.py:554 */ #include <cassert> #include <iostream> #include <string> #include "base/misc.hh" #include "mem/protocol/TransitionResult.hh" using namespace std; // Code for output operator ostream& operator<<(ostream& out, const TransitionResult& obj) { out << TransitionResult_to_string(obj); out << flush; return out; } // Code to convert state to a string string TransitionResult_to_string(const TransitionResult& obj) { switch(obj) { case TransitionResult_Valid: return "Valid"; case TransitionResult_ResourceStall: return "ResourceStall"; case TransitionResult_ProtocolStall: return "ProtocolStall"; default: panic("Invalid range for type TransitionResult"); } } // Code to convert from a string to the enumeration TransitionResult string_to_TransitionResult(const string& str) { if (str == "Valid") { return TransitionResult_Valid; } else if (str == "ResourceStall") { return TransitionResult_ResourceStall; } else if (str == "ProtocolStall") { return TransitionResult_ProtocolStall; } else { panic("Invalid string conversion for %s, type TransitionResult", str); } } // Code to increment an enumeration type TransitionResult& operator++(TransitionResult& e) { assert(e < TransitionResult_NUM); return e = TransitionResult(e+1); }
{ "content_hash": "fd42b07373dd680e60ba14d0623e3247", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 108, "avg_line_length": 24.770491803278688, "alnum_prop": 0.6876240900066182, "repo_name": "silkyar/570_Big_Little", "id": "186890091062a6a24935e991792bf3d98b59d5fa", "size": "1511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/ARM/mem/protocol/TransitionResult.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "232078" }, { "name": "C", "bytes": "887097" }, { "name": "C++", "bytes": "52497889" }, { "name": "D", "bytes": "13736198" }, { "name": "Emacs Lisp", "bytes": "1969" }, { "name": "Java", "bytes": "3096" }, { "name": "JavaScript", "bytes": "78818" }, { "name": "Perl", "bytes": "13199821" }, { "name": "Prolog", "bytes": "977139" }, { "name": "Python", "bytes": "3831426" }, { "name": "Ruby", "bytes": "19404" }, { "name": "Scilab", "bytes": "14370" }, { "name": "Shell", "bytes": "16704" }, { "name": "Visual Basic", "bytes": "2884" }, { "name": "XML", "bytes": "16048" } ], "symlink_target": "" }
Global Game Jam 2015 project
{ "content_hash": "e814cf12457ba0dd43515c6050d66d6b", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 28, "avg_line_length": 29, "alnum_prop": 0.8275862068965517, "repo_name": "anirul/Mirages", "id": "d3a826259f2cd51dfd046324627010d2dc3416cc", "size": "39", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.jboss.hal.ballroom.form; import javax.annotation.Nullable; import com.google.gwt.user.client.ui.Focusable; import elemental2.dom.HTMLElement; import org.jboss.gwt.elemento.core.IsElement; import org.jboss.hal.ballroom.Attachable; import static org.jboss.gwt.elemento.core.Elements.div; import static org.jboss.gwt.elemento.core.Elements.i; import static org.jboss.gwt.elemento.core.Elements.span; import static org.jboss.hal.resources.CSS.fontAwesome; import static org.jboss.hal.resources.CSS.helpBlock; import static org.jboss.hal.resources.CSS.inputGroup; import static org.jboss.hal.resources.CSS.inputGroupAddon; /** * Encapsulates the L&F of a {@linkplain FormItem form item} for a given {@linkplain Form.State form state}. The * appearance must include the label and the input element. Appearances should not hold state (except UI state). * State should be kept in the form item only not in its appearance(s). * <p> * An appearance can apply / unapply {@linkplain Decoration decorations}. */ interface Appearance<T> extends IsElement, Attachable, Focusable { /** Used as a {@code data-} attribute in the root element of the appearances. */ String FORM_ITEM_GROUP = "formItemGroup"; // ------------------------------------------------------ static builder methods static HTMLElement inputGroup() { return div().css(inputGroup).get(); } static HTMLElement helpBlock() { return span().css(helpBlock).get(); } static HTMLElement restrictedMarker() { return span().css(inputGroupAddon) .add(i().css(fontAwesome("lock"))) .get(); } static HTMLElement hintMarker() { return span().css(inputGroupAddon).get(); } // ------------------------------------------------------ API void showValue(T value); default void showExpression(String expression) { // noop } default String asString(T value) { return String.valueOf(value); } void clearValue(); String getId(); void setId(String id); void setName(String name); void setLabel(String label); default void apply(Decoration decoration) { apply(decoration, null); } <C> void apply(Decoration decoration, @Nullable C context); void unapply(Decoration decoration); }
{ "content_hash": "1e49c6c8a3ce4c231f0413c1bc9a3c65", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 112, "avg_line_length": 28.573170731707318, "alnum_prop": 0.6628254374733248, "repo_name": "hal/hal.next", "id": "8c7754469e026d5e9918cf60d338792979b56ca3", "size": "2970", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "ballroom/src/main/java/org/jboss/hal/ballroom/form/Appearance.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "50954" }, { "name": "FreeMarker", "bytes": "33623" }, { "name": "HTML", "bytes": "151281" }, { "name": "Java", "bytes": "5773648" }, { "name": "JavaScript", "bytes": "20449" }, { "name": "Shell", "bytes": "11613" } ], "symlink_target": "" }
<?php class Facade_WP_MetaBox_Template_LinkImage extends Facade_WP_MetaBox_Template { public function getKeys() { return [$this->id]; } }
{ "content_hash": "02f98c436b0e0397a8c822d7062fe50b", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 77, "avg_line_length": 16.444444444444443, "alnum_prop": 0.6959459459459459, "repo_name": "erik-landvall/wp-facade-foundation", "id": "34bfafed10d223c6f220d9cee1330e22662377ec", "size": "148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inc/Facade/WP/MetaBox/Template/LinkImage.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "26" }, { "name": "CSS", "bytes": "1435" }, { "name": "HTML", "bytes": "65296" }, { "name": "PHP", "bytes": "39705" } ], "symlink_target": "" }
import { combineReducers } from 'redux'; import getModuleStatusReducer from '../../lib/getModuleStatusReducer'; import conversationStatus from './conversationStatus'; export function getConversationStatusReducer(types) { return (state = conversationStatus.idle, { type }) => { switch (type) { case types.reply: return conversationStatus.pushing; case types.replySuccess: case types.replyError: return conversationStatus.idle; default: return state; } }; } export function getConversationIdReducer(types) { return (state = null, { type, conversationId }) => { switch (type) { case types.loadId: case types.load: return conversationId; case types.unload: return null; default: return state; } }; } export function getMessagesReducer(types) { return (state = [], { type, messages }) => { switch (type) { case types.load: return messages; case types.unload: return []; default: return state; } }; } export function getSenderNumberReducer(types) { return (state = null, { type, senderNumber }) => { switch (type) { case types.load: return senderNumber; case types.unload: return null; default: return state; } }; } export function getRecipientsReducer(types) { return (state = [], { type, recipients }) => { switch (type) { case types.load: case types.updateRecipients: return recipients; case types.unload: return []; default: return state; } }; } export function getMessageStoreUpdatedAtReducer(types) { return (state = null, { type, conversationsTimestamp }) => { switch (type) { case types.load: { return conversationsTimestamp; } default: return state; } }; } export default function getConversationReducer(types) { return combineReducers({ status: getModuleStatusReducer(types), conversationStatus: getConversationStatusReducer(types), id: getConversationIdReducer(types), messages: getMessagesReducer(types), senderNumber: getSenderNumberReducer(types), recipients: getRecipientsReducer(types), messageStoreUpdatedAt: getMessageStoreUpdatedAtReducer(types), }); }
{ "content_hash": "71fadd5eeb9e8ed6b36eb3b24ac4a91f", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 70, "avg_line_length": 24.621052631578948, "alnum_prop": 0.6412997007268063, "repo_name": "ele828/ringcentral-js-integration-commons", "id": "7d93802c280dff0f8912aca7446fb9a009abfe54", "size": "2339", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/modules/Conversation/getConversationReducer.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2305" }, { "name": "JavaScript", "bytes": "1179672" }, { "name": "PowerShell", "bytes": "173" }, { "name": "Shell", "bytes": "1144" } ], "symlink_target": "" }
package org.deepjava.runtime.mpc555.demo; import org.deepjava.runtime.mpc555.driver.MPIOSM_DIO; import org.deepjava.runtime.ppc32.Task; /* CHANGES: * 24.02.2011 NTB/Zueger creation */ /** * Simple blinker application demo. * Connect an LED to pin MPIOSM12. The LED will be toggled every half second. */ public class SimpleBlinkerDemo extends Task { static MPIOSM_DIO out; /** * Toggles the LED. */ public void action(){ out.set(!out.get()); } static { out = new MPIOSM_DIO(12, true); // Initialize MPIOSM12 as output out.set(false); // Set MPIOSM12 to low // Create and install the task SimpleBlinkerDemo t = new SimpleBlinkerDemo(); t.period = 500; Task.install(t); } }
{ "content_hash": "05a19d1872e9a9bdc3bf9c33b2541537", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 77, "avg_line_length": 20.324324324324323, "alnum_prop": 0.6555851063829787, "repo_name": "deepjava/runtime-library", "id": "ea1b6adf395628285c287aab873c8ec6ffe38716", "size": "1456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/deepjava/runtime/mpc555/demo/SimpleBlinkerDemo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1365433" } ], "symlink_target": "" }
<?php namespace Magento\ProductAlert\Helper; use Magento\Store\Model\Store; /** * ProductAlert data helper * * @author Magento Core Team <core@magentocommerce.com> */ class Data extends \Magento\Framework\Url\Helper\Data { /** * Current product instance (override registry one) * * @var null|\Magento\Catalog\Model\Product */ protected $_product = null; /** * Core registry * * @var \Magento\Framework\Registry */ protected $_coreRegistry = null; /** * @var \Magento\Framework\View\LayoutInterface */ protected $_layout; /** @var \Magento\Store\Model\StoreManagerInterface */ private $_storeManager; /** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\Registry $coreRegistry * @param \Magento\Framework\View\LayoutInterface $layout */ public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Registry $coreRegistry, \Magento\Framework\View\LayoutInterface $layout ) { $this->_coreRegistry = $coreRegistry; $this->_layout = $layout; $this->_storeManager = $storeManager; parent::__construct($context); } /** * Get current product instance * * @return \Magento\Catalog\Model\Product */ public function getProduct() { if ($this->_product !== null) { return $this->_product; } return $this->_coreRegistry->registry('product'); } /** * Set current product instance * * @param \Magento\Catalog\Model\Product $product * @return \Magento\ProductAlert\Helper\Data */ public function setProduct($product) { $this->_product = $product; return $this; } /** * @return Store */ public function getStore() { return $this->_storeManager->getStore(); } /** * @param string $type * @return string */ public function getSaveUrl($type) { return $this->_getUrl( 'productalert/add/' . $type, [ 'product_id' => $this->getProduct()->getId(), \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED => $this->getEncodedUrl() ] ); } /** * Create block instance * * @param string|\Magento\Framework\View\Element\AbstractBlock $block * @return \Magento\Framework\View\Element\AbstractBlock * @throws \Magento\Framework\Exception\LocalizedException */ public function createBlock($block) { if (is_string($block)) { if (class_exists($block)) { $block = $this->_layout->createBlock($block); } } if (!$block instanceof \Magento\Framework\View\Element\AbstractBlock) { throw new \Magento\Framework\Exception\LocalizedException(__('Invalid block type: %1', $block)); } return $block; } /** * Check whether stock alert is allowed * * @return bool */ public function isStockAlertAllowed() { return $this->scopeConfig->isSetFlag( \Magento\ProductAlert\Model\Observer::XML_PATH_STOCK_ALLOW, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } /** * Check whether price alert is allowed * * @return bool */ public function isPriceAlertAllowed() { return $this->scopeConfig->isSetFlag( \Magento\ProductAlert\Model\Observer::XML_PATH_PRICE_ALLOW, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } }
{ "content_hash": "6229697a06fa7200a5cc184da7ad8943", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 108, "avg_line_length": 26.170068027210885, "alnum_prop": 0.5887704704964908, "repo_name": "tarikgwa/test", "id": "60ac58422e7658f81ff6bcd222c271f881b65187", "size": "3945", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "html/app/code/Magento/ProductAlert/Helper/Data.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "26588" }, { "name": "CSS", "bytes": "4874492" }, { "name": "HTML", "bytes": "8635167" }, { "name": "JavaScript", "bytes": "6810903" }, { "name": "PHP", "bytes": "55645559" }, { "name": "Perl", "bytes": "7938" }, { "name": "Shell", "bytes": "4505" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Comp3135Component } from './comp-3135.component'; describe('Comp3135Component', () => { let component: Comp3135Component; let fixture: ComponentFixture<Comp3135Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Comp3135Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Comp3135Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "content_hash": "bc5002fc19ebc2231003c0c89c9dd97e", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 73, "avg_line_length": 23.88888888888889, "alnum_prop": 0.6744186046511628, "repo_name": "angular/angular-cli-stress-test", "id": "bed2c3e0e877edd0263bbebad04698efaa12b764", "size": "847", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/components/comp-3135/comp-3135.component.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1040888" }, { "name": "HTML", "bytes": "300322" }, { "name": "JavaScript", "bytes": "2404" }, { "name": "TypeScript", "bytes": "8535506" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>2nd Electrical control project</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="css/grayscale.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <!-- Navigation --> <nav class="navbar navbar-custom navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse"> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="index.html"> Control Project </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-right navbar-main-collapse"> <ul class="nav navbar-nav"> <!-- Hidden li included to remove active class from about link when scrolled up past about section --> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="basic.html">Basic system</a> </li> <li> <a class="page-scroll" href="sensors.html">Sensors</a> </li> <li> <a class="page-scroll" href="contact.html">Team &amp; Contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Intro Header --> <header class="intro"> <div class="intro-body"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1 class="brand-heading">Toy Car Project</h1> <p class="intro-text">Simple Toy car controlled by an andriod app based on Arduino controller with many other features</p> <a href="#about" class="btn btn-circle page-scroll"> <i class="fa fa-angle-double-down animated"></i> </a> </div> </div> </div> </div> </header> <!-- About Section --> <section id="about" class="container content-section about"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h2>About The project</h2> <p>The main function of the project is to control the car via an android application.</p> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <h4>Additional features:</h4> <ul> <li>Light Follower</li> <li>Smoke detector</li> <li>Tempreture Alarm</li> <li>Falme Alarm</li> <li>IR obstacle avoidance Sensor</li> <li>Tempreture sensor for a fan</li> <li>PIR Sensor</li> </ul> </div> </div> </div> </section> <hr> <!-- Contact Section --> <section id="" class="ind-team container content-section text-center"> <div class="row"> <h2>team members</h2> <div class="col-lg-6"> <p> 1 - Ahmed Reda Abdel-Azeem </p> <p> 3 - Ahmed Abdel-Hakim Bahnasy </p> <p> 5 - Ahmed Abdel-Rahman </p> <p> 7 - Ibrahim Fathy </p> <p> 9 - Anton zakka </p> </div> <div class="col-lg-6"> <p> 2 - Ahmed Abdel-Latif mohammed </p> <p> 4 - Ahmed Abdel-Samie Mohammed </p> <p> 6 - Anas Gamal Amin </p> <p> 8 - Ahmed Saber </p> </div> </div> </section> <br> <br> <br> <footer> <div class="container text-center"> <p>Copyright &copy; Project team - 2017</p> </div> </footer> <script src="vendor/jquery/jquery.js"></script> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="js/grayscale.js"></script> </body> </html>
{ "content_hash": "bbb450510a3baf3630a961a990731612", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 146, "avg_line_length": 37.29677419354839, "alnum_prop": 0.497145822522055, "repo_name": "Ahmed-Abd-El-Samea/control", "id": "b9dce0cd62d938e9eba83c5a392f0a2df0f2b769", "size": "5781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7765" }, { "name": "HTML", "bytes": "39799" }, { "name": "JavaScript", "bytes": "8492" } ], "symlink_target": "" }
module ModablesDSL module Message def self.log if @logger.nil? @logger = Logger.new(STDOUT) @logger.formatter = proc do |severity, datetime, progname, msg| "#{severity} #{datetime.strftime('%Y-%m-%d %H:%M:%S')} - #{msg}\n" end end @logger end def self.error msg self.log.error msg exit 1 end end end
{ "content_hash": "47c74103ced9e1632f92da3bf0755daf", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 77, "avg_line_length": 21.444444444444443, "alnum_prop": 0.5518134715025906, "repo_name": "modables/dsl", "id": "79f25f12853745d20f52aafe399256aa7cf99198", "size": "386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/modables_dsl/message.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "11626" } ], "symlink_target": "" }
#ifndef SRC_BGP_BGP_ORIGIN_VN_PATH_H_ #define SRC_BGP_BGP_ORIGIN_VN_PATH_H_ #include <boost/array.hpp> #include <boost/intrusive_ptr.hpp> #include <tbb/atomic.h> #include <set> #include <string> #include <vector> #include "bgp/bgp_attr_base.h" #include "base/parse_object.h" #include "base/util.h" class BgpAttr; class OriginVnPathDB; class BgpServer; struct OriginVnPathSpec : public BgpAttribute { static const int kSize = -1; static const uint8_t kFlags = Optional | Transitive; OriginVnPathSpec() : BgpAttribute(OriginVnPath, kFlags) { } explicit OriginVnPathSpec(const BgpAttribute &rhs) : BgpAttribute(rhs) { } std::vector<uint64_t> origin_vns; virtual int CompareTo(const BgpAttribute &rhs_attr) const; virtual void ToCanonical(BgpAttr *attr); virtual std::string ToString() const; }; class OriginVnPath { public: typedef boost::array<uint8_t, 8> OriginVnValue; typedef std::vector<OriginVnValue> OriginVnList; explicit OriginVnPath(OriginVnPathDB *ovnpath_db) : ovnpath_db_(ovnpath_db) { refcount_ = 0; } explicit OriginVnPath(const OriginVnPath &rhs) : ovnpath_db_(rhs.ovnpath_db_), origin_vns_(rhs.origin_vns_) { refcount_ = 0; } explicit OriginVnPath(OriginVnPathDB *ovnpath_db, const OriginVnPathSpec spec); virtual ~OriginVnPath() { } virtual void Remove(); void Prepend(const OriginVnValue &value); bool Contains(const OriginVnValue &value) const; int CompareTo(const OriginVnPath &rhs) const; const OriginVnList &origin_vns() const { return origin_vns_; } friend std::size_t hash_value(const OriginVnPath &ovnpath) { size_t hash = 0; for (OriginVnList::const_iterator it = ovnpath.origin_vns_.begin(); it != ovnpath.origin_vns_.end(); ++it) { boost::hash_range(hash, it->begin(), it->end()); } return hash; } private: friend int intrusive_ptr_add_ref(const OriginVnPath *covnpath); friend int intrusive_ptr_del_ref(const OriginVnPath *covnpath); friend void intrusive_ptr_release(const OriginVnPath *covnpath); mutable tbb::atomic<int> refcount_; OriginVnPathDB *ovnpath_db_; OriginVnList origin_vns_; }; inline int intrusive_ptr_add_ref(const OriginVnPath *covnpath) { return covnpath->refcount_.fetch_and_increment(); } inline int intrusive_ptr_del_ref(const OriginVnPath *covnpath) { return covnpath->refcount_.fetch_and_decrement(); } inline void intrusive_ptr_release(const OriginVnPath *covnpath) { int prev = covnpath->refcount_.fetch_and_decrement(); if (prev == 1) { OriginVnPath *ovnpath = const_cast<OriginVnPath *>(covnpath); ovnpath->Remove(); assert(ovnpath->refcount_ == 0); delete ovnpath; } } typedef boost::intrusive_ptr<const OriginVnPath> OriginVnPathPtr; struct OriginVnPathCompare { bool operator()(const OriginVnPath *lhs, const OriginVnPath *rhs) { return lhs->CompareTo(*rhs) < 0; } }; class OriginVnPathDB : public BgpPathAttributeDB<OriginVnPath, OriginVnPathPtr, OriginVnPathSpec, OriginVnPathCompare, OriginVnPathDB> { public: explicit OriginVnPathDB(BgpServer *server); OriginVnPathPtr PrependAndLocate(const OriginVnPath *ovnpath, const OriginVnPath::OriginVnValue &value); private: DISALLOW_COPY_AND_ASSIGN(OriginVnPathDB); }; #endif // SRC_BGP_BGP_ORIGIN_VN_PATH_H_
{ "content_hash": "0be129538810b575d3ce66e7d4a3646d", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 79, "avg_line_length": 31.146551724137932, "alnum_prop": 0.6609465817879878, "repo_name": "srajag/contrail-controller", "id": "865f0546619e64c6f50a29ee3efa83407bd929f9", "size": "3685", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/bgp/bgp_origin_vn_path.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "80551" }, { "name": "C", "bytes": "44989" }, { "name": "C++", "bytes": "14871796" }, { "name": "CSS", "bytes": "531" }, { "name": "Java", "bytes": "171966" }, { "name": "Lua", "bytes": "7673" }, { "name": "Makefile", "bytes": "12439" }, { "name": "Objective-C", "bytes": "720" }, { "name": "Protocol Buffer", "bytes": "1120" }, { "name": "Python", "bytes": "3008184" }, { "name": "Shell", "bytes": "54611" }, { "name": "Thrift", "bytes": "40763" } ], "symlink_target": "" }
/* tslint:disable:no-unused-variable */ // import { TestBed, async, inject, describe, it, expect } from '@angular/core/testing'; import { PatientIdentifier } from './patient-identifier.model'; describe('Model: PatientIdentifiers', () => { const existingPatientIdentifier: any = { uuid: 'uuid', display: 'the patient', identifier: 'the identifier', identifierType: { uuid: ' patient identifiers uuid' } }; it('should wrap openmrs patient identifiers for display correctly', () => { const wrappedPatient: PatientIdentifier = new PatientIdentifier( existingPatientIdentifier ); expect(wrappedPatient.uuid).toEqual(existingPatientIdentifier.uuid); expect(wrappedPatient.display).toEqual(existingPatientIdentifier.display); expect(wrappedPatient.identifier).toEqual( existingPatientIdentifier.identifier ); expect(wrappedPatient.identifierType.uuid).toEqual( existingPatientIdentifier.identifierType.uuid ); }); });
{ "content_hash": "db47a7afe9ec4b413473ec7e895d2faa", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 88, "avg_line_length": 33.333333333333336, "alnum_prop": 0.715, "repo_name": "AMPATH/ng2-amrs", "id": "c67a87a0a22444747ad1a0f398eaa437bbe21b6f", "size": "1000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/models/patient-identifier.model.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "218556" }, { "name": "HTML", "bytes": "746023" }, { "name": "JavaScript", "bytes": "395192" }, { "name": "SCSS", "bytes": "1999" }, { "name": "Shell", "bytes": "363" }, { "name": "TypeScript", "bytes": "3901875" } ], "symlink_target": "" }
struct Mesh; class ResourceMesh : public Resource { public: Mesh *mesh_data; ResourceMesh(long unsigned int id, int timestamp); ~ResourceMesh(); bool LoadToMemory(); bool UnloadFromMemory(); }; #endif //!__RESOURCE_MESH_H__
{ "content_hash": "c553d52d7385ef8e6e5afb841eaf27ac", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 51, "avg_line_length": 12.473684210526315, "alnum_prop": 0.70042194092827, "repo_name": "crandino/Lola_Engine", "id": "775576250dee42252929db2baa300dfb9644e297", "size": "317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/ResourceMesh.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3578378" }, { "name": "C++", "bytes": "4502783" }, { "name": "JavaScript", "bytes": "2933" }, { "name": "Objective-C", "bytes": "61563" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for io.js v1.6.3: v8::PhantomCallbackData&lt; T &gt; Class Template 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="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 style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for io.js v1.6.3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <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&#160;Page</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> <li><a href="examples.html"><span>Examples</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&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- 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="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_phantom_callback_data.html">PhantomCallbackData</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-types">Public Types</a> &#124; <a href="#pub-methods">Public Member Functions</a> &#124; <a href="classv8_1_1_phantom_callback_data-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">v8::PhantomCallbackData&lt; T &gt; Class Template Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for v8::PhantomCallbackData&lt; T &gt;:</div> <div class="dyncontent"> <div class="center"> <img src="classv8_1_1_phantom_callback_data.png" usemap="#v8::PhantomCallbackData&lt; T &gt;_map" alt=""/> <map id="v8::PhantomCallbackData&lt; T &gt;_map" name="v8::PhantomCallbackData&lt; T &gt;_map"> <area href="classv8_1_1internal_1_1_callback_data.html" alt="v8::internal::CallbackData" shape="rect" coords="0,0,186,24"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-types"></a> Public Types</h2></td></tr> <tr class="memitem:abc9d3785b5329fa1163003b9691b1346"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abc9d3785b5329fa1163003b9691b1346"></a> typedef void(*&#160;</td><td class="memItemRight" valign="bottom"><b>Callback</b>) (const <a class="el" href="classv8_1_1_phantom_callback_data.html">PhantomCallbackData</a>&lt; T &gt; &amp;data)</td></tr> <tr class="separator:abc9d3785b5329fa1163003b9691b1346"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><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:a0cd118d7190d55e57cee3883ee778d0a"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0cd118d7190d55e57cee3883ee778d0a"></a> V8_INLINE T *&#160;</td><td class="memItemRight" valign="bottom"><b>GetParameter</b> () const </td></tr> <tr class="separator:a0cd118d7190d55e57cee3883ee778d0a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aef91acbfed893aec03ae24f3f7ad7a58"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aef91acbfed893aec03ae24f3f7ad7a58"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>PhantomCallbackData</b> (<a class="el" href="classv8_1_1_isolate.html">Isolate</a> *isolate, T *parameter)</td></tr> <tr class="separator:aef91acbfed893aec03ae24f3f7ad7a58"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_classv8_1_1internal_1_1_callback_data"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classv8_1_1internal_1_1_callback_data')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="classv8_1_1internal_1_1_callback_data.html">v8::internal::CallbackData</a></td></tr> <tr class="memitem:ac94ddcb7e49c191922f03eb810f62692 inherit pub_methods_classv8_1_1internal_1_1_callback_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac94ddcb7e49c191922f03eb810f62692"></a> V8_INLINE <a class="el" href="classv8_1_1_isolate.html">v8::Isolate</a> *&#160;</td><td class="memItemRight" valign="bottom"><b>GetIsolate</b> () const </td></tr> <tr class="separator:ac94ddcb7e49c191922f03eb810f62692 inherit pub_methods_classv8_1_1internal_1_1_callback_data"><td class="memSeparator" colspan="2">&#160;</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 pro_methods_classv8_1_1internal_1_1_callback_data"><td colspan="2" onclick="javascript:toggleInherit('pro_methods_classv8_1_1internal_1_1_callback_data')"><img src="closed.png" alt="-"/>&#160;Protected Member Functions inherited from <a class="el" href="classv8_1_1internal_1_1_callback_data.html">v8::internal::CallbackData</a></td></tr> <tr class="memitem:a3f5e99bfe131cfea0ce0030895bdf593 inherit pro_methods_classv8_1_1internal_1_1_callback_data"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3f5e99bfe131cfea0ce0030895bdf593"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>CallbackData</b> (<a class="el" href="classv8_1_1_isolate.html">v8::Isolate</a> *isolate)</td></tr> <tr class="separator:a3f5e99bfe131cfea0ce0030895bdf593 inherit pro_methods_classv8_1_1internal_1_1_callback_data"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this class was generated from the following file:<ul> <li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:49:35 for V8 API Reference Guide for io.js v1.6.3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "e1c46864e3dc2ef406e8e513971d1283", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 364, "avg_line_length": 60.58904109589041, "alnum_prop": 0.6876554374858693, "repo_name": "v8-dox/v8-dox.github.io", "id": "c570fe7c468b79856ba348132896b60492d2c6c6", "size": "8846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "318d9d8/html/classv8_1_1_phantom_callback_data.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
local Nodes = {} ------------------------------------------------------------------------------- -- Declaring instance variables ------------------------------------------------------------------------------- -- The transport module Nodes.transport = nil ------------------------------------------------------------------------------- -- @local -- Function to request an endpoint instance for a particular type of request -- -- @param endpoint The string denoting the endpoint -- @param params The parameters to be passed -- @param endpointParams The endpoint params passed while object creation -- -- @return table Error or the data received from the elasticsearch server ------------------------------------------------------------------------------- function Nodes:requestEndpoint(endpoint, params, endpointParams) local Endpoint = require("elasticsearch.endpoints.Nodes." .. endpoint) local endpoint = Endpoint:new{ transport = self.transport, endpointParams = endpointParams or {} } if params ~= nil then -- Parameters need to be set local err = endpoint:setParams(params); if err ~= nil then -- Some error in setting parameters, return to user return nil, err end end -- Making request local response, err = endpoint:request() if response == nil then -- Some error in response, return to user return nil, err end -- Request successful, return body return response.body, response.statusCode end ------------------------------------------------------------------------------- -- Function to retrieve info of a node -- -- @usage -- params["node_id"] = (list) A comma-separated list of node IDs or names to limit the returned information; use '_local' to return information from the node you"re connecting to, leave empty to get information from all nodes -- ["metric"] = (list) A comma-separated list of metrics you wish returned. Leave empty to return all. -- ["flat_settings"] = (boolean) Return settings in flat format (default: false) -- ["human"] = (boolean) Whether to return time and byte values in human-readable format. -- -- @param params The stats Parameters -- -- @return table Error or the data received from the elasticsearch server ------------------------------------------------------------------------------- function Nodes:info(params) return self:requestEndpoint("Info", params) end ------------------------------------------------------------------------------- -- Function to retrieve statistics of a node -- -- @usage -- params["fields"] = (list) A comma-separated list of fields for 'fielddata' metric (supports wildcards) -- ["metric_family"] = (enum) Limit the information returned to a certain metric family -- ["metric"] = (enum) Limit the information returned for 'indices' family to a specific metric -- ["node_id"] = (list) A comma-separated list of node IDs or names to limit the returned information; use '_local' to return information from the node you"re connecting to, leave empty to get information from all nodes -- ["all"] = (boolean) Return all available information -- ["clear"] = (boolean) Reset the default level of detail -- ["fs"] = (boolean) Return information about the filesystem -- ["http"] = (boolean) Return information about HTTP -- ["indices"] = (boolean) Return information about indices -- ["jvm"] = (boolean) Return information about the JVM -- ["network"] = (boolean) Return information about network -- ["os"] = (boolean) Return information about the operating system -- ["process"] = (boolean) Return information about the Elasticsearch process -- ["thread_pool"] = (boolean) Return information about the thread pool -- ["transport"] = (boolean) Return information about transport -- -- @param params The stats Parameters -- -- @return table Error or the data received from the elasticsearch server ------------------------------------------------------------------------------- function Nodes:stats(params) return self:requestEndpoint("Stats", params) end ------------------------------------------------------------------------------- -- Function to retrieve current hot threads -- -- @usage -- params["node_id"] = (list) A comma-separated list of node IDs or names to limit the returned information; use '_local' to return information from the node you"re connecting to, leave empty to get information from all nodes -- ["interval"] = (time) The interval for the second sampling of threads -- ["snapshots"] = (number) Number of samples of thread stacktrace (default: 10) -- ["threads"] = (number) Specify the number of threads to provide information for (default: 3) -- ["type"] = (enum) The type to sample (default: cpu) -- -- @param params The stats Parameters -- -- @return table Error or the data received from the elasticsearch server ------------------------------------------------------------------------------- function Nodes:hotThreads(params) return self:requestEndpoint("HotThreads", params) end ------------------------------------------------------------------------------- -- Function to shutdown nodes -- -- @usage -- params["node_id"] = (list) A comma-separated list of node IDs or names to perform the operation on; use '_local' to perform the operation on the node you"re connected to, leave empty to perform the operation on all nodes -- ["delay"] = (time) Set the delay for the operation (default: 1s) -- ["exit"] = (boolean) Exit the JVM as well (default: true) -- -- @param params The stats Parameters -- -- @return table Error or the data received from the elasticsearch server ------------------------------------------------------------------------------- function Nodes:shutdown(params) return self:requestEndpoint("Shutdown", params) end ------------------------------------------------------------------------------- -- @local -- Returns an instance of Nodes class ------------------------------------------------------------------------------- function Nodes:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end return Nodes
{ "content_hash": "9127f96232e075aaf95f43a0a1f91e1f", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 231, "avg_line_length": 47.64179104477612, "alnum_prop": 0.5593671679197995, "repo_name": "DhavalKapil/elasticsearch-lua", "id": "99726243bf8346336a96562806e181df10be5318", "size": "6628", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/elasticsearch/Nodes.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "628365" }, { "name": "Shell", "bytes": "5442" } ], "symlink_target": "" }
/** * @constructor * @extends {WebInspector.Object} * @param {WebInspector.Setting} breakpointStorage * @param {WebInspector.DebuggerModel} debuggerModel * @param {WebInspector.Workspace} workspace */ WebInspector.BreakpointManager = function(breakpointStorage, debuggerModel, workspace) { this._storage = new WebInspector.BreakpointManager.Storage(this, breakpointStorage); this._debuggerModel = debuggerModel; this._workspace = workspace; this._breakpoints = new Map(); this._breakpointForDebuggerId = {}; this._breakpointsForUISourceCode = new Map(); this._sourceFilesWithRestoredBreakpoints = {}; this._debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.BreakpointResolved, this._breakpointResolved, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._projectWillReset, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); } WebInspector.BreakpointManager.Events = { BreakpointAdded: "breakpoint-added", BreakpointRemoved: "breakpoint-removed" } WebInspector.BreakpointManager.sourceFileId = function(uiSourceCode) { if (!uiSourceCode.url) return ""; var deobfuscatedPrefix = uiSourceCode.formatted() ? "deobfuscated:" : ""; return deobfuscatedPrefix + uiSourceCode.uri(); } WebInspector.BreakpointManager.prototype = { /** * @param {WebInspector.UISourceCode} uiSourceCode */ _restoreBreakpoints: function(uiSourceCode) { var sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); if (!sourceFileId || this._sourceFilesWithRestoredBreakpoints[sourceFileId]) return; this._sourceFilesWithRestoredBreakpoints[sourceFileId] = true; // Erase provisional breakpoints prior to restoring them. for (var debuggerId in this._breakpointForDebuggerId) { var breakpoint = this._breakpointForDebuggerId[debuggerId]; if (breakpoint._sourceFileId !== sourceFileId) continue; breakpoint.remove(true); } this._storage._restoreBreakpoints(uiSourceCode); }, /** * @param {WebInspector.Event} event */ _uiSourceCodeAdded: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data); this._restoreBreakpoints(uiSourceCode); if (uiSourceCode.contentType() === WebInspector.resourceTypes.Script || uiSourceCode.contentType() === WebInspector.resourceTypes.Document) { uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.SourceMappingChanged, this._uiSourceCodeMappingChanged, this); uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.FormattedChanged, this._uiSourceCodeFormatted, this); } }, /** * @param {WebInspector.Event} event */ _uiSourceCodeFormatted: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.target); this._restoreBreakpoints(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _resetBreakpoints: function(uiSourceCode) { var sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); var breakpoints = this._breakpoints.keys(); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; if (breakpoint._sourceFileId !== sourceFileId) return; if (breakpoint.enabled()) { breakpoint._removeFromDebugger(); breakpoint._setInDebugger(); } } }, /** * @param {WebInspector.Event} event */ _uiSourceCodeMappingChanged: function(event) { var identityHasChanged = /** @type {boolean} */ (event.data.identityHasChanged); if (!identityHasChanged) return; var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.target); this._resetBreakpoints(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number} lineNumber * @param {string} condition * @param {boolean} enabled * @return {WebInspector.BreakpointManager.Breakpoint} */ setBreakpoint: function(uiSourceCode, lineNumber, condition, enabled) { this._debuggerModel.setBreakpointsActive(true); return this._innerSetBreakpoint(uiSourceCode, lineNumber, condition, enabled); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number} lineNumber * @param {string} condition * @param {boolean} enabled * @return {WebInspector.BreakpointManager.Breakpoint} */ _innerSetBreakpoint: function(uiSourceCode, lineNumber, condition, enabled) { var breakpoint = this.findBreakpoint(uiSourceCode, lineNumber); if (breakpoint) { breakpoint._updateBreakpoint(condition, enabled); return breakpoint; } breakpoint = new WebInspector.BreakpointManager.Breakpoint(this, uiSourceCode, lineNumber, condition, enabled); this._breakpoints.put(breakpoint); return breakpoint; }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number} lineNumber * @return {?WebInspector.BreakpointManager.Breakpoint} */ findBreakpoint: function(uiSourceCode, lineNumber) { var breakpoints = this._breakpointsForUISourceCode.get(uiSourceCode); var lineBreakpoints = breakpoints ? breakpoints[lineNumber] : null; return lineBreakpoints ? lineBreakpoints[0] : null; }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {Array.<WebInspector.BreakpointManager.Breakpoint>} */ breakpointsForUISourceCode: function(uiSourceCode) { var result = []; var breakpoints = /** @type {Array.<WebInspector.BreakpointManager.Breakpoint>} */(this._breakpoints.keys()); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; var uiLocation = breakpoint._primaryUILocation; if (uiLocation.uiSourceCode === uiSourceCode) result.push(breakpoint); } return result; }, /** * @return {Array.<WebInspector.BreakpointManager.Breakpoint>} */ allBreakpoints: function() { var result = []; var breakpoints = /** @type {Array.<WebInspector.BreakpointManager.Breakpoint>} */(this._breakpoints.keys()); return breakpoints; }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {Array.<{breakpoint: WebInspector.BreakpointManager.Breakpoint, uiLocation: WebInspector.UILocation}>} */ breakpointLocationsForUISourceCode: function(uiSourceCode) { var result = []; var breakpoints = /** @type {Array.<WebInspector.BreakpointManager.Breakpoint>} */(this._breakpoints.keys()); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; var uiLocations = Object.values(breakpoint._uiLocations); for (var j = 0; j < uiLocations.length; ++j) { var uiLocation = uiLocations[j]; if (uiLocation.uiSourceCode === uiSourceCode) result.push({breakpoint: breakpoint, uiLocation: uiLocations[j]}); } } return result; }, /** * @return {Array.<{breakpoint: WebInspector.BreakpointManager.Breakpoint, uiLocation: WebInspector.UILocation}>} */ allBreakpointLocations: function() { var result = []; var breakpoints = /** @type {Array.<WebInspector.BreakpointManager.Breakpoint>} */(this._breakpoints.keys()); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; var uiLocations = Object.values(breakpoint._uiLocations); for (var j = 0; j < uiLocations.length; ++j) result.push({breakpoint: breakpoint, uiLocation: uiLocations[j]}); } return result; }, /** * @param {boolean} toggleState */ toggleAllBreakpoints: function(toggleState) { var breakpoints = /** @type {Array.<WebInspector.BreakpointManager.Breakpoint>} */(this._breakpoints.keys()); for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = breakpoints[i]; if (breakpoint.enabled() != toggleState) breakpoint.setEnabled(toggleState); } }, removeAllBreakpoints: function() { var breakpoints = /** @type {Array.<WebInspector.BreakpointManager.Breakpoint>} */(this._breakpoints.keys()); for (var i = 0; i < breakpoints.length; ++i) breakpoints[i].remove(); }, reset: function() { // Remove all breakpoints from UI and debugger, do not update storage. this._storage._muted = true; this.removeAllBreakpoints(); delete this._storage._muted; // Remove all provisional breakpoints from the debugger. for (var debuggerId in this._breakpointForDebuggerId) this._debuggerModel.removeBreakpoint(debuggerId); this._breakpointForDebuggerId = {}; this._sourceFilesWithRestoredBreakpoints = {}; }, _projectWillReset: function(event) { var project = /** @type {WebInspector.Project} */ (event.data); var uiSourceCodes = project.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) { var uiSourceCode = uiSourceCodes[i]; var breakpoints = this._breakpointsForUISourceCode.get(uiSourceCode) || []; for (var lineNumber in breakpoints) { var lineBreakpoints = breakpoints[lineNumber]; for (var j = 0; j < lineBreakpoints.length; ++j) { var breakpoint = lineBreakpoints[j]; breakpoint._resetLocations(); } } this._breakpointsForUISourceCode.remove(uiSourceCode); breakpoints = this.breakpointsForUISourceCode(uiSourceCode); for (var j = 0; j < breakpoints.length; ++j) { var breakpoint = breakpoints[j]; this._breakpoints.remove(breakpoint); } var sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); delete this._sourceFilesWithRestoredBreakpoints[sourceFileId]; } }, _breakpointResolved: function(event) { var breakpointId = /** @type {DebuggerAgent.BreakpointId} */ (event.data.breakpointId); var location = /** @type {WebInspector.DebuggerModel.Location} */ (event.data.location); var breakpoint = this._breakpointForDebuggerId[breakpointId]; if (!breakpoint) return; if (!this._breakpoints.contains(breakpoint)) this._breakpoints.put(breakpoint); breakpoint._addResolvedLocation(location); }, /** * @param {WebInspector.BreakpointManager.Breakpoint} breakpoint * @param {boolean} removeFromStorage */ _removeBreakpoint: function(breakpoint, removeFromStorage) { console.assert(!breakpoint._debuggerId) this._breakpoints.remove(breakpoint); if (removeFromStorage) this._storage._removeBreakpoint(breakpoint); }, /** * @param {WebInspector.BreakpointManager.Breakpoint} breakpoint * @param {WebInspector.UILocation} uiLocation */ _uiLocationAdded: function(breakpoint, uiLocation) { var breakpoints = this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode); if (!breakpoints) { breakpoints = {}; this._breakpointsForUISourceCode.put(uiLocation.uiSourceCode, breakpoints); } var lineBreakpoints = breakpoints[uiLocation.lineNumber]; if (!lineBreakpoints) { lineBreakpoints = []; breakpoints[uiLocation.lineNumber] = lineBreakpoints; } lineBreakpoints.push(breakpoint); this.dispatchEventToListeners(WebInspector.BreakpointManager.Events.BreakpointAdded, {breakpoint: breakpoint, uiLocation: uiLocation}); }, /** * @param {WebInspector.BreakpointManager.Breakpoint} breakpoint * @param {WebInspector.UILocation} uiLocation */ _uiLocationRemoved: function(breakpoint, uiLocation) { var breakpoints = this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode); if (!breakpoints) return; var lineBreakpoints = breakpoints[uiLocation.lineNumber]; if (!lineBreakpoints) return; lineBreakpoints.remove(breakpoint); if (!lineBreakpoints.length) delete breakpoints[uiLocation.lineNumber]; this.dispatchEventToListeners(WebInspector.BreakpointManager.Events.BreakpointRemoved, {breakpoint: breakpoint, uiLocation: uiLocation}); }, __proto__: WebInspector.Object.prototype } /** * @constructor * @param {WebInspector.BreakpointManager} breakpointManager * @param {WebInspector.UISourceCode} uiSourceCode * @param {number} lineNumber * @param {string} condition * @param {boolean} enabled */ WebInspector.BreakpointManager.Breakpoint = function(breakpointManager, uiSourceCode, lineNumber, condition, enabled) { this._breakpointManager = breakpointManager; this._primaryUILocation = new WebInspector.UILocation(uiSourceCode, lineNumber, 0); this._sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); /** @type {Array.<WebInspector.Script.Location>} */ this._liveLocations = []; /** @type {Object.<string, WebInspector.UILocation>} */ this._uiLocations = {}; // Force breakpoint update. /** @type {string} */ this._condition; /** @type {boolean} */ this._enabled; this._updateBreakpoint(condition, enabled); } WebInspector.BreakpointManager.Breakpoint.prototype = { /** * @return {WebInspector.UILocation} */ primaryUILocation: function() { return this._primaryUILocation; }, /** * @param {WebInspector.DebuggerModel.Location} location */ _addResolvedLocation: function(location) { this._liveLocations.push(this._breakpointManager._debuggerModel.createLiveLocation(location, this._locationUpdated.bind(this, location))); }, /** * @param {WebInspector.DebuggerModel.Location} location * @param {WebInspector.UILocation} uiLocation */ _locationUpdated: function(location, uiLocation) { var stringifiedLocation = location.scriptId + ":" + location.lineNumber + ":" + location.columnNumber; var oldUILocation = /** @type {WebInspector.UILocation} */ (this._uiLocations[stringifiedLocation]); if (oldUILocation) this._breakpointManager._uiLocationRemoved(this, oldUILocation); if (this._uiLocations[""]) { delete this._uiLocations[""]; this._breakpointManager._uiLocationRemoved(this, this._primaryUILocation); } this._uiLocations[stringifiedLocation] = uiLocation; this._breakpointManager._uiLocationAdded(this, uiLocation); }, /** * @return {boolean} */ enabled: function() { return this._enabled; }, /** * @param {boolean} enabled */ setEnabled: function(enabled) { this._updateBreakpoint(this._condition, enabled); }, /** * @return {string} */ condition: function() { return this._condition; }, /** * @param {string} condition */ setCondition: function(condition) { this._updateBreakpoint(condition, this._enabled); }, /** * @param {string} condition * @param {boolean} enabled */ _updateBreakpoint: function(condition, enabled) { if (this._enabled === enabled && this._condition === condition) return; if (this._enabled) this._removeFromDebugger(); this._enabled = enabled; this._condition = condition; this._breakpointManager._storage._updateBreakpoint(this); var scriptFile = this._primaryUILocation.uiSourceCode.scriptFile(); if (this._enabled && !(scriptFile && scriptFile.hasDivergedFromVM())) { this._setInDebugger(); return; } this._fakeBreakpointAtPrimaryLocation(); }, /** * @param {boolean=} keepInStorage */ remove: function(keepInStorage) { var removeFromStorage = !keepInStorage; this._resetLocations(); this._removeFromDebugger(); this._breakpointManager._removeBreakpoint(this, removeFromStorage); }, _setInDebugger: function() { console.assert(!this._debuggerId); var rawLocation = this._primaryUILocation.uiLocationToRawLocation(); var debuggerModelLocation = /** @type {WebInspector.DebuggerModel.Location} */ (rawLocation); if (debuggerModelLocation) this._breakpointManager._debuggerModel.setBreakpointByScriptLocation(debuggerModelLocation, this._condition, didSetBreakpoint.bind(this)); else this._breakpointManager._debuggerModel.setBreakpointByURL(this._primaryUILocation.uiSourceCode.url, this._primaryUILocation.lineNumber, 0, this._condition, didSetBreakpoint.bind(this)); /** * @this {WebInspector.BreakpointManager.Breakpoint} * @param {?DebuggerAgent.BreakpointId} breakpointId * @param {Array.<WebInspector.DebuggerModel.Location>} locations */ function didSetBreakpoint(breakpointId, locations) { if (!breakpointId) { this._resetLocations(); this._breakpointManager._removeBreakpoint(this, false); return; } this._debuggerId = breakpointId; this._breakpointManager._breakpointForDebuggerId[breakpointId] = this; if (!locations.length) { this._fakeBreakpointAtPrimaryLocation(); return; } this._resetLocations(); for (var i = 0; i < locations.length; ++i) { var script = this._breakpointManager._debuggerModel.scriptForId(locations[i].scriptId); var uiLocation = script.rawLocationToUILocation(locations[i].lineNumber, locations[i].columnNumber); if (this._breakpointManager.findBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber)) { // location clash this.remove(); return; } } for (var i = 0; i < locations.length; ++i) this._addResolvedLocation(locations[i]); } }, _removeFromDebugger: function() { if (this._debuggerId) { this._breakpointManager._debuggerModel.removeBreakpoint(this._debuggerId); delete this._breakpointManager._breakpointForDebuggerId[this._debuggerId]; delete this._debuggerId; } }, _resetLocations: function() { for (var stringifiedLocation in this._uiLocations) this._breakpointManager._uiLocationRemoved(this, this._uiLocations[stringifiedLocation]); for (var i = 0; i < this._liveLocations.length; ++i) this._liveLocations[i].dispose(); this._liveLocations = []; this._uiLocations = {}; }, /** * @return {string} */ _breakpointStorageId: function() { if (!this._sourceFileId) return ""; return this._sourceFileId + ":" + this._primaryUILocation.lineNumber; }, _fakeBreakpointAtPrimaryLocation: function() { this._resetLocations(); this._uiLocations[""] = this._primaryUILocation; this._breakpointManager._uiLocationAdded(this, this._primaryUILocation); } } /** * @constructor * @param {WebInspector.BreakpointManager} breakpointManager * @param {WebInspector.Setting} setting */ WebInspector.BreakpointManager.Storage = function(breakpointManager, setting) { this._breakpointManager = breakpointManager; this._setting = setting; var breakpoints = this._setting.get(); /** @type {Object.<string,WebInspector.BreakpointManager.Storage.Item>} */ this._breakpoints = {}; for (var i = 0; i < breakpoints.length; ++i) { var breakpoint = /** @type {WebInspector.BreakpointManager.Storage.Item} */ (breakpoints[i]); this._breakpoints[breakpoint.sourceFileId + ":" + breakpoint.lineNumber] = breakpoint; } } WebInspector.BreakpointManager.Storage.prototype = { /** * @param {WebInspector.UISourceCode} uiSourceCode */ _restoreBreakpoints: function(uiSourceCode) { this._muted = true; var sourceFileId = WebInspector.BreakpointManager.sourceFileId(uiSourceCode); for (var id in this._breakpoints) { var breakpoint = this._breakpoints[id]; if (breakpoint.sourceFileId === sourceFileId) this._breakpointManager._innerSetBreakpoint(uiSourceCode, breakpoint.lineNumber, breakpoint.condition, breakpoint.enabled); } delete this._muted; }, /** * @param {WebInspector.BreakpointManager.Breakpoint} breakpoint */ _updateBreakpoint: function(breakpoint) { if (this._muted || !breakpoint._breakpointStorageId()) return; this._breakpoints[breakpoint._breakpointStorageId()] = new WebInspector.BreakpointManager.Storage.Item(breakpoint); this._save(); }, /** * @param {WebInspector.BreakpointManager.Breakpoint} breakpoint */ _removeBreakpoint: function(breakpoint) { if (this._muted) return; delete this._breakpoints[breakpoint._breakpointStorageId()]; this._save(); }, _save: function() { var breakpointsArray = []; for (var id in this._breakpoints) breakpointsArray.push(this._breakpoints[id]); this._setting.set(breakpointsArray); } } /** * @constructor * @param {WebInspector.BreakpointManager.Breakpoint} breakpoint */ WebInspector.BreakpointManager.Storage.Item = function(breakpoint) { var primaryUILocation = breakpoint.primaryUILocation(); this.sourceFileId = breakpoint._sourceFileId; this.lineNumber = primaryUILocation.lineNumber; this.condition = breakpoint.condition(); this.enabled = breakpoint.enabled(); } /** @type {WebInspector.BreakpointManager} */ WebInspector.breakpointManager = null;
{ "content_hash": "db74c3d22d3c3247f1fdc60a23375588", "timestamp": "", "source": "github", "line_count": 641, "max_line_length": 197, "avg_line_length": 35.68642745709828, "alnum_prop": 0.6401311475409837, "repo_name": "kangbiu/strikingly-interview", "id": "02910f7391a4bc67fe8400985127b0b120ea3d72", "size": "24437", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/node-inspector/front-end/BreakpointManager.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "17199" }, { "name": "JavaScript", "bytes": "874" } ], "symlink_target": "" }