text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
* Copyright (C) 2018 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebSocketHandshake.h"
#include "Cookie.h"
#include "CookieJar.h"
#include "HTTPHeaderMap.h"
#include "HTTPHeaderNames.h"
#include "HTTPHeaderValues.h"
#include "HTTPParsers.h"
#include "InspectorInstrumentation.h"
#include "Logging.h"
#include "ResourceRequest.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include <wtf/URL.h>
#include "WebSocket.h"
#include <wtf/ASCIICType.h>
#include <wtf/CryptographicallyRandomNumber.h>
#include <wtf/SHA1.h>
#include <wtf/StdLibExtras.h>
#include <wtf/StringExtras.h>
#include <wtf/Vector.h>
#include <wtf/text/Base64.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringView.h>
#include <wtf/text/WTFString.h>
#include <wtf/unicode/CharacterNames.h>
namespace WebCore {
static String resourceName(const URL& url)
{
auto path = url.path();
auto result = makeString(
path,
path.isEmpty() ? "/" : "",
url.queryWithLeadingQuestionMark()
);
ASSERT(!result.isEmpty());
ASSERT(!result.contains(' '));
return result;
}
static String hostName(const URL& url, bool secure)
{
ASSERT(url.protocolIs("wss") == secure);
StringBuilder builder;
builder.append(url.host().convertToASCIILowercase());
if (url.port() && ((!secure && url.port().value() != 80) || (secure && url.port().value() != 443))) {
builder.append(':');
builder.appendNumber(url.port().value());
}
return builder.toString();
}
static const size_t maxInputSampleSize = 128;
static String trimInputSample(const char* p, size_t len)
{
String s = String(p, std::min<size_t>(len, maxInputSampleSize));
if (len > maxInputSampleSize)
s.append(horizontalEllipsis);
return s;
}
static String generateSecWebSocketKey()
{
static const size_t nonceSize = 16;
unsigned char key[nonceSize];
cryptographicallyRandomValues(key, nonceSize);
return base64Encode(key, nonceSize);
}
String WebSocketHandshake::getExpectedWebSocketAccept(const String& secWebSocketKey)
{
static const char* const webSocketKeyGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
SHA1 sha1;
CString keyData = secWebSocketKey.ascii();
sha1.addBytes(reinterpret_cast<const uint8_t*>(keyData.data()), keyData.length());
sha1.addBytes(reinterpret_cast<const uint8_t*>(webSocketKeyGUID), strlen(webSocketKeyGUID));
SHA1::Digest hash;
sha1.computeHash(hash);
return base64Encode(hash.data(), SHA1::hashSize);
}
WebSocketHandshake::WebSocketHandshake(const URL& url, const String& protocol, const String& userAgent, const String& clientOrigin, bool allowCookies)
: m_url(url)
, m_clientProtocol(protocol)
, m_secure(m_url.protocolIs("wss"))
, m_mode(Incomplete)
, m_userAgent(userAgent)
, m_clientOrigin(clientOrigin)
, m_allowCookies(allowCookies)
{
m_secWebSocketKey = generateSecWebSocketKey();
m_expectedAccept = getExpectedWebSocketAccept(m_secWebSocketKey);
}
WebSocketHandshake::~WebSocketHandshake() = default;
const URL& WebSocketHandshake::url() const
{
return m_url;
}
void WebSocketHandshake::setURL(const URL& url)
{
m_url = url.isolatedCopy();
}
// FIXME: Return type should just be String, not const String.
const String WebSocketHandshake::host() const
{
return m_url.host().convertToASCIILowercase();
}
const String& WebSocketHandshake::clientProtocol() const
{
return m_clientProtocol;
}
void WebSocketHandshake::setClientProtocol(const String& protocol)
{
m_clientProtocol = protocol;
}
bool WebSocketHandshake::secure() const
{
return m_secure;
}
String WebSocketHandshake::clientLocation() const
{
return makeString(m_secure ? "wss" : "ws", "://", hostName(m_url, m_secure), resourceName(m_url));
}
CString WebSocketHandshake::clientHandshakeMessage() const
{
// Keep the following consistent with clientHandshakeRequest().
StringBuilder builder;
builder.appendLiteral("GET ");
builder.append(resourceName(m_url));
builder.appendLiteral(" HTTP/1.1\r\n");
Vector<String> fields;
fields.append("Upgrade: websocket");
fields.append("Connection: Upgrade");
fields.append("Host: " + hostName(m_url, m_secure));
fields.append("Origin: " + m_clientOrigin);
if (!m_clientProtocol.isEmpty())
fields.append("Sec-WebSocket-Protocol: " + m_clientProtocol);
// Note: Cookies are not retrieved in the WebContent process. Instead, a proxy object is
// added in the handshake, and is exchanged for actual cookies in the Network process.
// Add no-cache headers to avoid compatibility issue.
// There are some proxies that rewrite "Connection: upgrade"
// to "Connection: close" in the response if a request doesn't contain
// these headers.
fields.append("Pragma: no-cache");
fields.append("Cache-Control: no-cache");
fields.append("Sec-WebSocket-Key: " + m_secWebSocketKey);
fields.append("Sec-WebSocket-Version: 13");
const String extensionValue = m_extensionDispatcher.createHeaderValue();
if (extensionValue.length())
fields.append("Sec-WebSocket-Extensions: " + extensionValue);
// Add a User-Agent header.
fields.append(makeString("User-Agent: ", m_userAgent));
// Fields in the handshake are sent by the client in a random order; the
// order is not meaningful. Thus, it's ok to send the order we constructed
// the fields.
for (auto& field : fields) {
builder.append(field);
builder.appendLiteral("\r\n");
}
builder.appendLiteral("\r\n");
return builder.toString().utf8();
}
ResourceRequest WebSocketHandshake::clientHandshakeRequest(const Function<String(const URL&)>& cookieRequestHeaderFieldValue) const
{
// Keep the following consistent with clientHandshakeMessage().
ResourceRequest request(m_url);
request.setHTTPMethod("GET");
request.setHTTPHeaderField(HTTPHeaderName::Connection, "Upgrade");
request.setHTTPHeaderField(HTTPHeaderName::Host, hostName(m_url, m_secure));
request.setHTTPHeaderField(HTTPHeaderName::Origin, m_clientOrigin);
if (!m_clientProtocol.isEmpty())
request.setHTTPHeaderField(HTTPHeaderName::SecWebSocketProtocol, m_clientProtocol);
URL url = httpURLForAuthenticationAndCookies();
if (m_allowCookies) {
String cookie = cookieRequestHeaderFieldValue(url);
if (!cookie.isEmpty())
request.setHTTPHeaderField(HTTPHeaderName::Cookie, cookie);
}
request.setHTTPHeaderField(HTTPHeaderName::Pragma, HTTPHeaderValues::noCache());
request.setHTTPHeaderField(HTTPHeaderName::CacheControl, HTTPHeaderValues::noCache());
request.setHTTPHeaderField(HTTPHeaderName::SecWebSocketKey, m_secWebSocketKey);
request.setHTTPHeaderField(HTTPHeaderName::SecWebSocketVersion, "13");
const String extensionValue = m_extensionDispatcher.createHeaderValue();
if (extensionValue.length())
request.setHTTPHeaderField(HTTPHeaderName::SecWebSocketExtensions, extensionValue);
// Add a User-Agent header.
request.setHTTPUserAgent(m_userAgent);
return request;
}
void WebSocketHandshake::reset()
{
m_mode = Incomplete;
m_extensionDispatcher.reset();
}
int WebSocketHandshake::readServerHandshake(const char* header, size_t len)
{
m_mode = Incomplete;
int statusCode;
String statusText;
int lineLength = readStatusLine(header, len, statusCode, statusText);
if (lineLength == -1)
return -1;
if (statusCode == -1) {
m_mode = Failed; // m_failureReason is set inside readStatusLine().
return len;
}
LOG(Network, "WebSocketHandshake %p readServerHandshake() Status code is %d", this, statusCode);
m_serverHandshakeResponse = ResourceResponse();
m_serverHandshakeResponse.setHTTPStatusCode(statusCode);
m_serverHandshakeResponse.setHTTPStatusText(statusText);
if (statusCode != 101) {
m_mode = Failed;
m_failureReason = makeString("Unexpected response code: ", statusCode);
return len;
}
m_mode = Normal;
if (!strnstr(header, "\r\n\r\n", len)) {
// Just hasn't been received fully yet.
m_mode = Incomplete;
return -1;
}
const char* p = readHTTPHeaders(header + lineLength, header + len);
if (!p) {
LOG(Network, "WebSocketHandshake %p readServerHandshake() readHTTPHeaders() failed", this);
m_mode = Failed; // m_failureReason is set inside readHTTPHeaders().
return len;
}
if (!checkResponseHeaders()) {
LOG(Network, "WebSocketHandshake %p readServerHandshake() checkResponseHeaders() failed", this);
m_mode = Failed;
return p - header;
}
m_mode = Connected;
return p - header;
}
WebSocketHandshake::Mode WebSocketHandshake::mode() const
{
return m_mode;
}
String WebSocketHandshake::failureReason() const
{
return m_failureReason;
}
String WebSocketHandshake::serverWebSocketProtocol() const
{
return m_serverHandshakeResponse.httpHeaderFields().get(HTTPHeaderName::SecWebSocketProtocol);
}
String WebSocketHandshake::serverSetCookie() const
{
return m_serverHandshakeResponse.httpHeaderFields().get(HTTPHeaderName::SetCookie);
}
String WebSocketHandshake::serverUpgrade() const
{
return m_serverHandshakeResponse.httpHeaderFields().get(HTTPHeaderName::Upgrade);
}
String WebSocketHandshake::serverConnection() const
{
return m_serverHandshakeResponse.httpHeaderFields().get(HTTPHeaderName::Connection);
}
String WebSocketHandshake::serverWebSocketAccept() const
{
return m_serverHandshakeResponse.httpHeaderFields().get(HTTPHeaderName::SecWebSocketAccept);
}
String WebSocketHandshake::acceptedExtensions() const
{
return m_extensionDispatcher.acceptedExtensions();
}
const ResourceResponse& WebSocketHandshake::serverHandshakeResponse() const
{
return m_serverHandshakeResponse;
}
void WebSocketHandshake::addExtensionProcessor(std::unique_ptr<WebSocketExtensionProcessor> processor)
{
m_extensionDispatcher.addProcessor(WTFMove(processor));
}
URL WebSocketHandshake::httpURLForAuthenticationAndCookies() const
{
URL url = m_url.isolatedCopy();
bool couldSetProtocol = url.setProtocol(m_secure ? "https" : "http");
ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
return url;
}
// https://tools.ietf.org/html/rfc6455#section-4.1
// "The HTTP version MUST be at least 1.1."
static inline bool headerHasValidHTTPVersion(StringView httpStatusLine)
{
const char* httpVersionStaticPreambleLiteral = "HTTP/";
StringView httpVersionStaticPreamble(reinterpret_cast<const LChar*>(httpVersionStaticPreambleLiteral), strlen(httpVersionStaticPreambleLiteral));
if (!httpStatusLine.startsWith(httpVersionStaticPreamble))
return false;
// Check that there is a version number which should be at least three characters after "HTTP/"
unsigned preambleLength = httpVersionStaticPreamble.length();
if (httpStatusLine.length() < preambleLength + 3)
return false;
auto dotPosition = httpStatusLine.find('.', preambleLength);
if (dotPosition == notFound)
return false;
StringView majorVersionView = httpStatusLine.substring(preambleLength, dotPosition - preambleLength);
bool isValid;
int majorVersion = majorVersionView.toIntStrict(isValid);
if (!isValid)
return false;
unsigned minorVersionLength;
unsigned charactersLeftAfterDotPosition = httpStatusLine.length() - dotPosition;
for (minorVersionLength = 1; minorVersionLength < charactersLeftAfterDotPosition; minorVersionLength++) {
if (!isASCIIDigit(httpStatusLine[dotPosition + minorVersionLength]))
break;
}
int minorVersion = (httpStatusLine.substring(dotPosition + 1, minorVersionLength)).toIntStrict(isValid);
if (!isValid)
return false;
return (majorVersion >= 1 && minorVersion >= 1) || majorVersion >= 2;
}
// Returns the header length (including "\r\n"), or -1 if we have not received enough data yet.
// If the line is malformed or the status code is not a 3-digit number,
// statusCode and statusText will be set to -1 and a null string, respectively.
int WebSocketHandshake::readStatusLine(const char* header, size_t headerLength, int& statusCode, String& statusText)
{
// Arbitrary size limit to prevent the server from sending an unbounded
// amount of data with no newlines and forcing us to buffer it all.
static const int maximumLength = 1024;
statusCode = -1;
statusText = String();
const char* space1 = nullptr;
const char* space2 = nullptr;
const char* p;
size_t consumedLength;
for (p = header, consumedLength = 0; consumedLength < headerLength; p++, consumedLength++) {
if (*p == ' ') {
if (!space1)
space1 = p;
else if (!space2)
space2 = p;
} else if (*p == '\0') {
// The caller isn't prepared to deal with null bytes in status
// line. WebSockets specification doesn't prohibit this, but HTTP
// does, so we'll just treat this as an error.
m_failureReason = "Status line contains embedded null"_s;
return p + 1 - header;
} else if (!isASCII(*p)) {
m_failureReason = "Status line contains non-ASCII character"_s;
return p + 1 - header;
} else if (*p == '\n')
break;
}
if (consumedLength == headerLength)
return -1; // We have not received '\n' yet.
const char* end = p + 1;
int lineLength = end - header;
if (lineLength > maximumLength) {
m_failureReason = "Status line is too long"_s;
return maximumLength;
}
// The line must end with "\r\n".
if (lineLength < 2 || *(end - 2) != '\r') {
m_failureReason = "Status line does not end with CRLF"_s;
return lineLength;
}
if (!space1 || !space2) {
m_failureReason = makeString("No response code found: ", trimInputSample(header, lineLength - 2));
return lineLength;
}
StringView httpStatusLine(reinterpret_cast<const LChar*>(header), space1 - header);
if (!headerHasValidHTTPVersion(httpStatusLine)) {
m_failureReason = makeString("Invalid HTTP version string: ", httpStatusLine);
return lineLength;
}
StringView statusCodeString(reinterpret_cast<const LChar*>(space1 + 1), space2 - space1 - 1);
if (statusCodeString.length() != 3) // Status code must consist of three digits.
return lineLength;
for (int i = 0; i < 3; ++i)
if (!isASCIIDigit(statusCodeString[i])) {
m_failureReason = makeString("Invalid status code: ", statusCodeString);
return lineLength;
}
bool ok = false;
statusCode = statusCodeString.toIntStrict(ok);
ASSERT(ok);
statusText = String(space2 + 1, end - space2 - 3); // Exclude "\r\n".
return lineLength;
}
const char* WebSocketHandshake::readHTTPHeaders(const char* start, const char* end)
{
StringView name;
String value;
bool sawSecWebSocketExtensionsHeaderField = false;
bool sawSecWebSocketAcceptHeaderField = false;
bool sawSecWebSocketProtocolHeaderField = false;
const char* p = start;
for (; p < end; p++) {
size_t consumedLength = parseHTTPHeader(p, end - p, m_failureReason, name, value);
if (!consumedLength)
return nullptr;
p += consumedLength;
// Stop once we consumed an empty line.
if (name.isEmpty())
break;
HTTPHeaderName headerName;
if (!findHTTPHeaderName(name, headerName)) {
// Evidence in the wild shows that services make use of custom headers in the handshake
m_serverHandshakeResponse.addHTTPHeaderField(name.toString(), value);
continue;
}
// https://tools.ietf.org/html/rfc7230#section-3.2.4
// "Newly defined header fields SHOULD limit their field values to US-ASCII octets."
if ((headerName == HTTPHeaderName::SecWebSocketExtensions
|| headerName == HTTPHeaderName::SecWebSocketAccept
|| headerName == HTTPHeaderName::SecWebSocketProtocol)
&& !value.isAllASCII()) {
m_failureReason = makeString(name, " header value should only contain ASCII characters");
return nullptr;
}
if (headerName == HTTPHeaderName::SecWebSocketExtensions) {
if (sawSecWebSocketExtensionsHeaderField) {
m_failureReason = "The Sec-WebSocket-Extensions header must not appear more than once in an HTTP response"_s;
return nullptr;
}
if (!m_extensionDispatcher.processHeaderValue(value)) {
m_failureReason = m_extensionDispatcher.failureReason();
return nullptr;
}
sawSecWebSocketExtensionsHeaderField = true;
} else {
if (headerName == HTTPHeaderName::SecWebSocketAccept) {
if (sawSecWebSocketAcceptHeaderField) {
m_failureReason = "The Sec-WebSocket-Accept header must not appear more than once in an HTTP response"_s;
return nullptr;
}
sawSecWebSocketAcceptHeaderField = true;
} else if (headerName == HTTPHeaderName::SecWebSocketProtocol) {
if (sawSecWebSocketProtocolHeaderField) {
m_failureReason = "The Sec-WebSocket-Protocol header must not appear more than once in an HTTP response"_s;
return nullptr;
}
sawSecWebSocketProtocolHeaderField = true;
}
m_serverHandshakeResponse.addHTTPHeaderField(headerName, value);
}
}
return p;
}
bool WebSocketHandshake::checkResponseHeaders()
{
const String& serverWebSocketProtocol = this->serverWebSocketProtocol();
const String& serverUpgrade = this->serverUpgrade();
const String& serverConnection = this->serverConnection();
const String& serverWebSocketAccept = this->serverWebSocketAccept();
if (serverUpgrade.isNull()) {
m_failureReason = "Error during WebSocket handshake: 'Upgrade' header is missing"_s;
return false;
}
if (serverConnection.isNull()) {
m_failureReason = "Error during WebSocket handshake: 'Connection' header is missing"_s;
return false;
}
if (serverWebSocketAccept.isNull()) {
m_failureReason = "Error during WebSocket handshake: 'Sec-WebSocket-Accept' header is missing"_s;
return false;
}
if (!equalLettersIgnoringASCIICase(serverUpgrade, "websocket")) {
m_failureReason = "Error during WebSocket handshake: 'Upgrade' header value is not 'WebSocket'"_s;
return false;
}
if (!equalLettersIgnoringASCIICase(serverConnection, "upgrade")) {
m_failureReason = "Error during WebSocket handshake: 'Connection' header value is not 'Upgrade'"_s;
return false;
}
if (serverWebSocketAccept != m_expectedAccept) {
m_failureReason = "Error during WebSocket handshake: Sec-WebSocket-Accept mismatch"_s;
return false;
}
if (!serverWebSocketProtocol.isNull()) {
if (m_clientProtocol.isEmpty()) {
m_failureReason = "Error during WebSocket handshake: Sec-WebSocket-Protocol mismatch"_s;
return false;
}
Vector<String> result = m_clientProtocol.split(WebSocket::subprotocolSeparator());
if (!result.contains(serverWebSocketProtocol)) {
m_failureReason = "Error during WebSocket handshake: Sec-WebSocket-Protocol mismatch"_s;
return false;
}
}
return true;
}
} // namespace WebCore
| {
"pile_set_name": "Github"
} |
/***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#pragma once
#include "../../Axioms/ReturnValue.hpp"
#include "../../Native/NativeTypeFor.hpp"
#include "../../Native/NativeTypeForCppml.hpp"
#include "../../Native/TypedNativeLibraryFunction.hpp"
template<class T>
class NativeTypeForImpl;
template<class A0, class A1, class A2, class A3, class A4, class A5>
class NativeTypeForImpl<Fora::ReturnValue<A0, A1, A2, A3, A4, A5> > {
public:
static NativeType get(void)
{
return NativeType::Composite(NativeTypeFor<uint64_t>::get()) +
NativeType::Composite(
NativeType::Array(
NativeTypeFor<uint8_t>::get(),
sizeof(Fora::ReturnValue<A0, A1, A2, A3, A4, A5>) - sizeof(uint64_t)
)
);
}
};
template<class A0, class A1, class A2, class A3, class A4, class A5>
class TypedNativeExpressionBehaviors<Fora::ReturnValue<A0, A1, A2, A3, A4, A5> > {
public:
TypedNativeExpressionBehaviors(NativeExpression e) : mThis(e)
{
}
TypedNativeExpression<uint64_t> getIndex() const
{
return TypedNativeExpression<uint64_t>(mThis[0]);
}
TypedNativeExpression<A0> get0() const
{
return TypedNativeExpression<A0>(
mThis[1].cast(NativeTypeFor<A0>::get(), true)
);
}
TypedNativeExpression<A1> get1() const
{
return TypedNativeExpression<A1>(
mThis[1].cast(NativeTypeFor<A1>::get(), true)
);
}
TypedNativeExpression<A2> get2() const
{
return TypedNativeExpression<A2>(
mThis[1].cast(NativeTypeFor<A2>::get(), true)
);
}
TypedNativeExpression<A3> get3() const
{
return TypedNativeExpression<A3>(
mThis[1].cast(NativeTypeFor<A3>::get(), true)
);
}
TypedNativeExpression<A4> get4() const
{
return TypedNativeExpression<A4>(
mThis[1].cast(NativeTypeFor<A4>::get(), true)
);
}
TypedNativeExpression<A5> get5() const
{
return TypedNativeExpression<A5>(
mThis[1].cast(NativeTypeFor<A5>::get(), true)
);
}
private:
NativeExpression mThis;
};
| {
"pile_set_name": "Github"
} |
// DEFINITE UNSAFE
#include <stdio.h>
#include <string.h>
char* foo(char* a, int n) {
int i;
for (i = 0; i < n; i++)
a[i] = 'A';
return a;
}
int main() {
char str[50];
strcpy(str, "This is string.h library function");
puts(str);
memset(str, '$', 50); // SAFE
char* A = foo(str, 10);
// char * B; <- B will be undefined
char B[10];
memcpy(B, A, 10); // SAFE
char* C = foo(B, 11); // WARNING
puts(C);
return (0);
}
| {
"pile_set_name": "Github"
} |
class ObjectParams
@isValid: (param) ->
###
Проверяет, что указанный параметр присутствует в данном наборе параметров
@param param: any
@return: boolean
###
return no unless typeof(param) is 'string'
# RANDOM необходим для идентификации параграфов, __RANDOM некоторое время создавался по ошибке
return yes if param in ['RANDOM', '__RANDOM']
return no unless param.substring(0, 2) is @_prefix
return yes if @.hasOwnProperty(param.substring(2))
no
class TextLevelParams extends ObjectParams
###
Список поддерживаемых текстовых параметров
Соглашение имен: для проверки важно ставить значения параметров равному имени параметра с префиксом 'T_'
###
@_prefix: 'T_'
@URL: 'T_URL'
@BOLD: 'T_BOLD'
@ITALIC: 'T_ITALIC'
@STRUCKTHROUGH: 'T_STRUCKTHROUGH'
@UNDERLINED: 'T_UNDERLINED'
@BG_COLOR: 'T_BG_COLOR'
class LineLevelParams extends ObjectParams
###
Список поддерживаемых текстовых параметров
Соглашение имен: для проверки важно ставить значения параметров равному имени параметра с префиксом 'L_'
###
@_prefix: 'L_'
@BULLETED: 'L_BULLETED'
@NUMBERED: 'L_NUMBERED'
class ModelField
@PARAMS: 'params'
@TEXT: 't'
class ParamsField
@TEXT: '__TEXT'
@TYPE: '__TYPE'
@ID: '__ID'
@URL: '__URL'
@MIME: '__MIME'
@SIZE: '__SIZE'
@THUMBNAIL: '__THUMBNAIL'
@USER_ID: '__USER_ID'
@NAME: '__NAME'
@RANDOM: 'RANDOM'
@TAG: '__TAG'
@THREAD_ID: '__THREAD_ID'
class ModelType
@TEXT: 'TEXT'
@BLIP: 'BLIP'
@LINE: 'LINE'
@ATTACHMENT: 'ATTACHMENT'
@RECIPIENT: 'RECIPIENT'
@TASK_RECIPIENT: 'TASK'
@GADGET: 'GADGET'
@FILE: 'FILE'
@TAG: 'TAG'
exports.TextLevelParams = TextLevelParams
exports.LineLevelParams = LineLevelParams
exports.ModelField = ModelField
exports.ParamsField = ParamsField
exports.ModelType = ModelType
| {
"pile_set_name": "Github"
} |
/*
* Hibernate Search, full-text search for your domain model
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.search.testsupport.textbuilder;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
/**
* Test utility meant to produce sentences of a randomly generated language,
* having some properties of natural languages.
* The goal is to produce sentences which look like a western text,
* but without needing an actual resource to read from so we can create unlimited
* garbage. We also get a chance to produce some novel poetry.
* All sentences from the same SentenceInventor will share
* a limited dictionary, making the frequencies somehow repeatable, suitable to test
* with Lucene.
* Sentences produced depend from the constructor arguments,
* making the output predictable for testing purposes.
*
* @author Sanne Grinovero
*/
public class SentenceInventor {
private final Random r;
private final WordDictionary dictionary;
private final Locale randomlocale;
//array contains repeated object for probability distribution (more chance for a ",")
private final char[] sentenceSeparators = new char[] { ',', ',', ',' , ';', ':', ':' };
//same as above, but favour the "full stop" char as a more likely end for periods.
private final char[] periodSeparators = new char[] { '.', '.', '.' , '.', '.', '?', '?', '!' };
/**
* @param randomSeed the seed to use for random generator
* @param dictionarySize the number of terms to insert in the dictionary used to build sentences
*/
public SentenceInventor(long randomSeed, int dictionarySize) {
r = new Random( randomSeed );
randomlocale = randomLocale();
dictionary = randomDictionary( dictionarySize );
}
/**
* @return a random Locale among the ones available on the current system
*/
private Locale randomLocale() {
Locale[] availableLocales = Locale.getAvailableLocales();
int index = r.nextInt( availableLocales.length );
return availableLocales[index];
}
/**
* @return a random character from the ASCII table (text chars only)
*/
public char randomCharacter() {
return (char) (r.nextInt( 26 ) + 65);
}
/**
* @param length the desired length
* @return a randomly generated String
*/
public String randomString(int length) {
char[] chars = new char[length];
for ( int i = 0; i < length; i++ ) {
chars[i] = randomCharacter();
}
return new String( chars );
}
/**
* Produces a randomly generated String, using
* only western alphabet characters and selecting
* the length as a normal distribution of natural languages.
* @return the generated String
*/
public String randomString() {
double d = r.nextGaussian() * 6.3d;
int l = (int) d + 6;
if ( l > 0 ) {
return randomString( l );
}
else {
return randomString();
}
}
/**
* Produces a random String, which might be lowercase,
* completely uppercase, or uppercasing the first char
* (randomly selected)
* @return produced String
*/
public String randomTerm() {
int i = r.nextInt( 200 );
String term = randomString();
if ( i > 10 ) {
//completely lowercase 189/200 cases
return term.toLowerCase( randomlocale );
}
else if ( i < 2 ) {
//completely uppercase in 2/200 cases
return term;
}
else {
//first letter uppercase in 9/200 cases
return term.substring( 0, 1 ) + term.substring( 1 ).toLowerCase( randomlocale );
}
}
private WordDictionary randomDictionary(int size) {
Set<String> tree = new TreeSet<String>();
while ( tree.size() != size ) {
tree.add( randomTerm() );
}
return new WordDictionary( tree );
}
/**
* Builds a sentence concatenating terms from the generated dictionary and spaces
* @return a sentence
*/
public String nextSentence() {
int sentenceLength = r.nextInt( 3 ) + r.nextInt( 10 ) + 1;
String[] sentence = new String[sentenceLength];
for ( int i = 0; i < sentenceLength; i++ ) {
sentence[i] = dictionary.randomWord();
}
if ( sentenceLength == 1 ) {
return sentence[0];
}
else {
StringBuilder sb = new StringBuilder( sentence[0] );
for ( int i = 1; i < sentenceLength; i++ ) {
sb.append( " " );
sb.append( sentence[i] );
}
return sb.toString();
}
}
/**
* Combines a random (gaussian) number of sentences in a period,
* using some punctuation symbols and
* capitalizing first char, terminating with dot and newline.
* @return
*/
public String nextPeriod() {
//Combine two random values to make extreme long/short less likely,
//But still make the "one statement" period more likely than other shapes.
int periodLengthSentences = r.nextInt( 6 ) + r.nextInt( 4 ) - 3;
periodLengthSentences = ( periodLengthSentences < 1 ) ? 1 : periodLengthSentences;
String firstsentence = nextSentence();
StringBuilder sb = new StringBuilder()
.append( firstsentence.substring( 0,1 ).toUpperCase( randomlocale ) )
.append( firstsentence.substring( 1 ) );
for ( int i = 1; i < periodLengthSentences; i++ ) {
int separatorCharIndex = r.nextInt( sentenceSeparators.length );
sb
.append( sentenceSeparators[separatorCharIndex] )
.append( ' ' )
.append( nextSentence() );
}
int periodSeparatorCharIndex = r.nextInt( periodSeparators.length );
sb.append( periodSeparators[periodSeparatorCharIndex] );
sb.append( "\n" );
return sb.toString();
}
//run it to get an idea of what this class is going to produce
public static void main(String[] args) {
SentenceInventor wi = new SentenceInventor( 7L, 10000 );
for ( int i = 0; i < 3000; i++ ) {
//CHECKSTYLE:OFF
System.out.print( wi.nextPeriod() );
//CHECKSTYLE:ON
}
}
}
| {
"pile_set_name": "Github"
} |
<div class="layout-row min-size panel-contents compact-toolbar">
<div class="control-toolbar toolbar-padded separator">
<div class="toolbar-item" data-calculate-width>
<div class="toolbar" id="<?= $this->getId('toolbar-buttons') ?>">
<?= $this->makePartial("toolbar-buttons") ?>
</div>
</div>
<div class="relative toolbar-item loading-indicator-container size-input-text">
<input
type="text"
name="search"
value="<?= e($this->getSearchTerm()) ?>"
class="form-control icon search" autocomplete="off"
placeholder="<?= e(trans('rainlab.builder::lang.plugin.search')) ?>"
data-track-input
data-load-indicator
data-load-indicator-opaque
data-request="<?= $this->getEventHandler('onSearch') ?>"
/>
</div>
</div>
</div> | {
"pile_set_name": "Github"
} |
namespace glm
{
template<typename T, qualifier Q>
GLM_FUNC_QUALIFIER T dot(qua<T, Q> const& x, qua<T, Q> const& y)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'dot' accepts only floating-point inputs");
return detail::compute_dot<qua<T, Q>, T, detail::is_aligned<Q>::value>::call(x, y);
}
template<typename T, qualifier Q>
GLM_FUNC_QUALIFIER T length(qua<T, Q> const& q)
{
return glm::sqrt(dot(q, q));
}
template<typename T, qualifier Q>
GLM_FUNC_QUALIFIER qua<T, Q> normalize(qua<T, Q> const& q)
{
T len = length(q);
if(len <= static_cast<T>(0)) // Problem
return qua<T, Q>(static_cast<T>(1), static_cast<T>(0), static_cast<T>(0), static_cast<T>(0));
T oneOverLen = static_cast<T>(1) / len;
return qua<T, Q>(q.w * oneOverLen, q.x * oneOverLen, q.y * oneOverLen, q.z * oneOverLen);
}
template<typename T, qualifier Q>
GLM_FUNC_QUALIFIER qua<T, Q> cross(qua<T, Q> const& q1, qua<T, Q> const& q2)
{
return qua<T, Q>(
q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z,
q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y,
q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z,
q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x);
}
}//namespace glm
| {
"pile_set_name": "Github"
} |
// via OpenZeppelin
export default async promise => {
try {
await promise;
assert.fail('Expected revert not received');
} catch (error) {
const revertFound = error.message.search('revert') >= 0;
assert(
revertFound,
`Expected "revert", got ${error} instead`
);
}
};
| {
"pile_set_name": "Github"
} |
/**
*
* Problem Statement-
* [Forming a Magic Square](https://www.hackerrank.com/challenges/magic-square-forming/problem)
*
*/
package com.javaaid.hackerrank.solutions.generalprogramming.basicprogramming;
import java.util.Scanner;
/**
* @author Kanahaiya Gupta
*
*/
public class FormingAMagicSquare {
static int formingMagicSquare(int[][] s) {
int[][][] magicSquareCombinations={ {{4,9,2},{3,5,7},{8,1,6}},
{{8,3,4},{1,5,9},{6,7,2}},
{{6,1,8},{7,5,3},{2,9,4}},
{{2,7,6},{9,5,1},{4,3,8}},
{{2,9,4},{7,5,3},{6,1,8}},
{{8,1,6},{3,5,7},{4,9,2}},
{{6,7,2},{1,5,9},{8,3,4}},
{{4,3,8},{9,5,1},{2,7,6}}};
int minCost = Integer.MAX_VALUE;
for (int i = 0; i < magicSquareCombinations.length; i++) {
int modifyCost = 0;
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
modifyCost += Math.abs(s[j][k] - magicSquareCombinations[i][j][k]);
}
}
minCost = Math.min(modifyCost, minCost);
}
return minCost;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[][] s = new int[3][3];
for(int s_i = 0; s_i < 3; s_i++){
for(int s_j = 0; s_j < 3; s_j++){
s[s_i][s_j] = in.nextInt();
}
}
int result = formingMagicSquare(s);
System.out.println(result);
in.close();
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package rate provides a rate limiter.
package rate
import (
"fmt"
"math"
"sync"
"time"
)
// Limit defines the maximum frequency of some events.
// Limit is represented as number of events per second.
// A zero Limit allows no events.
type Limit float64
// Inf is the infinite rate limit; it allows all events (even if burst is zero).
const Inf = Limit(math.MaxFloat64)
// Every converts a minimum time interval between events to a Limit.
func Every(interval time.Duration) Limit {
if interval <= 0 {
return Inf
}
return 1 / Limit(interval.Seconds())
}
// A Limiter controls how frequently events are allowed to happen.
// It implements a "token bucket" of size b, initially full and refilled
// at rate r tokens per second.
// Informally, in any large enough time interval, the Limiter limits the
// rate to r tokens per second, with a maximum burst size of b events.
// As a special case, if r == Inf (the infinite rate), b is ignored.
// See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets.
//
// The zero value is a valid Limiter, but it will reject all events.
// Use NewLimiter to create non-zero Limiters.
//
// Limiter has three main methods, Allow, Reserve, and Wait.
// Most callers should use Wait.
//
// Each of the three methods consumes a single token.
// They differ in their behavior when no token is available.
// If no token is available, Allow returns false.
// If no token is available, Reserve returns a reservation for a future token
// and the amount of time the caller must wait before using it.
// If no token is available, Wait blocks until one can be obtained
// or its associated context.Context is canceled.
//
// The methods AllowN, ReserveN, and WaitN consume n tokens.
type Limiter struct {
limit Limit
burst int
mu sync.Mutex
tokens float64
// last is the last time the limiter's tokens field was updated
last time.Time
// lastEvent is the latest time of a rate-limited event (past or future)
lastEvent time.Time
}
// Limit returns the maximum overall event rate.
func (lim *Limiter) Limit() Limit {
lim.mu.Lock()
defer lim.mu.Unlock()
return lim.limit
}
// Burst returns the maximum burst size. Burst is the maximum number of tokens
// that can be consumed in a single call to Allow, Reserve, or Wait, so higher
// Burst values allow more events to happen at once.
// A zero Burst allows no events, unless limit == Inf.
func (lim *Limiter) Burst() int {
return lim.burst
}
// NewLimiter returns a new Limiter that allows events up to rate r and permits
// bursts of at most b tokens.
func NewLimiter(r Limit, b int) *Limiter {
return &Limiter{
limit: r,
burst: b,
}
}
// Allow is shorthand for AllowN(time.Now(), 1).
func (lim *Limiter) Allow() bool {
return lim.AllowN(time.Now(), 1)
}
// AllowN reports whether n events may happen at time now.
// Use this method if you intend to drop / skip events that exceed the rate limit.
// Otherwise use Reserve or Wait.
func (lim *Limiter) AllowN(now time.Time, n int) bool {
return lim.reserveN(now, n, 0).ok
}
// A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
// A Reservation may be canceled, which may enable the Limiter to permit additional events.
type Reservation struct {
ok bool
lim *Limiter
tokens int
timeToAct time.Time
// This is the Limit at reservation time, it can change later.
limit Limit
}
// OK returns whether the limiter can provide the requested number of tokens
// within the maximum wait time. If OK is false, Delay returns InfDuration, and
// Cancel does nothing.
func (r *Reservation) OK() bool {
return r.ok
}
// Delay is shorthand for DelayFrom(time.Now()).
func (r *Reservation) Delay() time.Duration {
return r.DelayFrom(time.Now())
}
// InfDuration is the duration returned by Delay when a Reservation is not OK.
const InfDuration = time.Duration(1<<63 - 1)
// DelayFrom returns the duration for which the reservation holder must wait
// before taking the reserved action. Zero duration means act immediately.
// InfDuration means the limiter cannot grant the tokens requested in this
// Reservation within the maximum wait time.
func (r *Reservation) DelayFrom(now time.Time) time.Duration {
if !r.ok {
return InfDuration
}
delay := r.timeToAct.Sub(now)
if delay < 0 {
return 0
}
return delay
}
// Cancel is shorthand for CancelAt(time.Now()).
func (r *Reservation) Cancel() {
r.CancelAt(time.Now())
return
}
// CancelAt indicates that the reservation holder will not perform the reserved action
// and reverses the effects of this Reservation on the rate limit as much as possible,
// considering that other reservations may have already been made.
func (r *Reservation) CancelAt(now time.Time) {
if !r.ok {
return
}
r.lim.mu.Lock()
defer r.lim.mu.Unlock()
if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {
return
}
// calculate tokens to restore
// The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved
// after r was obtained. These tokens should not be restored.
restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))
if restoreTokens <= 0 {
return
}
// advance time to now
now, _, tokens := r.lim.advance(now)
// calculate new number of tokens
tokens += restoreTokens
if burst := float64(r.lim.burst); tokens > burst {
tokens = burst
}
// update state
r.lim.last = now
r.lim.tokens = tokens
if r.timeToAct == r.lim.lastEvent {
prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))
if !prevEvent.Before(now) {
r.lim.lastEvent = prevEvent
}
}
return
}
// Reserve is shorthand for ReserveN(time.Now(), 1).
func (lim *Limiter) Reserve() *Reservation {
return lim.ReserveN(time.Now(), 1)
}
// ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
// The Limiter takes this Reservation into account when allowing future events.
// ReserveN returns false if n exceeds the Limiter's burst size.
// Usage example:
// r := lim.ReserveN(time.Now(), 1)
// if !r.OK() {
// // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
// return
// }
// time.Sleep(r.Delay())
// Act()
// Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
// If you need to respect a deadline or cancel the delay, use Wait instead.
// To drop or skip events exceeding rate limit, use Allow instead.
func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {
r := lim.reserveN(now, n, InfDuration)
return &r
}
// contextContext is a temporary(?) copy of the context.Context type
// to support both Go 1.6 using golang.org/x/net/context and Go 1.7+
// with the built-in context package. If people ever stop using Go 1.6
// we can remove this.
type contextContext interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}
// Wait is shorthand for WaitN(ctx, 1).
func (lim *Limiter) wait(ctx contextContext) (err error) {
return lim.WaitN(ctx, 1)
}
// WaitN blocks until lim permits n events to happen.
// It returns an error if n exceeds the Limiter's burst size, the Context is
// canceled, or the expected wait time exceeds the Context's Deadline.
// The burst limit is ignored if the rate limit is Inf.
func (lim *Limiter) waitN(ctx contextContext, n int) (err error) {
if n > lim.burst && lim.limit != Inf {
return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
}
// Check if ctx is already cancelled
select {
case <-ctx.Done():
return ctx.Err()
default:
}
// Determine wait limit
now := time.Now()
waitLimit := InfDuration
if deadline, ok := ctx.Deadline(); ok {
waitLimit = deadline.Sub(now)
}
// Reserve
r := lim.reserveN(now, n, waitLimit)
if !r.ok {
return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
}
// Wait if necessary
delay := r.DelayFrom(now)
if delay == 0 {
return nil
}
t := time.NewTimer(delay)
defer t.Stop()
select {
case <-t.C:
// We can proceed.
return nil
case <-ctx.Done():
// Context was canceled before we could proceed. Cancel the
// reservation, which may permit other events to proceed sooner.
r.Cancel()
return ctx.Err()
}
}
// SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
func (lim *Limiter) SetLimit(newLimit Limit) {
lim.SetLimitAt(time.Now(), newLimit)
}
// SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
// or underutilized by those which reserved (using Reserve or Wait) but did not yet act
// before SetLimitAt was called.
func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
lim.mu.Lock()
defer lim.mu.Unlock()
now, _, tokens := lim.advance(now)
lim.last = now
lim.tokens = tokens
lim.limit = newLimit
}
// reserveN is a helper method for AllowN, ReserveN, and WaitN.
// maxFutureReserve specifies the maximum reservation wait duration allowed.
// reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
lim.mu.Lock()
if lim.limit == Inf {
lim.mu.Unlock()
return Reservation{
ok: true,
lim: lim,
tokens: n,
timeToAct: now,
}
}
now, last, tokens := lim.advance(now)
// Calculate the remaining number of tokens resulting from the request.
tokens -= float64(n)
// Calculate the wait duration
var waitDuration time.Duration
if tokens < 0 {
waitDuration = lim.limit.durationFromTokens(-tokens)
}
// Decide result
ok := n <= lim.burst && waitDuration <= maxFutureReserve
// Prepare reservation
r := Reservation{
ok: ok,
lim: lim,
limit: lim.limit,
}
if ok {
r.tokens = n
r.timeToAct = now.Add(waitDuration)
}
// Update state
if ok {
lim.last = now
lim.tokens = tokens
lim.lastEvent = r.timeToAct
} else {
lim.last = last
}
lim.mu.Unlock()
return r
}
// advance calculates and returns an updated state for lim resulting from the passage of time.
// lim is not changed.
func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
last := lim.last
if now.Before(last) {
last = now
}
// Avoid making delta overflow below when last is very old.
maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
elapsed := now.Sub(last)
if elapsed > maxElapsed {
elapsed = maxElapsed
}
// Calculate the new number of tokens, due to time that passed.
delta := lim.limit.tokensFromDuration(elapsed)
tokens := lim.tokens + delta
if burst := float64(lim.burst); tokens > burst {
tokens = burst
}
return now, last, tokens
}
// durationFromTokens is a unit conversion function from the number of tokens to the duration
// of time it takes to accumulate them at a rate of limit tokens per second.
func (limit Limit) durationFromTokens(tokens float64) time.Duration {
seconds := tokens / float64(limit)
return time.Nanosecond * time.Duration(1e9*seconds)
}
// tokensFromDuration is a unit conversion function from a time duration to the number of tokens
// which could be accumulated during that duration at a rate of limit tokens per second.
func (limit Limit) tokensFromDuration(d time.Duration) float64 {
return d.Seconds() * float64(limit)
}
| {
"pile_set_name": "Github"
} |
using UnityEngine.UI;
namespace UnityEngine.Experimental.Rendering.UI
{
public class DebugUIHandlerIntField : DebugUIHandlerWidget
{
public Text nameLabel;
public Text valueLabel;
DebugUI.IntField m_Field;
internal override void SetWidget(DebugUI.Widget widget)
{
base.SetWidget(widget);
m_Field = CastWidget<DebugUI.IntField>();
nameLabel.text = m_Field.displayName;
UpdateValueLabel();
}
public override bool OnSelection(bool fromNext, DebugUIHandlerWidget previous)
{
nameLabel.color = colorSelected;
valueLabel.color = colorSelected;
return true;
}
public override void OnDeselection()
{
nameLabel.color = colorDefault;
valueLabel.color = colorDefault;
}
public override void OnIncrement(bool fast)
{
ChangeValue(fast, 1);
}
public override void OnDecrement(bool fast)
{
ChangeValue(fast, -1);
}
void ChangeValue(bool fast, int multiplier)
{
int value = m_Field.GetValue();
value += m_Field.incStep * (fast ? m_Field.intStepMult : 1) * multiplier;
m_Field.SetValue(value);
UpdateValueLabel();
}
void UpdateValueLabel()
{
if (valueLabel != null)
valueLabel.text = m_Field.GetValue().ToString("N0");
}
}
}
| {
"pile_set_name": "Github"
} |
<%@ Page Title="渠道包下载" Language="C#" MasterPageFile="~/Admin.Master" AutoEventWireup="true" CodeBehind="DownLoadIOSPackage.aspx.cs" Inherits="SDKPackage.Dropload.DownLoadIOSPackage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!-- Datatables -->
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">
<link href="/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet">
<link href="/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet">
<link href="/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet">
<link href="/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet">
<script type="text/javascript">
$(function () {
$("#MainContent_DropDownList1").change(function () {
<% this.ListView1.DataBind();%>
});
})
</script>
<style type="text/css">
.table > tbody > tr > td {
vertical-align: middle;
}
</style>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>IOS渠道包下载
</h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div class="row">
<div class="form-inline text-center">
<div class="form-group">
<label class="control-label">查看游戏</label>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="form-control" DataSourceID="SqlDataSourceGame" DataTextField="GameDisplayName" DataValueField="GameID" AutoPostBack="True"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSourceGame" runat="server" ConnectionString="<%$ ConnectionStrings:SdkPackageConnString %>" SelectCommand="select GameID,GameDisplayName from sdk_gameInfo"></asp:SqlDataSource>
</div>
<div class="form-group">
<label class="control-label">查看版本</label>
<asp:DropDownList ID="DropDownList2" runat="server" CssClass="form-control" DataSourceID="SqlDataSourceGameVersion" DataTextField="GameVersion" DataValueField="id" AutoPostBack="True"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSourceGameVersion" runat="server" ConnectionString="<%$ ConnectionStrings:SdkPackageConnString %>" SelectCommand=" select id=0,GameVersion='--全部--' union all select id,(GameVersion+'_'+PageageTable) as GameVersion from [sdk_UploadPackageInfo] where GameID=@GameID and GamePlatFrom='IOS'">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="GameID" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br />
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSourcePackage">
<EmptyDataTemplate>
<table runat="server">
<tr>
<td>演示平台不开放IOS打包功能(没有MAC系统的云主机)</td>
</tr>
</table>
</EmptyDataTemplate>
<ItemTemplate>
<tr>
<td>
<%#"<a href=\"/share/ios-output/ipa/"+Eval("GameID")+"/"+Eval("CreateTaskID")+"/"+Eval("PackageName")+"\">下载</a>" %>
</td>
<td>
<asp:Label ID="platformNameLabel" runat="server" Text='<%# Eval("platformName") %>' />
</td>
<td>
<asp:Label ID="createTaskLabel" runat="server" Text='<%# Eval("CreateTaskID") %>' />
</td>
<td>
<asp:Label ID="createDatetimeLabel" runat="server" Text='<%# Eval("CollectDatetime") %>' />
</td>
<td>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Compellation") %>' />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" class="table table-striped jambo_table">
<caption>游戏IPK包列表</caption>
<thead>
<tr>
<th>渠道包</th>
<th>渠道</th>
<th>批号</th>
<th>时间</th>
<th>创建人</th>
</tr>
</thead>
<tbody>
<tr id="itemPlaceholder" runat="server">
</tr>
</tbody>
</table>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSourcePackage" runat="server" ConnectionString="<%$ ConnectionStrings:SdkPackageConnString %>" SelectCommand="sdk_getPackageList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="GameID" Type="Int32" DefaultValue="0" />
<asp:ControlParameter ControlID="DropDownList2" Name="PackTaskID" Type="Int32" DefaultValue="0" />
<asp:Parameter Name="SystemName" Type="String" DefaultValue="IOS" />
<asp:Parameter Name="IsSign" Type="String" DefaultValue="0" />
<asp:Parameter Name="PackageReviewStatus" Type="Int32" DefaultValue="1" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<script src="/vendors/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
<script src="/vendors/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script>
<script src="/vendors/datatables.net-buttons/js/buttons.flash.min.js"></script>
<script src="/vendors/datatables.net-buttons/js/buttons.html5.min.js"></script>
<script src="/vendors/datatables.net-buttons/js/buttons.print.min.js"></script>
<script src="/vendors/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js"></script>
<script src="/vendors/datatables.net-keytable/js/dataTables.keyTable.min.js"></script>
<script src="/vendors/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
<script src="/vendors/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
<script src="/vendors/datatables.net-scroller/js/datatables.scroller.min.js"></script>
<script src="/vendors/jszip/dist/jszip.min.js"></script>
<script src="/vendors/pdfmake/build/pdfmake.min.js"></script>
<script src="/vendors/pdfmake/build/vfs_fonts.js"></script>
<!-- Datatables -->
<script>
$(document).ready(function() {
$('#itemPlaceholderContainer').dataTable({
"sPaginationType" : "full_numbers",
"oLanguage" : {
"sLengthMenu": "每页显示 _MENU_ 条记录",
"sZeroRecords": "抱歉, 没有找到",
"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
"sInfoEmpty": "没有数据",
"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
"sZeroRecords": "没有检索到数据",
"sSearch": "名称:",
"oPaginate": {
"sFirst": "首页",
"sPrevious": "前一页",
"sNext": "后一页",
"sLast": "尾页"
}
}
});
});
</script>
<!-- /Datatables -->
</asp:Content>
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 7083945a93bfc7d41ae15dca92061711
folderAsset: yes
timeCreated: 1455936191
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2011 Ryszard Wiśniewski <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package brut.androlib.res.util;
import java.io.IOException;
import org.xmlpull.v1.XmlSerializer;
/**
* @author Ryszard Wiśniewski <[email protected]>
*/
public interface ExtXmlSerializer extends XmlSerializer {
public ExtXmlSerializer newLine() throws IOException;
public void setDisabledAttrEscape(boolean disabled);
public static final String PROPERTY_SERIALIZER_INDENTATION = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation";
public static final String PROPERTY_SERIALIZER_LINE_SEPARATOR = "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator";
public static final String PROPERTY_DEFAULT_ENCODING = "DEFAULT_ENCODING";
}
| {
"pile_set_name": "Github"
} |
+++
Title = "Sponsor"
Type = "event"
Description = "Sponsor devopsdays lima 2020"
+++
We greatly value sponsors for this open event. If you are interested in sponsoring, please drop us an email at [{{< email_organizers >}}].
<hr>
devopsdays is a self-organizing conference for practitioners that depends on sponsorships. We do not have vendor booths, sell product presentations, or distribute attendee contact lists. Sponsors have the opportunity to have short elevator pitches during the program and will get recognition on the website and social media before, during and after the event. Sponsors are encouraged to represent themselves by actively participating and engaging with the attendees as peers. Any attendee also has the opportunity to demo products/projects as part of an open space session.
<p>
Gold sponsors get a full table and Silver sponsors a shared table where they can interact with those interested to come visit during breaks. All attendees are welcome to propose any subject they want during the open spaces, but this is a community-focused conference, so heavy marketing will probably work against you when trying to make a good impression on the attendees.
<p>
The best thing to do is send engineers to interact with the experts at devopsdays on their own terms.
<p>
<!--
<hr/>
<div style="width:590px">
<table border=1 cellspacing=1>
<tr>
<th><i>packages</i></th>
<th><center><b><u>Bronze<br />1000 usd</u></center></b></th>
<th><center><b><u>Silver<br />3000 usd</u></center></b></th>
<th><center><b><u>Gold<br />5000 usd</u></center></b></th>
<th></th>
</tr>
<tr><td>2 included tickets</td><td bgcolor="gold"> </td><td bgcolor="gold"> </td><td bgcolor="gold"> </td></tr>
<tr><td>logo on event website</td><td bgcolor="gold"> </td><td bgcolor="gold"> </td><td bgcolor="gold"> </td></tr>
<tr><td>logo on shared slide, rotating during breaks</td><td bgcolor="gold"> </td><td bgcolor="gold"> </td><td bgcolor="gold"> </td></tr>
<tr><td>logo on all email communication</td><td> </td><td bgcolor="gold"> </td><td bgcolor="gold"> </td></tr>
<tr><td>logo on its own slide, rotating during breaks</td><td> </td><td bgcolor="gold"> </td><td bgcolor="gold"> </td></tr>
<tr><td>1 minute pitch to full audience (including streaming audience)</td><td> </td><td> </td><td bgcolor="gold"> </td></tr></tr>
<tr><td>2 additional tickets (4 in total)</td><td> </td><td bgcolor="gold"> </td><td> </td></tr>
<tr><td>4 additional tickets (6 in total)</td><td> </td><td> </td><td bgcolor="gold"> </td></tr>
<tr><td>shared table for swag</td><td> </td><td bgcolor="gold"> </td><td> </td></tr>
<tr><td>booth/table space</td><td> </td><td> </td><td bgcolor="gold"> </td></tr>
</table>
<hr/>
There are also opportunities for exclusive special sponsorships. We'll have sponsors for various events with special privileges for the sponsors of these events. If you are interested in special sponsorships or have a creative idea about how you can support the event, send us an email.
<br/>
<br/>
<br>
<br>
<table border=1 cellspacing=1>
<tr>
<th><i>Sponsor FAQ</i></th>
<th><center><b>Answers to questions frequently asked by sponsors </center></b></th>
<th></th>
</tr>
<tr><td>What dates/times can we set up and tear down?</td><td></td></tr>
<tr><td>How do we ship to the venue?</td><td></td></tr>
<tr><td>How do we ship from the venue?</td><td></td></tr>
<tr><td>Whom should we send?</td><td></td></tr>
<tr><td>What should we expect regarding electricity? (how much, any fees, etc)</td><td></td></tr>
<tr><td>What should we expect regarding WiFi? (how much, any fees, etc)</td><td></td></tr>
<tr><td>How do we order additional A/V equipment?</td><td></td></tr>
<tr><td>Additional important details</td><td></td></tr>
</table>
</div>
-->
<hr/>
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 Mozilla
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
import React, { Component, PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import Style from '../../../../shared/style';
import Star from './star';
const CONTAINER_STYLE = Style.registerStyle({
flexShrink: 0,
});
class Ratings extends Component {
constructor(props) {
super(props);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
render() {
// Sanity checks
if (this.props.minRating >= this.props.maxRating ||
this.props.rating < this.props.minRating ||
this.props.rating > this.props.maxRating) {
return (<div />);
}
// Since the default for these values are 1 and 5, use the rating as the
// pure star value, otherwise normalize it as you would. This is a bit weird,
// since "1" is the lower default rating, so properly normalizing 3 of 5 stars,
// where 1 is the minimum, traditional normalization would give us 2.5 stars as
// the half way point. This is some magic to make things Close To Being Nice.
const starRating = this.props.minRating === 1 && this.props.maxRating === 5
? this.props.rating
: this.props.rating - (this.props.minRating / this.props.maxRating) - this.props.minRating;
// This doesn't take into account min rating, but I don't think there are
// common cases where the min isn't 0 or 1.
const title = `${starRating} of ${this.props.maxRating} rating`;
return (
<div className={CONTAINER_STYLE}>
{Array(5).fill().map((_, i) => {
const starNumber = i + 1;
if (starRating >= starNumber) {
return (
<Star title={title}
type="full"
key={i} />
);
}
if (starRating > (starNumber - 1)) {
return (
<Star title={title}
type="half"
key={i} />
);
}
return (
<Star title={title}
type="empty"
key={i} />
);
})}
</div>
);
}
}
Ratings.displayName = 'Ratings';
Ratings.propTypes = {
rating: PropTypes.number.isRequired,
maxRating: PropTypes.number.isRequired,
minRating: PropTypes.number.isRequired,
};
export default Ratings;
| {
"pile_set_name": "Github"
} |
// moment.js language configuration
// language : catalan (ca)
// author : Juan G. Hurtado : https://github.com/juanghurtado
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory(window.moment); // Browser global
}
}(function (moment) {
return moment.lang('ca', {
months : "Gener_Febrer_Març_Abril_Maig_Juny_Juliol_Agost_Setembre_Octubre_Novembre_Desembre".split("_"),
monthsShort : "Gen._Febr._Mar._Abr._Mai._Jun._Jul._Ag._Set._Oct._Nov._Des.".split("_"),
weekdays : "Diumenge_Dilluns_Dimarts_Dimecres_Dijous_Divendres_Dissabte".split("_"),
weekdaysShort : "Dg._Dl._Dt._Dc._Dj._Dv._Ds.".split("_"),
weekdaysMin : "Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),
longDateFormat : {
LT : "H:mm",
L : "DD/MM/YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY LT",
LLLL : "dddd D MMMM YYYY LT"
},
calendar : {
sameDay : function () {
return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
},
nextDay : function () {
return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
},
nextWeek : function () {
return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
},
lastDay : function () {
return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
},
lastWeek : function () {
return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
},
sameElse : 'L'
},
relativeTime : {
future : "en %s",
past : "fa %s",
s : "uns segons",
m : "un minut",
mm : "%d minuts",
h : "una hora",
hh : "%d hores",
d : "un dia",
dd : "%d dies",
M : "un mes",
MM : "%d mesos",
y : "un any",
yy : "%d anys"
},
ordinal : '%dº',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
}));
| {
"pile_set_name": "Github"
} |
-ifndef(_hadoopfs_types_included).
-define(_hadoopfs_types_included, yeah).
-record(thriftHandle, {id}).
-record(pathname, {pathname}).
-record(fileStatus, {path, length, isdir, block_replication, blocksize, modification_time, permission, owner, group}).
-record(blockLocation, {hosts, names, offset, length}).
-record(malformedInputException, {message}).
-record(thriftIOException, {message}).
-endif.
| {
"pile_set_name": "Github"
} |
[]
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2001-2011 Hartmut Kaiser
http://spirit.sourceforge.net/
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef BOOST_SPIRIT_INCLUDE_QI_CORE
#define BOOST_SPIRIT_INCLUDE_QI_CORE
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/qi/parser.hpp>
#include <boost/spirit/home/qi/parse.hpp>
#include <boost/spirit/home/qi/what.hpp>
#include <boost/spirit/home/qi/action.hpp>
#include <boost/spirit/home/qi/char.hpp>
#include <boost/spirit/home/qi/directive.hpp>
#include <boost/spirit/home/qi/nonterminal.hpp>
#include <boost/spirit/home/qi/numeric.hpp>
#include <boost/spirit/home/qi/operator.hpp>
#include <boost/spirit/home/qi/string.hpp>
#endif
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Framework\GraphQl\Schema\Type\Output\ElementMapper\Formatter;
use Magento\Framework\GraphQl\Config\Data\WrappedTypeProcessor;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Config\Element\TypeInterface;
use Magento\Framework\GraphQl\Config\ConfigElementInterface;
use Magento\Framework\GraphQl\Schema\Type\Input\InputMapper;
use Magento\Framework\GraphQl\Schema\Type\Output\ElementMapper\FormatterInterface;
use Magento\Framework\GraphQl\Schema\Type\Output\OutputMapper;
use Magento\Framework\GraphQl\Schema\Type\OutputTypeInterface;
use Magento\Framework\GraphQl\Schema\Type\ScalarTypes;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfoFactory;
use Magento\Framework\GraphQl\Query\Resolver\Factory as ResolverFactory;
/**
* Convert fields of the given 'type' config element to the objects compatible with GraphQL schema generator.
*/
class Fields implements FormatterInterface
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var OutputMapper
*/
private $outputMapper;
/**
* @var InputMapper
*/
private $inputMapper;
/**
* @var ScalarTypes
*/
private $scalarTypes;
/**
* @var WrappedTypeProcessor
*/
private $wrappedTypeProcessor;
/**
* @var ResolveInfoFactory
*/
private $resolveInfoFactory;
/**
* @var ResolverFactory
*/
private $resolverFactory;
/**
* @param ObjectManagerInterface $objectManager
* @param OutputMapper $outputMapper
* @param InputMapper $inputMapper
* @param ScalarTypes $scalarTypes
* @param WrappedTypeProcessor $wrappedTypeProcessor
* @param ResolveInfoFactory $resolveInfoFactory
* @param ResolverFactory $resolverFactory
*/
public function __construct(
ObjectManagerInterface $objectManager,
OutputMapper $outputMapper,
InputMapper $inputMapper,
ScalarTypes $scalarTypes,
WrappedTypeProcessor $wrappedTypeProcessor,
ResolveInfoFactory $resolveInfoFactory,
?ResolverFactory $resolverFactory = null
) {
$this->objectManager = $objectManager;
$this->outputMapper = $outputMapper;
$this->inputMapper = $inputMapper;
$this->scalarTypes = $scalarTypes;
$this->wrappedTypeProcessor = $wrappedTypeProcessor;
$this->resolveInfoFactory = $resolveInfoFactory;
$this->resolverFactory = $resolverFactory ?? $this->objectManager->get(ResolverFactory::class);
}
/**
* @inheritdoc
*/
public function format(ConfigElementInterface $configElement, OutputTypeInterface $outputType): array
{
$typeConfig = [];
if ($configElement instanceof TypeInterface) {
$typeConfig = [
'fields' => function () use ($configElement, $outputType) {
$fieldsConfig = [];
foreach ($configElement->getFields() as $field) {
$fieldsConfig[$field->getName()] = $this->getFieldConfig($configElement, $outputType, $field);
}
return $fieldsConfig;
}
];
}
return $typeConfig;
}
/**
* Get field's type object compatible with GraphQL schema generator.
*
* @param TypeInterface $typeConfigElement
* @param OutputTypeInterface $outputType
* @param Field $field
* @return TypeInterface
*/
private function getFieldType(TypeInterface $typeConfigElement, OutputTypeInterface $outputType, Field $field)
{
if ($this->scalarTypes->isScalarType($field->getTypeName())) {
$type = $this->wrappedTypeProcessor->processScalarWrappedType($field);
} else {
if ($typeConfigElement->getName() == $field->getTypeName()) {
$type = $outputType;
} else {
$type = $this->outputMapper->getOutputType($field->getTypeName());
}
$type = $this->wrappedTypeProcessor->processWrappedType($field, $type);
}
return $type;
}
/**
* Generate field config.
*
* @param TypeInterface $typeConfigElement
* @param OutputTypeInterface $outputType
* @param Field $field
* @return array
*/
private function getFieldConfig(
TypeInterface $typeConfigElement,
OutputTypeInterface $outputType,
Field $field
): array {
$type = $this->getFieldType($typeConfigElement, $outputType, $field);
$fieldConfig = [
'name' => $field->getName(),
'type' => $type,
];
if (!empty($field->getDescription())) {
$fieldConfig['description'] = $field->getDescription();
}
if (!empty($field->getDeprecated())) {
if (isset($field->getDeprecated()['reason'])) {
$fieldConfig['deprecationReason'] = $field->getDeprecated()['reason'];
}
}
if ($field->getResolver() != null) {
$resolver = $this->resolverFactory->createByClass($field->getResolver());
$fieldConfig['resolve'] =
function ($value, $args, $context, $info) use ($resolver, $field) {
$wrapperInfo = $this->resolveInfoFactory->create($info);
return $resolver->resolve($field, $context, $wrapperInfo, $value, $args);
};
}
return $this->formatArguments($field, $fieldConfig);
}
/**
* Format arguments configured for passed in field.
*
* @param Field $field
* @param array $config
* @return array
*/
private function formatArguments(Field $field, array $config) : array
{
foreach ($field->getArguments() as $argument) {
$inputType = $this->inputMapper->getRepresentation($argument);
$config['args'][$argument->getName()] = $inputType;
}
return $config;
}
}
| {
"pile_set_name": "Github"
} |
/***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
*
* Copyright (C) 2014 by Marcin Bukat
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
#include <getopt.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include "rkw.h"
#define VERSION "v0.1"
static void banner(void)
{
printf("RKWtool " VERSION " (C) Marcin Bukat 2014\n");
printf("This is free software; see the source for copying conditions. There is NO\n");
printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n");
}
static void usage(char *name)
{
banner();
printf("Usage: %s [-i] [-b] [-e] [-a] [-o prefix] file.rkw\n", name);
printf("-i\t\tprint info about RKW file\n");
printf("-b\t\textract nand bootloader images (s1.bin and s2.bin)\n");
printf("-e\t\textract firmware files stored in RKST section\n");
printf("-o prefix\twhen extracting firmware files put it there\n");
printf("-a\t\textract additional file(s) (usually Rock27Boot.bin)\n");
printf("-A\t\textract all data\n");
printf("file.rkw\tRKW file to be processed\n");
}
int main(int argc, char **argv)
{
int opt;
struct rkw_info_t *rkw_info = NULL;
char *prefix = NULL;
bool info = false;
bool extract = false;
bool bootloader = false;
bool addfile = false;
while ((opt = getopt(argc, argv, "iebo:aA")) != -1)
{
switch (opt)
{
case 'i':
info = true;
break;
case 'e':
extract = true;
break;
case 'b':
bootloader = true;
break;
case 'o':
prefix = optarg;
break;
case 'a':
addfile = true;
break;
case 'A':
extract = true;
bootloader = true;
addfile = true;
break;
default:
usage(argv[0]);
break;
}
}
if ((argc - optind) != 1 ||
(!info && !extract && ! bootloader && !addfile))
{
usage(argv[0]);
return -1;
}
banner();
rkw_info = rkw_slurp(argv[optind]);
if (rkw_info)
{
if (info)
{
rkrs_list_named_items(rkw_info);
rkst_list_named_items(rkw_info);
}
if (extract)
unpack_rkst(rkw_info, prefix);
if (bootloader)
unpack_bootloader(rkw_info, prefix);
if (addfile)
unpack_addfile(rkw_info, prefix);
rkw_free(rkw_info);
return 0;
}
return -1;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build arm,freebsd
package unix
import (
"syscall"
"unsafe"
)
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: int32(nsec)}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: int32(usec)}
}
func SetKevent(k *Kevent_t, fd, mode, flags int) {
k.Ident = uint32(fd)
k.Filter = int16(mode)
k.Flags = uint16(flags)
}
func (iov *Iovec) SetLen(length int) {
iov.Len = uint32(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
var writtenOut uint64 = 0
_, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0)
written = int(writtenOut)
if e1 != 0 {
err = e1
}
return
}
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
| {
"pile_set_name": "Github"
} |
package me.devsaki.hentoid.activities.bundles;
import android.os.Bundle;
import javax.annotation.Nonnull;
/**
* Helper class to transfer data from any Activity to {@link me.devsaki.hentoid.activities.PrefsActivity}
* through a Bundle
* <p>
* Use Builder class to set data; use Parser class to get data
*/
public class PrefsActivityBundle {
private static final String KEY_IS_VIEWER_PREFS = "isViewer";
private static final String KEY_IS_DOWNLOADER_PREFS = "isDownloader";
private PrefsActivityBundle() {
throw new UnsupportedOperationException();
}
public static final class Builder {
private final Bundle bundle = new Bundle();
public void setIsViewerPrefs(boolean isViewerPrefs) {
bundle.putBoolean(KEY_IS_VIEWER_PREFS, isViewerPrefs);
}
public void setIsDownloaderPrefs(boolean isDownloaderPrefs) {
bundle.putBoolean(KEY_IS_DOWNLOADER_PREFS, isDownloaderPrefs);
}
public Bundle getBundle() {
return bundle;
}
}
public static final class Parser {
private final Bundle bundle;
public Parser(@Nonnull Bundle bundle) {
this.bundle = bundle;
}
public boolean isViewerPrefs() {
return bundle.getBoolean(KEY_IS_VIEWER_PREFS, false);
}
public boolean isDownloaderPrefs() {
return bundle.getBoolean(KEY_IS_DOWNLOADER_PREFS, false);
}
}
}
| {
"pile_set_name": "Github"
} |
Alt-Svc: quic=":443"; ma=2592000; v="39,38,37,35"
Content-Length: 1561
Content-Type: text/html; charset=UTF-8
Date: Fri, 06 Oct 2017 07:12:39 GMT
P3p: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
Server: sffe
Set-Cookie: NID=113=sf8HB8MOccdtv3GuiD-oxHqAbOB5tEVpRQ2MHJRVMQ-c5BI7geDIJYGYRDUgxkxfqiEIlPxQQhbChpaMHeCvWjlcQ4FX-SPq3-koIA_KaMvzvJepU4FgNBrG02AHzOSc; expires=Sat, 07-Apr-2018 07:12:39 GMT; path=/; domain=.google.ie; HttpOnly
Status: 404
X-Content-Type-Options: nosniff
X-Xss-Protection: 1; mode=block
| {
"pile_set_name": "Github"
} |
/*
Copyright 2008-2018 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
* Clipperz is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public
License along with Clipperz. If not, see http://www.gnu.org/licenses/.
*/
//try { if (typeof(Clipperz.ByteArray) == 'undefined') { throw ""; }} catch (e) {
// throw "Clipperz.Crypto.ECC depends on Clipperz.ByteArray!";
//}
if (typeof(Clipperz.Crypto.ECC) == 'undefined') { Clipperz.Crypto.ECC = {}; }
if (typeof(Clipperz.Crypto.ECC.BinaryField) == 'undefined') { Clipperz.Crypto.ECC.BinaryField = {}; }
Clipperz.Crypto.ECC.BinaryField.FiniteField = function(args) {
args = args || {};
this._modulus = args.modulus;
return this;
}
Clipperz.Crypto.ECC.BinaryField.FiniteField.prototype = MochiKit.Base.update(null, {
'asString': function() {
return "Clipperz.Crypto.ECC.BinaryField.FiniteField (" + this.modulus().asString() + ")";
},
//-----------------------------------------------------------------------------
'modulus': function() {
return this._modulus;
},
//-----------------------------------------------------------------------------
'_module': function(aValue) {
var result;
var modulusComparison;
modulusComparison = Clipperz.Crypto.ECC.BinaryField.Value._compare(aValue, this.modulus()._value);
if (modulusComparison < 0) {
result = aValue;
} else if (modulusComparison == 0) {
result = [0];
} else {
var modulusBitSize;
var resultBitSize;
result = aValue;
modulusBitSize = this.modulus().bitSize();
resultBitSize = Clipperz.Crypto.ECC.BinaryField.Value._bitSize(result);
while (resultBitSize >= modulusBitSize) {
Clipperz.Crypto.ECC.BinaryField.Value._overwriteXor(result, Clipperz.Crypto.ECC.BinaryField.Value._shiftLeft(this.modulus()._value, resultBitSize - modulusBitSize));
resultBitSize = Clipperz.Crypto.ECC.BinaryField.Value._bitSize(result);
}
}
return result;
},
'module': function(aValue) {
return new Clipperz.Crypto.ECC.BinaryField.Value(this._module(aValue._value.slice(0)));
},
//-----------------------------------------------------------------------------
'_add': function(a, b) {
return Clipperz.Crypto.ECC.BinaryField.Value._xor(a, b);
},
'_overwriteAdd': function(a, b) {
Clipperz.Crypto.ECC.BinaryField.Value._overwriteXor(a, b);
},
'add': function(a, b) {
return new Clipperz.Crypto.ECC.BinaryField.Value(this._add(a._value, b._value));
},
//-----------------------------------------------------------------------------
'negate': function(aValue) {
return aValue.clone();
},
//-----------------------------------------------------------------------------
'_multiply': function(a, b) {
var result;
var valueToXor;
var i,c;
result = [0];
valueToXor = b;
c = Clipperz.Crypto.ECC.BinaryField.Value._bitSize(a);
for (i=0; i<c; i++) {
if (Clipperz.Crypto.ECC.BinaryField.Value._isBitSet(a, i) === true) {
Clipperz.Crypto.ECC.BinaryField.Value._overwriteXor(result, valueToXor);
}
valueToXor = Clipperz.Crypto.ECC.BinaryField.Value._overwriteShiftLeft(valueToXor, 1);
}
result = this._module(result);
return result;
},
'multiply': function(a, b) {
return new Clipperz.Crypto.ECC.BinaryField.Value(this._multiply(a._value, b._value));
},
//-----------------------------------------------------------------------------
'_fastMultiply': function(a, b) {
var result;
var B;
var i,c;
result = [0];
B = b.slice(0); // Is this array copy avoidable?
c = 32;
for (i=0; i<c; i++) {
var ii, cc;
cc = a.length;
for (ii=0; ii<cc; ii++) {
if (((a[ii] >>> i) & 0x01) == 1) {
Clipperz.Crypto.ECC.BinaryField.Value._overwriteXor(result, B, ii);
}
}
if (i < (c-1)) {
B = Clipperz.Crypto.ECC.BinaryField.Value._overwriteShiftLeft(B, 1);
}
}
result = this._module(result);
return result;
},
'fastMultiply': function(a, b) {
return new Clipperz.Crypto.ECC.BinaryField.Value(this._fastMultiply(a._value, b._value));
},
//-----------------------------------------------------------------------------
//
// Guide to Elliptic Curve Cryptography
// Darrel Hankerson, Alfred Menezes, Scott Vanstone
// - Pag: 49, Alorithm 2.34
//
//-----------------------------------------------------------------------------
'_square': function(aValue) {
var result;
var value;
var c,i;
var precomputedValues;
value = aValue;
result = new Array(value.length * 2);
precomputedValues = Clipperz.Crypto.ECC.BinaryField.FiniteField.squarePrecomputedBytes;
c = value.length;
for (i=0; i<c; i++) {
result[i*2] = precomputedValues[(value[i] & 0x000000ff)];
result[i*2] |= ((precomputedValues[(value[i] & 0x0000ff00) >>> 8]) << 16);
result[i*2 + 1] = precomputedValues[(value[i] & 0x00ff0000) >>> 16];
result[i*2 + 1] |= ((precomputedValues[(value[i] & 0xff000000) >>> 24]) << 16);
}
return this._module(result);
},
'square': function(aValue) {
return new Clipperz.Crypto.ECC.BinaryField.Value(this._square(aValue._value));
},
//-----------------------------------------------------------------------------
'_inverse': function(aValue) {
var result;
var b, c;
var u, v;
// b = Clipperz.Crypto.ECC.BinaryField.Value.I._value;
b = [1];
// c = Clipperz.Crypto.ECC.BinaryField.Value.O._value;
c = [0];
u = this._module(aValue);
v = this.modulus()._value.slice(0);
while (Clipperz.Crypto.ECC.BinaryField.Value._bitSize(u) > 1) {
var bitDifferenceSize;
bitDifferenceSize = Clipperz.Crypto.ECC.BinaryField.Value._bitSize(u) - Clipperz.Crypto.ECC.BinaryField.Value._bitSize(v);
if (bitDifferenceSize < 0) {
var swap;
swap = u;
u = v;
v = swap;
swap = c;
c = b;
b = swap;
bitDifferenceSize = -bitDifferenceSize;
}
u = this._add(u, Clipperz.Crypto.ECC.BinaryField.Value._shiftLeft(v, bitDifferenceSize));
b = this._add(b, Clipperz.Crypto.ECC.BinaryField.Value._shiftLeft(c, bitDifferenceSize));
// this._overwriteAdd(u, Clipperz.Crypto.ECC.BinaryField.Value._shiftLeft(v, bitDifferenceSize));
// this._overwriteAdd(b, Clipperz.Crypto.ECC.BinaryField.Value._shiftLeft(c, bitDifferenceSize));
}
result = this._module(b);
return result;
},
'inverse': function(aValue) {
return new Clipperz.Crypto.ECC.BinaryField.Value(this._inverse(aValue._value));
},
//-----------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
Clipperz.Crypto.ECC.BinaryField.FiniteField.squarePrecomputedBytes = [
0x0000, // 0 = 0000 0000 -> 0000 0000 0000 0000
0x0001, // 1 = 0000 0001 -> 0000 0000 0000 0001
0x0004, // 2 = 0000 0010 -> 0000 0000 0000 0100
0x0005, // 3 = 0000 0011 -> 0000 0000 0000 0101
0x0010, // 4 = 0000 0100 -> 0000 0000 0001 0000
0x0011, // 5 = 0000 0101 -> 0000 0000 0001 0001
0x0014, // 6 = 0000 0110 -> 0000 0000 0001 0100
0x0015, // 7 = 0000 0111 -> 0000 0000 0001 0101
0x0040, // 8 = 0000 1000 -> 0000 0000 0100 0000
0x0041, // 9 = 0000 1001 -> 0000 0000 0100 0001
0x0044, // 10 = 0000 1010 -> 0000 0000 0100 0100
0x0045, // 11 = 0000 1011 -> 0000 0000 0100 0101
0x0050, // 12 = 0000 1100 -> 0000 0000 0101 0000
0x0051, // 13 = 0000 1101 -> 0000 0000 0101 0001
0x0054, // 14 = 0000 1110 -> 0000 0000 0101 0100
0x0055, // 15 = 0000 1111 -> 0000 0000 0101 0101
0x0100, // 16 = 0001 0000 -> 0000 0001 0000 0000
0x0101, // 17 = 0001 0001 -> 0000 0001 0000 0001
0x0104, // 18 = 0001 0010 -> 0000 0001 0000 0100
0x0105, // 19 = 0001 0011 -> 0000 0001 0000 0101
0x0110, // 20 = 0001 0100 -> 0000 0001 0001 0000
0x0111, // 21 = 0001 0101 -> 0000 0001 0001 0001
0x0114, // 22 = 0001 0110 -> 0000 0001 0001 0100
0x0115, // 23 = 0001 0111 -> 0000 0001 0001 0101
0x0140, // 24 = 0001 1000 -> 0000 0001 0100 0000
0x0141, // 25 = 0001 1001 -> 0000 0001 0100 0001
0x0144, // 26 = 0001 1010 -> 0000 0001 0100 0100
0x0145, // 27 = 0001 1011 -> 0000 0001 0100 0101
0x0150, // 28 = 0001 1100 -> 0000 0001 0101 0000
0x0151, // 28 = 0001 1101 -> 0000 0001 0101 0001
0x0154, // 30 = 0001 1110 -> 0000 0001 0101 0100
0x0155, // 31 = 0001 1111 -> 0000 0001 0101 0101
0x0400, // 32 = 0010 0000 -> 0000 0100 0000 0000
0x0401, // 33 = 0010 0001 -> 0000 0100 0000 0001
0x0404, // 34 = 0010 0010 -> 0000 0100 0000 0100
0x0405, // 35 = 0010 0011 -> 0000 0100 0000 0101
0x0410, // 36 = 0010 0100 -> 0000 0100 0001 0000
0x0411, // 37 = 0010 0101 -> 0000 0100 0001 0001
0x0414, // 38 = 0010 0110 -> 0000 0100 0001 0100
0x0415, // 39 = 0010 0111 -> 0000 0100 0001 0101
0x0440, // 40 = 0010 1000 -> 0000 0100 0100 0000
0x0441, // 41 = 0010 1001 -> 0000 0100 0100 0001
0x0444, // 42 = 0010 1010 -> 0000 0100 0100 0100
0x0445, // 43 = 0010 1011 -> 0000 0100 0100 0101
0x0450, // 44 = 0010 1100 -> 0000 0100 0101 0000
0x0451, // 45 = 0010 1101 -> 0000 0100 0101 0001
0x0454, // 46 = 0010 1110 -> 0000 0100 0101 0100
0x0455, // 47 = 0010 1111 -> 0000 0100 0101 0101
0x0500, // 48 = 0011 0000 -> 0000 0101 0000 0000
0x0501, // 49 = 0011 0001 -> 0000 0101 0000 0001
0x0504, // 50 = 0011 0010 -> 0000 0101 0000 0100
0x0505, // 51 = 0011 0011 -> 0000 0101 0000 0101
0x0510, // 52 = 0011 0100 -> 0000 0101 0001 0000
0x0511, // 53 = 0011 0101 -> 0000 0101 0001 0001
0x0514, // 54 = 0011 0110 -> 0000 0101 0001 0100
0x0515, // 55 = 0011 0111 -> 0000 0101 0001 0101
0x0540, // 56 = 0011 1000 -> 0000 0101 0100 0000
0x0541, // 57 = 0011 1001 -> 0000 0101 0100 0001
0x0544, // 58 = 0011 1010 -> 0000 0101 0100 0100
0x0545, // 59 = 0011 1011 -> 0000 0101 0100 0101
0x0550, // 60 = 0011 1100 -> 0000 0101 0101 0000
0x0551, // 61 = 0011 1101 -> 0000 0101 0101 0001
0x0554, // 62 = 0011 1110 -> 0000 0101 0101 0100
0x0555, // 63 = 0011 1111 -> 0000 0101 0101 0101
0x1000, // 64 = 0100 0000 -> 0001 0000 0000 0000
0x1001, // 65 = 0100 0001 -> 0001 0000 0000 0001
0x1004, // 66 = 0100 0010 -> 0001 0000 0000 0100
0x1005, // 67 = 0100 0011 -> 0001 0000 0000 0101
0x1010, // 68 = 0100 0100 -> 0001 0000 0001 0000
0x1011, // 69 = 0100 0101 -> 0001 0000 0001 0001
0x1014, // 70 = 0100 0110 -> 0001 0000 0001 0100
0x1015, // 71 = 0100 0111 -> 0001 0000 0001 0101
0x1040, // 72 = 0100 1000 -> 0001 0000 0100 0000
0x1041, // 73 = 0100 1001 -> 0001 0000 0100 0001
0x1044, // 74 = 0100 1010 -> 0001 0000 0100 0100
0x1045, // 75 = 0100 1011 -> 0001 0000 0100 0101
0x1050, // 76 = 0100 1100 -> 0001 0000 0101 0000
0x1051, // 77 = 0100 1101 -> 0001 0000 0101 0001
0x1054, // 78 = 0100 1110 -> 0001 0000 0101 0100
0x1055, // 79 = 0100 1111 -> 0001 0000 0101 0101
0x1100, // 80 = 0101 0000 -> 0001 0001 0000 0000
0x1101, // 81 = 0101 0001 -> 0001 0001 0000 0001
0x1104, // 82 = 0101 0010 -> 0001 0001 0000 0100
0x1105, // 83 = 0101 0011 -> 0001 0001 0000 0101
0x1110, // 84 = 0101 0100 -> 0001 0001 0001 0000
0x1111, // 85 = 0101 0101 -> 0001 0001 0001 0001
0x1114, // 86 = 0101 0110 -> 0001 0001 0001 0100
0x1115, // 87 = 0101 0111 -> 0001 0001 0001 0101
0x1140, // 88 = 0101 1000 -> 0001 0001 0100 0000
0x1141, // 89 = 0101 1001 -> 0001 0001 0100 0001
0x1144, // 90 = 0101 1010 -> 0001 0001 0100 0100
0x1145, // 91 = 0101 1011 -> 0001 0001 0100 0101
0x1150, // 92 = 0101 1100 -> 0001 0001 0101 0000
0x1151, // 93 = 0101 1101 -> 0001 0001 0101 0001
0x1154, // 94 = 0101 1110 -> 0001 0001 0101 0100
0x1155, // 95 = 0101 1111 -> 0001 0001 0101 0101
0x1400, // 96 = 0110 0000 -> 0001 0100 0000 0000
0x1401, // 97 = 0110 0001 -> 0001 0100 0000 0001
0x1404, // 98 = 0110 0010 -> 0001 0100 0000 0100
0x1405, // 99 = 0110 0011 -> 0001 0100 0000 0101
0x1410, // 100 = 0110 0100 -> 0001 0100 0001 0000
0x1411, // 101 = 0110 0101 -> 0001 0100 0001 0001
0x1414, // 102 = 0110 0110 -> 0001 0100 0001 0100
0x1415, // 103 = 0110 0111 -> 0001 0100 0001 0101
0x1440, // 104 = 0110 1000 -> 0001 0100 0100 0000
0x1441, // 105 = 0110 1001 -> 0001 0100 0100 0001
0x1444, // 106 = 0110 1010 -> 0001 0100 0100 0100
0x1445, // 107 = 0110 1011 -> 0001 0100 0100 0101
0x1450, // 108 = 0110 1100 -> 0001 0100 0101 0000
0x1451, // 109 = 0110 1101 -> 0001 0100 0101 0001
0x1454, // 110 = 0110 1110 -> 0001 0100 0101 0100
0x1455, // 111 = 0110 1111 -> 0001 0100 0101 0101
0x1500, // 112 = 0111 0000 -> 0001 0101 0000 0000
0x1501, // 113 = 0111 0001 -> 0001 0101 0000 0001
0x1504, // 114 = 0111 0010 -> 0001 0101 0000 0100
0x1505, // 115 = 0111 0011 -> 0001 0101 0000 0101
0x1510, // 116 = 0111 0100 -> 0001 0101 0001 0000
0x1511, // 117 = 0111 0101 -> 0001 0101 0001 0001
0x1514, // 118 = 0111 0110 -> 0001 0101 0001 0100
0x1515, // 119 = 0111 0111 -> 0001 0101 0001 0101
0x1540, // 120 = 0111 1000 -> 0001 0101 0100 0000
0x1541, // 121 = 0111 1001 -> 0001 0101 0100 0001
0x1544, // 122 = 0111 1010 -> 0001 0101 0100 0100
0x1545, // 123 = 0111 1011 -> 0001 0101 0100 0101
0x1550, // 124 = 0111 1100 -> 0001 0101 0101 0000
0x1551, // 125 = 0111 1101 -> 0001 0101 0101 0001
0x1554, // 126 = 0111 1110 -> 0001 0101 0101 0100
0x1555, // 127 = 0111 1111 -> 0001 0101 0101 0101
0x4000, // 128 = 1000 0000 -> 0100 0000 0000 0000
0x4001, // 129 = 1000 0001 -> 0100 0000 0000 0001
0x4004, // 130 = 1000 0010 -> 0100 0000 0000 0100
0x4005, // 131 = 1000 0011 -> 0100 0000 0000 0101
0x4010, // 132 = 1000 0100 -> 0100 0000 0001 0000
0x4011, // 133 = 1000 0101 -> 0100 0000 0001 0001
0x4014, // 134 = 1000 0110 -> 0100 0000 0001 0100
0x4015, // 135 = 1000 0111 -> 0100 0000 0001 0101
0x4040, // 136 = 1000 1000 -> 0100 0000 0100 0000
0x4041, // 137 = 1000 1001 -> 0100 0000 0100 0001
0x4044, // 138 = 1000 1010 -> 0100 0000 0100 0100
0x4045, // 139 = 1000 1011 -> 0100 0000 0100 0101
0x4050, // 140 = 1000 1100 -> 0100 0000 0101 0000
0x4051, // 141 = 1000 1101 -> 0100 0000 0101 0001
0x4054, // 142 = 1000 1110 -> 0100 0000 0101 0100
0x4055, // 143 = 1000 1111 -> 0100 0000 0101 0101
0x4100, // 144 = 1001 0000 -> 0100 0001 0000 0000
0x4101, // 145 = 1001 0001 -> 0100 0001 0000 0001
0x4104, // 146 = 1001 0010 -> 0100 0001 0000 0100
0x4105, // 147 = 1001 0011 -> 0100 0001 0000 0101
0x4110, // 148 = 1001 0100 -> 0100 0001 0001 0000
0x4111, // 149 = 1001 0101 -> 0100 0001 0001 0001
0x4114, // 150 = 1001 0110 -> 0100 0001 0001 0100
0x4115, // 151 = 1001 0111 -> 0100 0001 0001 0101
0x4140, // 152 = 1001 1000 -> 0100 0001 0100 0000
0x4141, // 153 = 1001 1001 -> 0100 0001 0100 0001
0x4144, // 154 = 1001 1010 -> 0100 0001 0100 0100
0x4145, // 155 = 1001 1011 -> 0100 0001 0100 0101
0x4150, // 156 = 1001 1100 -> 0100 0001 0101 0000
0x4151, // 157 = 1001 1101 -> 0100 0001 0101 0001
0x4154, // 158 = 1001 1110 -> 0100 0001 0101 0100
0x4155, // 159 = 1001 1111 -> 0100 0001 0101 0101
0x4400, // 160 = 1010 0000 -> 0100 0100 0000 0000
0x4401, // 161 = 1010 0001 -> 0100 0100 0000 0001
0x4404, // 162 = 1010 0010 -> 0100 0100 0000 0100
0x4405, // 163 = 1010 0011 -> 0100 0100 0000 0101
0x4410, // 164 = 1010 0100 -> 0100 0100 0001 0000
0x4411, // 165 = 1010 0101 -> 0100 0100 0001 0001
0x4414, // 166 = 1010 0110 -> 0100 0100 0001 0100
0x4415, // 167 = 1010 0111 -> 0100 0100 0001 0101
0x4440, // 168 = 1010 1000 -> 0100 0100 0100 0000
0x4441, // 169 = 1010 1001 -> 0100 0100 0100 0001
0x4444, // 170 = 1010 1010 -> 0100 0100 0100 0100
0x4445, // 171 = 1010 1011 -> 0100 0100 0100 0101
0x4450, // 172 = 1010 1100 -> 0100 0100 0101 0000
0x4451, // 173 = 1010 1101 -> 0100 0100 0101 0001
0x4454, // 174 = 1010 1110 -> 0100 0100 0101 0100
0x4455, // 175 = 1010 1111 -> 0100 0100 0101 0101
0x4500, // 176 = 1011 0000 -> 0100 0101 0000 0000
0x4501, // 177 = 1011 0001 -> 0100 0101 0000 0001
0x4504, // 178 = 1011 0010 -> 0100 0101 0000 0100
0x4505, // 179 = 1011 0011 -> 0100 0101 0000 0101
0x4510, // 180 = 1011 0100 -> 0100 0101 0001 0000
0x4511, // 181 = 1011 0101 -> 0100 0101 0001 0001
0x4514, // 182 = 1011 0110 -> 0100 0101 0001 0100
0x4515, // 183 = 1011 0111 -> 0100 0101 0001 0101
0x4540, // 184 = 1011 1000 -> 0100 0101 0100 0000
0x4541, // 185 = 1011 1001 -> 0100 0101 0100 0001
0x4544, // 186 = 1011 1010 -> 0100 0101 0100 0100
0x4545, // 187 = 1011 1011 -> 0100 0101 0100 0101
0x4550, // 188 = 1011 1100 -> 0100 0101 0101 0000
0x4551, // 189 = 1011 1101 -> 0100 0101 0101 0001
0x4554, // 190 = 1011 1110 -> 0100 0101 0101 0100
0x4555, // 191 = 1011 1111 -> 0100 0101 0101 0101
0x5000, // 192 = 1100 0000 -> 0101 0000 0000 0000
0x5001, // 193 = 1100 0001 -> 0101 0000 0000 0001
0x5004, // 194 = 1100 0010 -> 0101 0000 0000 0100
0x5005, // 195 = 1100 0011 -> 0101 0000 0000 0101
0x5010, // 196 = 1100 0100 -> 0101 0000 0001 0000
0x5011, // 197 = 1100 0101 -> 0101 0000 0001 0001
0x5014, // 198 = 1100 0110 -> 0101 0000 0001 0100
0x5015, // 199 = 1100 0111 -> 0101 0000 0001 0101
0x5040, // 200 = 1100 1000 -> 0101 0000 0100 0000
0x5041, // 201 = 1100 1001 -> 0101 0000 0100 0001
0x5044, // 202 = 1100 1010 -> 0101 0000 0100 0100
0x5045, // 203 = 1100 1011 -> 0101 0000 0100 0101
0x5050, // 204 = 1100 1100 -> 0101 0000 0101 0000
0x5051, // 205 = 1100 1101 -> 0101 0000 0101 0001
0x5054, // 206 = 1100 1110 -> 0101 0000 0101 0100
0x5055, // 207 = 1100 1111 -> 0101 0000 0101 0101
0x5100, // 208 = 1101 0000 -> 0101 0001 0000 0000
0x5101, // 209 = 1101 0001 -> 0101 0001 0000 0001
0x5104, // 210 = 1101 0010 -> 0101 0001 0000 0100
0x5105, // 211 = 1101 0011 -> 0101 0001 0000 0101
0x5110, // 212 = 1101 0100 -> 0101 0001 0001 0000
0x5111, // 213 = 1101 0101 -> 0101 0001 0001 0001
0x5114, // 214 = 1101 0110 -> 0101 0001 0001 0100
0x5115, // 215 = 1101 0111 -> 0101 0001 0001 0101
0x5140, // 216 = 1101 1000 -> 0101 0001 0100 0000
0x5141, // 217 = 1101 1001 -> 0101 0001 0100 0001
0x5144, // 218 = 1101 1010 -> 0101 0001 0100 0100
0x5145, // 219 = 1101 1011 -> 0101 0001 0100 0101
0x5150, // 220 = 1101 1100 -> 0101 0001 0101 0000
0x5151, // 221 = 1101 1101 -> 0101 0001 0101 0001
0x5154, // 222 = 1101 1110 -> 0101 0001 0101 0100
0x5155, // 223 = 1101 1111 -> 0101 0001 0101 0101
0x5400, // 224 = 1110 0000 -> 0101 0100 0000 0000
0x5401, // 225 = 1110 0001 -> 0101 0100 0000 0001
0x5404, // 226 = 1110 0010 -> 0101 0100 0000 0100
0x5405, // 227 = 1110 0011 -> 0101 0100 0000 0101
0x5410, // 228 = 1110 0100 -> 0101 0100 0001 0000
0x5411, // 229 = 1110 0101 -> 0101 0100 0001 0001
0x5414, // 230 = 1110 0110 -> 0101 0100 0001 0100
0x5415, // 231 = 1110 0111 -> 0101 0100 0001 0101
0x5440, // 232 = 1110 1000 -> 0101 0100 0100 0000
0x5441, // 233 = 1110 1001 -> 0101 0100 0100 0001
0x5444, // 234 = 1110 1010 -> 0101 0100 0100 0100
0x5445, // 235 = 1110 1011 -> 0101 0100 0100 0101
0x5450, // 236 = 1110 1100 -> 0101 0100 0101 0000
0x5451, // 237 = 1110 1101 -> 0101 0100 0101 0001
0x5454, // 238 = 1110 1110 -> 0101 0100 0101 0100
0x5455, // 239 = 1110 1111 -> 0101 0100 0101 0101
0x5500, // 240 = 1111 0000 -> 0101 0101 0000 0000
0x5501, // 241 = 1111 0001 -> 0101 0101 0000 0001
0x5504, // 242 = 1111 0010 -> 0101 0101 0000 0100
0x5505, // 243 = 1111 0011 -> 0101 0101 0000 0101
0x5510, // 244 = 1111 0100 -> 0101 0101 0001 0000
0x5511, // 245 = 1111 0101 -> 0101 0101 0001 0001
0x5514, // 246 = 1111 0110 -> 0101 0101 0001 0100
0x5515, // 247 = 1111 0111 -> 0101 0101 0001 0101
0x5540, // 248 = 1111 1000 -> 0101 0101 0100 0000
0x5541, // 249 = 1111 1001 -> 0101 0101 0100 0001
0x5544, // 250 = 1111 1010 -> 0101 0101 0100 0100
0x5545, // 251 = 1111 1011 -> 0101 0101 0100 0101
0x5550, // 252 = 1111 1100 -> 0101 0101 0101 0000
0x5551, // 253 = 1111 1101 -> 0101 0101 0101 0001
0x5554, // 254 = 1111 1110 -> 0101 0101 0101 0100
0x5555 // 255 = 1111 1111 -> 0101 0101 0101 0101
]
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Azavea
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package geotrellis.raster.io.geotiff
import geotrellis.raster.{GridBounds, RasterExtent, TileLayout, PixelIsArea, Dimensions}
import geotrellis.raster.rasterize.Rasterizer
import geotrellis.vector.{Extent, Geometry}
import spire.syntax.cfor._
import scala.collection.mutable
/**
* This case class represents how the segments in a given [[GeoTiff]] are arranged.
*
* @param totalCols The total amount of cols in the GeoTiff
* @param totalRows The total amount of rows in the GeoTiff
* @param tileLayout The [[TileLayout]] of the GeoTiff
* @param storageMethod Storage method used for the segments (tiled or striped)
* @param interleaveMethod The interleave method used for segments (pixel or band)
*/
case class GeoTiffSegmentLayout(
totalCols: Int,
totalRows: Int,
tileLayout: TileLayout,
storageMethod: StorageMethod,
interleaveMethod: InterleaveMethod
) {
def isTiled: Boolean =
storageMethod match {
case _: Tiled => true
case _ => false
}
def isStriped: Boolean = !isTiled
def hasPixelInterleave: Boolean = interleaveMethod == PixelInterleave
/**
* Finds the corresponding segment index given GeoTiff col and row.
* If this is a band interleave geotiff, returns the segment index
* for the first band.
*
* @param col Pixel column in overall layout
* @param row Pixel row in overall layout
* @return The index of the segment in this layout
*/
private [geotiff] def getSegmentIndex(col: Int, row: Int): Int = {
val layoutCol = col / tileLayout.tileCols
val layoutRow = row / tileLayout.tileRows
(layoutRow * tileLayout.layoutCols) + layoutCol
}
/** Partition a list of pixel windows to localize required segment reads.
* Some segments may be required by more than one partition.
* Pixel windows outside of layout range will be filtered.
* Maximum partition size may be exceeded if any window size exceeds it.
* Windows will not be split to satisfy partition size limits.
*
* @param windows List of pixel windows from this layout
* @param maxPartitionSize Maximum pixel count for each partition
*/
def partitionWindowsBySegments(windows: Seq[GridBounds[Int]], maxPartitionSize: Long): Array[Array[GridBounds[Int]]] = {
val partition = mutable.ArrayBuilder.make[GridBounds[Int]]
partition.sizeHintBounded(128, windows)
var partitionSize: Long = 0l
var partitionCount: Long = 0l
val partitions = mutable.ArrayBuilder.make[Array[GridBounds[Int]]]
def finalizePartition() {
val res = partition.result
if (res.nonEmpty) partitions += res
partition.clear()
partitionSize = 0l
partitionCount = 0l
}
def addToPartition(window: GridBounds[Int]) {
partition += window
partitionSize += window.size
partitionCount += 1
}
val sourceBounds = GridBounds(0, 0, totalCols - 1, totalRows - 1)
// Because GeoTiff segment indecies are enumorated in row-major order
// sorting windows by the min index also provides spatial order
val sorted = windows
.filter(sourceBounds.intersects)
.map { window =>
window -> getSegmentIndex(col = window.colMin, row = window.rowMin)
}.sortBy(_._2)
for ((window, _) <- sorted) {
if ((partitionCount == 0) || (partitionSize + window.size) < maxPartitionSize) {
addToPartition(window)
} else {
finalizePartition()
addToPartition(window)
}
}
finalizePartition()
partitions.result
}
private def bestWindowSize(maxSize: Int, segment: Int): Int = {
var i: Int = 1
var result: Int = -1
// Search for the largest factor of segment that is > 1 and <=
// maxSize. If one cannot be found, give up and return maxSize.
while (i < math.sqrt(segment) && result == -1) {
if ((segment % i == 0) && ((segment/i) <= maxSize)) result = (segment/i)
i += 1
}
if (result == -1) maxSize; else result
}
def listWindows(maxSize: Int): Array[GridBounds[Int]] = {
val segCols = tileLayout.tileCols
val segRows = tileLayout.tileRows
val colSize: Int =
if (maxSize >= segCols * 2) {
math.floor(maxSize.toDouble / segCols).toInt * segCols
} else if (maxSize >= segCols) {
segCols
} else bestWindowSize(maxSize, segCols)
val rowSize: Int =
if (maxSize >= segRows * 2) {
math.floor(maxSize.toDouble / segRows).toInt * segRows
} else if (maxSize >= segRows) {
segRows
} else bestWindowSize(maxSize, segRows)
val windows = listWindows(colSize, rowSize)
windows
}
/** List all pixel windows that meet the given geometry */
def listWindows(maxSize: Int, extent: Extent, geometry: Geometry): Array[GridBounds[Int]] = {
val segCols = tileLayout.tileCols
val segRows = tileLayout.tileRows
val maxColSize: Int =
if (maxSize >= segCols * 2) {
math.floor(maxSize.toDouble / segCols).toInt * segCols
} else if (maxSize >= segCols) {
segCols
} else bestWindowSize(maxSize, segCols)
val maxRowSize: Int =
if (maxSize >= segRows) {
math.floor(maxSize.toDouble / segRows).toInt * segRows
} else if (maxSize >= segRows) {
segRows
} else bestWindowSize(maxSize, segRows)
val result = scala.collection.mutable.Set.empty[GridBounds[Int]]
val re = RasterExtent(extent, math.max(totalCols / maxColSize,1), math.max(totalRows / maxRowSize,1))
val options = Rasterizer.Options(includePartial=true, sampleType=PixelIsArea)
Rasterizer.foreachCellByGeometry(geometry, re, options)({ (col: Int, row: Int) =>
result +=
GridBounds(
col * maxColSize,
row * maxRowSize,
math.min((col + 1) * maxColSize - 1, totalCols - 1),
math.min((row + 1) * maxRowSize - 1, totalRows - 1)
)
})
result.toArray
}
/** List all pixel windows that cover a grid of given size */
def listWindows(cols: Int, rows: Int): Array[GridBounds[Int]] = {
val result = scala.collection.mutable.ArrayBuilder.make[GridBounds[Int]]
result.sizeHint((totalCols / cols) * (totalRows / rows))
cfor(0)(_ < totalCols, _ + cols) { col =>
cfor(0)(_ < totalRows, _ + rows) { row =>
result +=
GridBounds(
col,
row,
math.min(col + cols - 1, totalCols - 1),
math.min(row + rows - 1, totalRows - 1)
)
}
}
result.result
}
def bandSegmentCount: Int =
tileLayout.layoutCols * tileLayout.layoutRows
def getSegmentCoordinate(segmentIndex: Int): (Int, Int) =
(segmentIndex % tileLayout.layoutCols, segmentIndex / tileLayout.layoutCols)
/**
* Calculates pixel dimensions of a given segment in this layout.
* Segments are indexed in row-major order relative to the GeoTiff they comprise.
*
* @param segmentIndex: An Int that represents the given segment in the index
* @return Tuple representing segment (cols, rows)
*/
def getSegmentDimensions(segmentIndex: Int): Dimensions[Int] = {
val normalizedSegmentIndex = segmentIndex % bandSegmentCount
val layoutCol = normalizedSegmentIndex % tileLayout.layoutCols
val layoutRow = normalizedSegmentIndex / tileLayout.layoutCols
val cols =
if(layoutCol == tileLayout.layoutCols - 1) {
totalCols - ((tileLayout.layoutCols - 1) * tileLayout.tileCols)
} else {
tileLayout.tileCols
}
val rows =
if(layoutRow == tileLayout.layoutRows - 1) {
totalRows - ((tileLayout.layoutRows - 1) * tileLayout.tileRows)
} else {
tileLayout.tileRows
}
Dimensions(cols, rows)
}
private [geotrellis] def getGridBounds(segmentIndex: Int): GridBounds[Int] = {
val normalizedSegmentIndex = segmentIndex % bandSegmentCount
val Dimensions(segmentCols, segmentRows) = getSegmentDimensions(segmentIndex)
val (startCol, startRow) = {
val (layoutCol, layoutRow) = getSegmentCoordinate(normalizedSegmentIndex)
(layoutCol * tileLayout.tileCols, layoutRow * tileLayout.tileRows)
}
val endCol = (startCol + segmentCols) - 1
val endRow = (startRow + segmentRows) - 1
GridBounds(startCol, startRow, endCol, endRow)
}
}
trait GeoTiffSegmentLayoutTransform {
private [geotrellis] def segmentLayout: GeoTiffSegmentLayout
private lazy val GeoTiffSegmentLayout(totalCols, totalRows, tileLayout, isTiled, interleaveMethod) =
segmentLayout
/** Count of the bands in the GeoTiff */
def bandCount: Int
/** Calculate the number of segments per band */
private def bandSegmentCount: Int =
tileLayout.layoutCols * tileLayout.layoutRows
/**
* Calculates pixel dimensions of a given segment in this layout.
* Segments are indexed in row-major order relative to the GeoTiff they comprise.
*
* @param segmentIndex: An Int that represents the given segment in the index
* @return Tuple representing segment (cols, rows)
*/
def getSegmentDimensions(segmentIndex: Int): Dimensions[Int] = {
val normalizedSegmentIndex = segmentIndex % bandSegmentCount
val layoutCol = normalizedSegmentIndex % tileLayout.layoutCols
val layoutRow = normalizedSegmentIndex / tileLayout.layoutCols
val cols =
if(layoutCol == tileLayout.layoutCols - 1) {
totalCols - ((tileLayout.layoutCols - 1) * tileLayout.tileCols)
} else {
tileLayout.tileCols
}
val rows =
if(layoutRow == tileLayout.layoutRows - 1) {
totalRows - ((tileLayout.layoutRows - 1) * tileLayout.tileRows)
} else {
tileLayout.tileRows
}
Dimensions(cols, rows)
}
/**
* Calculates the total pixel count for given segment in this layout.
*
* @param segmentIndex: An Int that represents the given segment in the index
* @return Pixel size of the segment
*/
def getSegmentSize(segmentIndex: Int): Int = {
val Dimensions(cols, rows) = getSegmentDimensions(segmentIndex)
cols * rows
}
/**
* Finds the corresponding segment index given GeoTiff col and row.
* If this is a band interleave geotiff, returns the segment index
* for the first band.
*
* @param col Pixel column in overall layout
* @param row Pixel row in overall layout
* @return The index of the segment in this layout
*/
private [geotiff] def getSegmentIndex(col: Int, row: Int): Int =
segmentLayout.getSegmentIndex(col, row)
private [geotiff] def getSegmentTransform(segmentIndex: Int): SegmentTransform = {
val id = segmentIndex % bandSegmentCount
if (segmentLayout.isStriped)
StripedSegmentTransform(id, GeoTiffSegmentLayoutTransform(segmentLayout, bandCount))
else
TiledSegmentTransform(id, GeoTiffSegmentLayoutTransform(segmentLayout, bandCount))
}
def getSegmentCoordinate(segmentIndex: Int): (Int, Int) =
(segmentIndex % tileLayout.layoutCols, segmentIndex / tileLayout.layoutCols)
private [geotrellis] def getGridBounds(segmentIndex: Int): GridBounds[Int] = {
val normalizedSegmentIndex = segmentIndex % bandSegmentCount
val Dimensions(segmentCols, segmentRows) = getSegmentDimensions(segmentIndex)
val (startCol, startRow) = {
val (layoutCol, layoutRow) = getSegmentCoordinate(normalizedSegmentIndex)
(layoutCol * tileLayout.tileCols, layoutRow * tileLayout.tileRows)
}
val endCol = (startCol + segmentCols) - 1
val endRow = (startRow + segmentRows) - 1
GridBounds(startCol, startRow, endCol, endRow)
}
/** Returns all segment indices which intersect given pixel grid bounds */
private [geotrellis] def getIntersectingSegments(bounds: GridBounds[Int]): Array[Int] = {
val colMax = totalCols - 1
val rowMax = totalRows - 1
val intersects = !(colMax < bounds.colMin || bounds.colMax < 0) && !(rowMax < bounds.rowMin || bounds.rowMax < 0)
if (intersects) {
val tc = tileLayout.tileCols
val tr = tileLayout.tileRows
val colMin = math.max(0, bounds.colMin)
val rowMin = math.max(0, bounds.rowMin)
val colMax = math.min(totalCols - 1, bounds.colMax)
val rowMax = math.min(totalRows -1, bounds.rowMax)
val ab = mutable.ArrayBuilder.make[Int]
cfor(colMin / tc)(_ <= colMax / tc, _ + 1) { layoutCol =>
cfor(rowMin / tr)(_ <= rowMax / tr, _ + 1) { layoutRow =>
ab += (layoutRow * tileLayout.layoutCols) + layoutCol
}
}
ab.result
} else {
Array.empty[Int]
}
}
/** Partition a list of pixel windows to localize required segment reads.
* Some segments may be required by more than one partition.
* Pixel windows outside of layout range will be filtered.
* Maximum partition size may be exceeded if any window size exceeds it.
* Windows will not be split to satisfy partition size limits.
*
* @param windows List of pixel windows from this layout
* @param maxPartitionSize Maximum pixel count for each partition
*/
def partitionWindowsBySegments(windows: Seq[GridBounds[Int]], maxPartitionSize: Long): Array[Array[GridBounds[Int]]] =
segmentLayout.partitionWindowsBySegments(windows, maxPartitionSize)
/** Returns all segment indices which intersect given pixel grid bounds,
* and for a subset of bands.
* In a band interleave geotiff, generates the segment indices for the first band.
*
* @return An array of (band index, segment index) tuples.
*/
private [geotiff] def getIntersectingSegments(bounds: GridBounds[Int], bands: Array[Int]): Array[(Int, Int)] = {
val firstBandSegments = getIntersectingSegments(bounds)
bands.flatMap { band =>
val segmentOffset = bandSegmentCount * band
firstBandSegments.map { i => (band, i + segmentOffset) }
}
}
}
object GeoTiffSegmentLayoutTransform {
def apply(_segmentLayout: GeoTiffSegmentLayout, _bandCount: Int): GeoTiffSegmentLayoutTransform =
new GeoTiffSegmentLayoutTransform {
val segmentLayout = _segmentLayout
val bandCount = _bandCount
}
}
/**
* The companion object of [[GeoTiffSegmentLayout]]
*/
object GeoTiffSegmentLayout {
/**
* Given the totalCols, totalRows, storageMethod, and BandType of a GeoTiff,
* a new instance of GeoTiffSegmentLayout will be created
*
* @param totalCols: The total amount of cols in the GeoTiff
* @param totalRows: The total amount of rows in the GeoTiff
* @param storageMethod: The [[StorageMethod]] of the GeoTiff
* @param bandType: The [[BandType]] of the GeoTiff
*/
def apply(
totalCols: Int,
totalRows: Int,
storageMethod: StorageMethod,
interleaveMethod: InterleaveMethod,
bandType: BandType
): GeoTiffSegmentLayout = {
val tileLayout =
storageMethod match {
case Tiled(blockCols, blockRows) =>
val layoutCols = math.ceil(totalCols.toDouble / blockCols).toInt
val layoutRows = math.ceil(totalRows.toDouble / blockRows).toInt
TileLayout(layoutCols, layoutRows, blockCols, blockRows)
case s: Striped =>
val rowsPerStrip = math.min(s.rowsPerStrip(totalRows, bandType), totalRows).toInt
val layoutRows = math.ceil(totalRows.toDouble / rowsPerStrip).toInt
TileLayout(1, layoutRows, totalCols, rowsPerStrip)
}
GeoTiffSegmentLayout(totalCols, totalRows, tileLayout, storageMethod, interleaveMethod)
}
}
| {
"pile_set_name": "Github"
} |
<!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.7"/>
<title>Mooltipass: src/AES/gf256mul/gf256mul.h Source File</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/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="HaD_Mooltipass.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Mooltipass
</div>
<div id="projectbrief">Offline Password Keeper Developed on Hackaday</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.7 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</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)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Pages</a></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="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_b09f712dc5b362ce98c669b88a24f750.html">AES</a></li><li class="navelem"><a class="el" href="dir_5168b6abe292d0262f630f0bc43cae62.html">gf256mul</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">gf256mul.h</div> </div>
</div><!--header-->
<div class="contents">
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> <span class="comment">/* gf256mul.h */</span></div>
<div class="line"><a name="l00002"></a><span class="lineno"> 2</span> <span class="comment">/*</span></div>
<div class="line"><a name="l00003"></a><span class="lineno"> 3</span> <span class="comment"> This file is part of the AVR-Crypto-Lib.</span></div>
<div class="line"><a name="l00004"></a><span class="lineno"> 4</span> <span class="comment"> Copyright (C) 2008 Daniel Otte ([email protected])</span></div>
<div class="line"><a name="l00005"></a><span class="lineno"> 5</span> <span class="comment"></span></div>
<div class="line"><a name="l00006"></a><span class="lineno"> 6</span> <span class="comment"> This program is free software: you can redistribute it and/or modify</span></div>
<div class="line"><a name="l00007"></a><span class="lineno"> 7</span> <span class="comment"> it under the terms of the GNU General Public License as published by</span></div>
<div class="line"><a name="l00008"></a><span class="lineno"> 8</span> <span class="comment"> the Free Software Foundation, either version 3 of the License, or</span></div>
<div class="line"><a name="l00009"></a><span class="lineno"> 9</span> <span class="comment"> (at your option) any later version.</span></div>
<div class="line"><a name="l00010"></a><span class="lineno"> 10</span> <span class="comment"></span></div>
<div class="line"><a name="l00011"></a><span class="lineno"> 11</span> <span class="comment"> This program is distributed in the hope that it will be useful,</span></div>
<div class="line"><a name="l00012"></a><span class="lineno"> 12</span> <span class="comment"> but WITHOUT ANY WARRANTY; without even the implied warranty of</span></div>
<div class="line"><a name="l00013"></a><span class="lineno"> 13</span> <span class="comment"> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span></div>
<div class="line"><a name="l00014"></a><span class="lineno"> 14</span> <span class="comment"> GNU General Public License for more details.</span></div>
<div class="line"><a name="l00015"></a><span class="lineno"> 15</span> <span class="comment"></span></div>
<div class="line"><a name="l00016"></a><span class="lineno"> 16</span> <span class="comment"> You should have received a copy of the GNU General Public License</span></div>
<div class="line"><a name="l00017"></a><span class="lineno"> 17</span> <span class="comment"> along with this program. If not, see <http://www.gnu.org/licenses/>.</span></div>
<div class="line"><a name="l00018"></a><span class="lineno"> 18</span> <span class="comment">*/</span></div>
<div class="line"><a name="l00019"></a><span class="lineno"> 19</span> <span class="preprocessor">#ifndef GF256MUL_H_</span></div>
<div class="line"><a name="l00020"></a><span class="lineno"> 20</span> <span class="preprocessor">#define GF256MUL_H_</span></div>
<div class="line"><a name="l00021"></a><span class="lineno"> 21</span> </div>
<div class="line"><a name="l00032"></a><span class="lineno"> 32</span> <span class="preprocessor">#include <stdint.h></span></div>
<div class="line"><a name="l00033"></a><span class="lineno"> 33</span> </div>
<div class="line"><a name="l00034"></a><span class="lineno"> 34</span> uint8_t gf256mul(uint8_t a, uint8_t b, uint8_t reducer);</div>
<div class="line"><a name="l00035"></a><span class="lineno"> 35</span> </div>
<div class="line"><a name="l00036"></a><span class="lineno"> 36</span> <span class="preprocessor">#endif </span><span class="comment">/* GF256MUL_H_ */</span><span class="preprocessor"></span></div>
<div class="line"><a name="l00037"></a><span class="lineno"> 37</span> </div>
</div><!-- fragment --></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Mon Apr 21 2014 22:26:15 for Mooltipass by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.7
</small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
// Package jlexer contains a JSON lexer implementation.
//
// It is expected that it is mostly used with generated parser code, so the interface is tuned
// for a parser that knows what kind of data is expected.
package jlexer
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"unicode"
"unicode/utf16"
"unicode/utf8"
)
// tokenKind determines type of a token.
type tokenKind byte
const (
tokenUndef tokenKind = iota // No token.
tokenDelim // Delimiter: one of '{', '}', '[' or ']'.
tokenString // A string literal, e.g. "abc\u1234"
tokenNumber // Number literal, e.g. 1.5e5
tokenBool // Boolean literal: true or false.
tokenNull // null keyword.
)
// token describes a single token: type, position in the input and value.
type token struct {
kind tokenKind // Type of a token.
boolValue bool // Value if a boolean literal token.
byteValue []byte // Raw value of a token.
delimValue byte
}
// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice.
type Lexer struct {
Data []byte // Input data given to the lexer.
start int // Start of the current token.
pos int // Current unscanned position in the input stream.
token token // Last scanned token, if token.kind != tokenUndef.
firstElement bool // Whether current element is the first in array or an object.
wantSep byte // A comma or a colon character, which need to occur before a token.
UseMultipleErrors bool // If we want to use multiple errors.
fatalError error // Fatal error occurred during lexing. It is usually a syntax error.
multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors.
}
// FetchToken scans the input for the next token.
func (r *Lexer) FetchToken() {
r.token.kind = tokenUndef
r.start = r.pos
// Check if r.Data has r.pos element
// If it doesn't, it mean corrupted input data
if len(r.Data) < r.pos {
r.errParse("Unexpected end of data")
return
}
// Determine the type of a token by skipping whitespace and reading the
// first character.
for _, c := range r.Data[r.pos:] {
switch c {
case ':', ',':
if r.wantSep == c {
r.pos++
r.start++
r.wantSep = 0
} else {
r.errSyntax()
}
case ' ', '\t', '\r', '\n':
r.pos++
r.start++
case '"':
if r.wantSep != 0 {
r.errSyntax()
}
r.token.kind = tokenString
r.fetchString()
return
case '{', '[':
if r.wantSep != 0 {
r.errSyntax()
}
r.firstElement = true
r.token.kind = tokenDelim
r.token.delimValue = r.Data[r.pos]
r.pos++
return
case '}', ']':
if !r.firstElement && (r.wantSep != ',') {
r.errSyntax()
}
r.wantSep = 0
r.token.kind = tokenDelim
r.token.delimValue = r.Data[r.pos]
r.pos++
return
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-':
if r.wantSep != 0 {
r.errSyntax()
}
r.token.kind = tokenNumber
r.fetchNumber()
return
case 'n':
if r.wantSep != 0 {
r.errSyntax()
}
r.token.kind = tokenNull
r.fetchNull()
return
case 't':
if r.wantSep != 0 {
r.errSyntax()
}
r.token.kind = tokenBool
r.token.boolValue = true
r.fetchTrue()
return
case 'f':
if r.wantSep != 0 {
r.errSyntax()
}
r.token.kind = tokenBool
r.token.boolValue = false
r.fetchFalse()
return
default:
r.errSyntax()
return
}
}
r.fatalError = io.EOF
return
}
// isTokenEnd returns true if the char can follow a non-delimiter token
func isTokenEnd(c byte) bool {
return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':'
}
// fetchNull fetches and checks remaining bytes of null keyword.
func (r *Lexer) fetchNull() {
r.pos += 4
if r.pos > len(r.Data) ||
r.Data[r.pos-3] != 'u' ||
r.Data[r.pos-2] != 'l' ||
r.Data[r.pos-1] != 'l' ||
(r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) {
r.pos -= 4
r.errSyntax()
}
}
// fetchTrue fetches and checks remaining bytes of true keyword.
func (r *Lexer) fetchTrue() {
r.pos += 4
if r.pos > len(r.Data) ||
r.Data[r.pos-3] != 'r' ||
r.Data[r.pos-2] != 'u' ||
r.Data[r.pos-1] != 'e' ||
(r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) {
r.pos -= 4
r.errSyntax()
}
}
// fetchFalse fetches and checks remaining bytes of false keyword.
func (r *Lexer) fetchFalse() {
r.pos += 5
if r.pos > len(r.Data) ||
r.Data[r.pos-4] != 'a' ||
r.Data[r.pos-3] != 'l' ||
r.Data[r.pos-2] != 's' ||
r.Data[r.pos-1] != 'e' ||
(r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) {
r.pos -= 5
r.errSyntax()
}
}
// fetchNumber scans a number literal token.
func (r *Lexer) fetchNumber() {
hasE := false
afterE := false
hasDot := false
r.pos++
for i, c := range r.Data[r.pos:] {
switch {
case c >= '0' && c <= '9':
afterE = false
case c == '.' && !hasDot:
hasDot = true
case (c == 'e' || c == 'E') && !hasE:
hasE = true
hasDot = true
afterE = true
case (c == '+' || c == '-') && afterE:
afterE = false
default:
r.pos += i
if !isTokenEnd(c) {
r.errSyntax()
} else {
r.token.byteValue = r.Data[r.start:r.pos]
}
return
}
}
r.pos = len(r.Data)
r.token.byteValue = r.Data[r.start:]
}
// findStringLen tries to scan into the string literal for ending quote char to determine required size.
// The size will be exact if no escapes are present and may be inexact if there are escaped chars.
func findStringLen(data []byte) (hasEscapes bool, length int) {
delta := 0
for i := 0; i < len(data); i++ {
switch data[i] {
case '\\':
i++
delta++
if i < len(data) && data[i] == 'u' {
delta++
}
case '"':
return (delta > 0), (i - delta)
}
}
return false, len(data)
}
// getu4 decodes \uXXXX from the beginning of s, returning the hex value,
// or it returns -1.
func getu4(s []byte) rune {
if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
return -1
}
var val rune
for i := 2; i < len(s) && i < 6; i++ {
var v byte
c := s[i]
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
v = c - '0'
case 'a', 'b', 'c', 'd', 'e', 'f':
v = c - 'a' + 10
case 'A', 'B', 'C', 'D', 'E', 'F':
v = c - 'A' + 10
default:
return -1
}
val <<= 4
val |= rune(v)
}
return val
}
// processEscape processes a single escape sequence and returns number of bytes processed.
func (r *Lexer) processEscape(data []byte) (int, error) {
if len(data) < 2 {
return 0, fmt.Errorf("syntax error at %v", string(data))
}
c := data[1]
switch c {
case '"', '/', '\\':
r.token.byteValue = append(r.token.byteValue, c)
return 2, nil
case 'b':
r.token.byteValue = append(r.token.byteValue, '\b')
return 2, nil
case 'f':
r.token.byteValue = append(r.token.byteValue, '\f')
return 2, nil
case 'n':
r.token.byteValue = append(r.token.byteValue, '\n')
return 2, nil
case 'r':
r.token.byteValue = append(r.token.byteValue, '\r')
return 2, nil
case 't':
r.token.byteValue = append(r.token.byteValue, '\t')
return 2, nil
case 'u':
rr := getu4(data)
if rr < 0 {
return 0, errors.New("syntax error")
}
read := 6
if utf16.IsSurrogate(rr) {
rr1 := getu4(data[read:])
if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
read += 6
rr = dec
} else {
rr = unicode.ReplacementChar
}
}
var d [4]byte
s := utf8.EncodeRune(d[:], rr)
r.token.byteValue = append(r.token.byteValue, d[:s]...)
return read, nil
}
return 0, errors.New("syntax error")
}
// fetchString scans a string literal token.
func (r *Lexer) fetchString() {
r.pos++
data := r.Data[r.pos:]
hasEscapes, length := findStringLen(data)
if !hasEscapes {
r.token.byteValue = data[:length]
r.pos += length + 1
return
}
r.token.byteValue = make([]byte, 0, length)
p := 0
for i := 0; i < len(data); {
switch data[i] {
case '"':
r.pos += i + 1
r.token.byteValue = append(r.token.byteValue, data[p:i]...)
i++
return
case '\\':
r.token.byteValue = append(r.token.byteValue, data[p:i]...)
off, err := r.processEscape(data[i:])
if err != nil {
r.errParse(err.Error())
return
}
i += off
p = i
default:
i++
}
}
r.errParse("unterminated string literal")
}
// scanToken scans the next token if no token is currently available in the lexer.
func (r *Lexer) scanToken() {
if r.token.kind != tokenUndef || r.fatalError != nil {
return
}
r.FetchToken()
}
// consume resets the current token to allow scanning the next one.
func (r *Lexer) consume() {
r.token.kind = tokenUndef
r.token.delimValue = 0
}
// Ok returns true if no error (including io.EOF) was encountered during scanning.
func (r *Lexer) Ok() bool {
return r.fatalError == nil
}
const maxErrorContextLen = 13
func (r *Lexer) errParse(what string) {
if r.fatalError == nil {
var str string
if len(r.Data)-r.pos <= maxErrorContextLen {
str = string(r.Data)
} else {
str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..."
}
r.fatalError = &LexerError{
Reason: what,
Offset: r.pos,
Data: str,
}
}
}
func (r *Lexer) errSyntax() {
r.errParse("syntax error")
}
func (r *Lexer) errInvalidToken(expected string) {
if r.fatalError != nil {
return
}
if r.UseMultipleErrors {
r.pos = r.start
r.consume()
r.SkipRecursive()
switch expected {
case "[":
r.token.delimValue = ']'
r.token.kind = tokenDelim
case "{":
r.token.delimValue = '}'
r.token.kind = tokenDelim
}
r.addNonfatalError(&LexerError{
Reason: fmt.Sprintf("expected %s", expected),
Offset: r.start,
Data: string(r.Data[r.start:r.pos]),
})
return
}
var str string
if len(r.token.byteValue) <= maxErrorContextLen {
str = string(r.token.byteValue)
} else {
str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..."
}
r.fatalError = &LexerError{
Reason: fmt.Sprintf("expected %s", expected),
Offset: r.pos,
Data: str,
}
}
func (r *Lexer) GetPos() int {
return r.pos
}
// Delim consumes a token and verifies that it is the given delimiter.
func (r *Lexer) Delim(c byte) {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() || r.token.delimValue != c {
r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled.
r.errInvalidToken(string([]byte{c}))
} else {
r.consume()
}
}
// IsDelim returns true if there was no scanning error and next token is the given delimiter.
func (r *Lexer) IsDelim(c byte) bool {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
return !r.Ok() || r.token.delimValue == c
}
// Null verifies that the next token is null and consumes it.
func (r *Lexer) Null() {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() || r.token.kind != tokenNull {
r.errInvalidToken("null")
}
r.consume()
}
// IsNull returns true if the next token is a null keyword.
func (r *Lexer) IsNull() bool {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
return r.Ok() && r.token.kind == tokenNull
}
// Skip skips a single token.
func (r *Lexer) Skip() {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
r.consume()
}
// SkipRecursive skips next array or object completely, or just skips a single token if not
// an array/object.
//
// Note: no syntax validation is performed on the skipped data.
func (r *Lexer) SkipRecursive() {
r.scanToken()
var start, end byte
if r.token.delimValue == '{' {
start, end = '{', '}'
} else if r.token.delimValue == '[' {
start, end = '[', ']'
} else {
r.consume()
return
}
r.consume()
level := 1
inQuotes := false
wasEscape := false
for i, c := range r.Data[r.pos:] {
switch {
case c == start && !inQuotes:
level++
case c == end && !inQuotes:
level--
if level == 0 {
r.pos += i + 1
return
}
case c == '\\' && inQuotes:
wasEscape = !wasEscape
continue
case c == '"' && inQuotes:
inQuotes = wasEscape
case c == '"':
inQuotes = true
}
wasEscape = false
}
r.pos = len(r.Data)
r.fatalError = &LexerError{
Reason: "EOF reached while skipping array/object or token",
Offset: r.pos,
Data: string(r.Data[r.pos:]),
}
}
// Raw fetches the next item recursively as a data slice
func (r *Lexer) Raw() []byte {
r.SkipRecursive()
if !r.Ok() {
return nil
}
return r.Data[r.start:r.pos]
}
// IsStart returns whether the lexer is positioned at the start
// of an input string.
func (r *Lexer) IsStart() bool {
return r.pos == 0
}
// Consumed reads all remaining bytes from the input, publishing an error if
// there is anything but whitespace remaining.
func (r *Lexer) Consumed() {
if r.pos > len(r.Data) || !r.Ok() {
return
}
for _, c := range r.Data[r.pos:] {
if c != ' ' && c != '\t' && c != '\r' && c != '\n' {
r.AddError(&LexerError{
Reason: "invalid character '" + string(c) + "' after top-level value",
Offset: r.pos,
Data: string(r.Data[r.pos:]),
})
return
}
r.pos++
r.start++
}
}
func (r *Lexer) unsafeString() (string, []byte) {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() || r.token.kind != tokenString {
r.errInvalidToken("string")
return "", nil
}
bytes := r.token.byteValue
ret := bytesToStr(r.token.byteValue)
r.consume()
return ret, bytes
}
// UnsafeString returns the string value if the token is a string literal.
//
// Warning: returned string may point to the input buffer, so the string should not outlive
// the input buffer. Intended pattern of usage is as an argument to a switch statement.
func (r *Lexer) UnsafeString() string {
ret, _ := r.unsafeString()
return ret
}
// UnsafeBytes returns the byte slice if the token is a string literal.
func (r *Lexer) UnsafeBytes() []byte {
_, ret := r.unsafeString()
return ret
}
// String reads a string literal.
func (r *Lexer) String() string {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() || r.token.kind != tokenString {
r.errInvalidToken("string")
return ""
}
ret := string(r.token.byteValue)
r.consume()
return ret
}
// Bytes reads a string literal and base64 decodes it into a byte slice.
func (r *Lexer) Bytes() []byte {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() || r.token.kind != tokenString {
r.errInvalidToken("string")
return nil
}
ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue)))
len, err := base64.StdEncoding.Decode(ret, r.token.byteValue)
if err != nil {
r.fatalError = &LexerError{
Reason: err.Error(),
}
return nil
}
r.consume()
return ret[:len]
}
// Bool reads a true or false boolean keyword.
func (r *Lexer) Bool() bool {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() || r.token.kind != tokenBool {
r.errInvalidToken("bool")
return false
}
ret := r.token.boolValue
r.consume()
return ret
}
func (r *Lexer) number() string {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() || r.token.kind != tokenNumber {
r.errInvalidToken("number")
return ""
}
ret := bytesToStr(r.token.byteValue)
r.consume()
return ret
}
func (r *Lexer) Uint8() uint8 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 8)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return uint8(n)
}
func (r *Lexer) Uint16() uint16 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 16)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return uint16(n)
}
func (r *Lexer) Uint32() uint32 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 32)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return uint32(n)
}
func (r *Lexer) Uint64() uint64 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return n
}
func (r *Lexer) Uint() uint {
return uint(r.Uint64())
}
func (r *Lexer) Int8() int8 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 8)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return int8(n)
}
func (r *Lexer) Int16() int16 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 16)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return int16(n)
}
func (r *Lexer) Int32() int32 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 32)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return int32(n)
}
func (r *Lexer) Int64() int64 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return n
}
func (r *Lexer) Int() int {
return int(r.Int64())
}
func (r *Lexer) Uint8Str() uint8 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 8)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return uint8(n)
}
func (r *Lexer) Uint16Str() uint16 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 16)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return uint16(n)
}
func (r *Lexer) Uint32Str() uint32 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 32)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return uint32(n)
}
func (r *Lexer) Uint64Str() uint64 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return n
}
func (r *Lexer) UintStr() uint {
return uint(r.Uint64Str())
}
func (r *Lexer) UintptrStr() uintptr {
return uintptr(r.Uint64Str())
}
func (r *Lexer) Int8Str() int8 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 8)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return int8(n)
}
func (r *Lexer) Int16Str() int16 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 16)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return int16(n)
}
func (r *Lexer) Int32Str() int32 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 32)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return int32(n)
}
func (r *Lexer) Int64Str() int64 {
s, b := r.unsafeString()
if !r.Ok() {
return 0
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: string(b),
})
}
return n
}
func (r *Lexer) IntStr() int {
return int(r.Int64Str())
}
func (r *Lexer) Float32() float32 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseFloat(s, 32)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return float32(n)
}
func (r *Lexer) Float64() float64 {
s := r.number()
if !r.Ok() {
return 0
}
n, err := strconv.ParseFloat(s, 64)
if err != nil {
r.addNonfatalError(&LexerError{
Offset: r.start,
Reason: err.Error(),
Data: s,
})
}
return n
}
func (r *Lexer) Error() error {
return r.fatalError
}
func (r *Lexer) AddError(e error) {
if r.fatalError == nil {
r.fatalError = e
}
}
func (r *Lexer) AddNonFatalError(e error) {
r.addNonfatalError(&LexerError{
Offset: r.start,
Data: string(r.Data[r.start:r.pos]),
Reason: e.Error(),
})
}
func (r *Lexer) addNonfatalError(err *LexerError) {
if r.UseMultipleErrors {
// We don't want to add errors with the same offset.
if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset {
return
}
r.multipleErrors = append(r.multipleErrors, err)
return
}
r.fatalError = err
}
func (r *Lexer) GetNonFatalErrors() []*LexerError {
return r.multipleErrors
}
// JsonNumber fetches and json.Number from 'encoding/json' package.
// Both int, float or string, contains them are valid values
func (r *Lexer) JsonNumber() json.Number {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() {
r.errInvalidToken("json.Number")
return json.Number("0")
}
switch r.token.kind {
case tokenString:
return json.Number(r.String())
case tokenNumber:
return json.Number(r.Raw())
default:
r.errSyntax()
return json.Number("0")
}
}
// Interface fetches an interface{} analogous to the 'encoding/json' package.
func (r *Lexer) Interface() interface{} {
if r.token.kind == tokenUndef && r.Ok() {
r.FetchToken()
}
if !r.Ok() {
return nil
}
switch r.token.kind {
case tokenString:
return r.String()
case tokenNumber:
return r.Float64()
case tokenBool:
return r.Bool()
case tokenNull:
r.Null()
return nil
}
if r.token.delimValue == '{' {
r.consume()
ret := map[string]interface{}{}
for !r.IsDelim('}') {
key := r.String()
r.WantColon()
ret[key] = r.Interface()
r.WantComma()
}
r.Delim('}')
if r.Ok() {
return ret
} else {
return nil
}
} else if r.token.delimValue == '[' {
r.consume()
var ret []interface{}
for !r.IsDelim(']') {
ret = append(ret, r.Interface())
r.WantComma()
}
r.Delim(']')
if r.Ok() {
return ret
} else {
return nil
}
}
r.errSyntax()
return nil
}
// WantComma requires a comma to be present before fetching next token.
func (r *Lexer) WantComma() {
r.wantSep = ','
r.firstElement = false
}
// WantColon requires a colon to be present before fetching next token.
func (r *Lexer) WantColon() {
r.wantSep = ':'
r.firstElement = false
}
| {
"pile_set_name": "Github"
} |
[FTP a file to a server and send the URL to your friend. Supported automatic zipping before upload and encryption via SFTP and FTPS.]
[Default FTP server]
[Close dialog after upload is completed]
[ZIP support]
[Enter archive name manually]
[Compression level:]
[Upload File Manager]
[Completed:]
[Remaining:]
[File Manager]
[FTP File Manager]
[Deselect All]
[Delete from list]
[Delete from FTP]
[Enter file name]
[File exists]
[File with the same name already exists on the server.]
[How to proceed?]
[Copy URL]
[Automatically delete file after...]
[Delete from List]
[Do you really want to cancel all running jobs?]
[FTP Server 1]
[FTP Server 2]
[FTP Server 3]
[FTP Server 4]
[FTP Server 5]
[FTP Server %d]
[Zip and upload file(s)]
[Zip and upload folder]
[FTP File manager]
[Show FTPFile manager]
[Upload file]
[Zip and upload file]
[You have to fill FTP server setting before upload a file.]
[Error has occurred while trying to create a dialog!]
[FTP File - Select a folder]
[Folder not found!]
[The selected folder does not contain any files.\nFTP File sends files only from the selected folder, not from subfolders.]
[Error occurred when zipping the file(s).]
[%0.1f kB/s]
[%0.1f%% (%d kB/%d kB)]
[%s (%d kB/%d kB)]
[Do you really want to cancel this upload?]
[Status: %s\r\nFile: %s\r\nServer: %S]
[File exists - %s]
[Error occurred when opening local file.\nAborting file upload...]
[Error occurred when initializing libcurl.\nAborting file upload...]
[FTP error occurred.\n%s]
[Download link:]
[Do you really want to cancel running upload?]
[%s\r\nSpeed: %s\r\nCompleted: %s\r\nRemaining: %s]
[You have to fill and enable at least one FTP server in setting.]
[FTP+SSL (Explicit)]
[FTP+SSL (Implicit)]
[SFTP (Secure FTP over SSH)]
| {
"pile_set_name": "Github"
} |
//
// "$Id: Fl_Widget.H 5982 2007-11-19 16:21:48Z matt $"
//
// Widget header file for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2005 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
// USA.
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
#ifndef Fl_Widget_H
#define Fl_Widget_H
#include "Enumerations.H"
class Fl_Widget;
class Fl_Window;
class Fl_Group;
class Fl_Image;
typedef void (Fl_Callback )(Fl_Widget*, void*);
typedef Fl_Callback* Fl_Callback_p; // needed for BORLAND
typedef void (Fl_Callback0)(Fl_Widget*);
typedef void (Fl_Callback1)(Fl_Widget*, long);
struct FL_EXPORT Fl_Label {
const char* value;
Fl_Image* image;
Fl_Image* deimage;
uchar type;
uchar font;
uchar size;
unsigned color;
void draw(int,int,int,int, Fl_Align) const ;
void measure(int&, int&) const ;
};
class FL_EXPORT Fl_Widget {
friend class Fl_Group;
Fl_Group* parent_;
Fl_Callback* callback_;
void* user_data_;
short x_,y_,w_,h_;
Fl_Label label_;
int flags_;
unsigned color_;
unsigned color2_;
uchar type_;
uchar damage_;
uchar box_;
uchar align_;
uchar when_;
const char *tooltip_;
// unimplemented copy ctor and assignment operator
Fl_Widget(const Fl_Widget &);
Fl_Widget& operator=(const Fl_Widget &);
protected:
Fl_Widget(int,int,int,int,const char* =0);
void x(int v) {x_ = (short)v;}
void y(int v) {y_ = (short)v;}
void w(int v) {w_ = (short)v;}
void h(int v) {h_ = (short)v;}
int flags() const {return flags_;}
void set_flag(int c) {flags_ |= c;}
void clear_flag(int c) {flags_ &= ~c;}
enum {INACTIVE=1, INVISIBLE=2, OUTPUT=4, SHORTCUT_LABEL=64,
CHANGED=128, VISIBLE_FOCUS=512, COPIED_LABEL = 1024};
void draw_box() const;
void draw_box(Fl_Boxtype, Fl_Color) const;
void draw_box(Fl_Boxtype, int,int,int,int, Fl_Color) const;
void draw_focus() {draw_focus(box(),x(),y(),w(),h());}
void draw_focus(Fl_Boxtype, int,int,int,int) const;
void draw_label() const;
void draw_label(int, int, int, int) const;
public:
virtual ~Fl_Widget();
virtual void draw() = 0;
virtual int handle(int);
Fl_Group* parent() const {return parent_;}
void parent(Fl_Group* p) {parent_ = p;} // for hacks only, Fl_Group::add()
uchar type() const {return type_;}
void type(uchar t) {type_ = t;}
int x() const {return x_;}
int y() const {return y_;}
int w() const {return w_;}
int h() const {return h_;}
virtual void resize(int,int,int,int);
int damage_resize(int,int,int,int);
void position(int X,int Y) {resize(X,Y,w_,h_);}
void size(int W,int H) {resize(x_,y_,W,H);}
Fl_Align align() const {return (Fl_Align)align_;}
void align(uchar a) {align_ = a;}
Fl_Boxtype box() const {return (Fl_Boxtype)box_;}
void box(Fl_Boxtype a) {box_ = a;}
Fl_Color color() const {return (Fl_Color)color_;}
void color(unsigned a) {color_ = a;}
Fl_Color selection_color() const {return (Fl_Color)color2_;}
void selection_color(unsigned a) {color2_ = a;}
void color(unsigned a, unsigned b) {color_=a; color2_=b;}
const char* label() const {return label_.value;}
void label(const char* a);
void copy_label(const char* a);
void label(Fl_Labeltype a,const char* b) {label_.type = a; label_.value = b;}
Fl_Labeltype labeltype() const {return (Fl_Labeltype)label_.type;}
void labeltype(Fl_Labeltype a) {label_.type = a;}
Fl_Color labelcolor() const {return (Fl_Color)label_.color;}
void labelcolor(unsigned a) {label_.color=a;}
Fl_Font labelfont() const {return (Fl_Font)label_.font;}
void labelfont(uchar a) {label_.font=a;}
uchar labelsize() const {return label_.size;}
void labelsize(uchar a) {label_.size=a;}
Fl_Image* image() {return label_.image;}
void image(Fl_Image* a) {label_.image=a;}
void image(Fl_Image& a) {label_.image=&a;}
Fl_Image* deimage() {return label_.deimage;}
void deimage(Fl_Image* a) {label_.deimage=a;}
void deimage(Fl_Image& a) {label_.deimage=&a;}
const char *tooltip() const {return tooltip_;}
void tooltip(const char *t);
Fl_Callback_p callback() const {return callback_;}
void callback(Fl_Callback* c, void* p) {callback_=c; user_data_=p;}
void callback(Fl_Callback* c) {callback_=c;}
void callback(Fl_Callback0*c) {callback_=(Fl_Callback*)c;}
void callback(Fl_Callback1*c, long p=0) {callback_=(Fl_Callback*)c; user_data_=(void*)p;}
void* user_data() const {return user_data_;}
void user_data(void* v) {user_data_ = v;}
long argument() const {return (long)user_data_;}
void argument(long v) {user_data_ = (void*)v;}
Fl_When when() const {return (Fl_When)when_;}
void when(uchar i) {when_ = i;}
int visible() const {return !(flags_&INVISIBLE);}
int visible_r() const;
void show();
void hide();
void set_visible() {flags_ &= ~INVISIBLE;}
void clear_visible() {flags_ |= INVISIBLE;}
int active() const {return !(flags_&INACTIVE);}
int active_r() const;
void activate();
void deactivate();
int output() const {return (flags_&OUTPUT);}
void set_output() {flags_ |= OUTPUT;}
void clear_output() {flags_ &= ~OUTPUT;}
int takesevents() const {return !(flags_&(INACTIVE|INVISIBLE|OUTPUT));}
int changed() const {return flags_&CHANGED;}
void set_changed() {flags_ |= CHANGED;}
void clear_changed() {flags_ &= ~CHANGED;}
int take_focus();
void set_visible_focus() { flags_ |= VISIBLE_FOCUS; }
void clear_visible_focus() { flags_ &= ~VISIBLE_FOCUS; }
void visible_focus(int v) { if (v) set_visible_focus(); else clear_visible_focus(); }
int visible_focus() { return flags_ & VISIBLE_FOCUS; }
static void default_callback(Fl_Widget*, void*);
void do_callback() {callback_(this,user_data_); if (callback_ != default_callback) clear_changed();}
void do_callback(Fl_Widget* o,void* arg=0) {callback_(o,arg); if (callback_ != default_callback) clear_changed();}
void do_callback(Fl_Widget* o,long arg) {callback_(o,(void*)arg); if (callback_ != default_callback) clear_changed();}
int test_shortcut();
static char label_shortcut(const char *t);
static int test_shortcut(const char*);
int contains(const Fl_Widget*) const ;
int inside(const Fl_Widget* o) const {return o ? o->contains(this) : 0;}
void redraw();
void redraw_label();
uchar damage() const {return damage_;}
void clear_damage(uchar c = 0) {damage_ = c;}
void damage(uchar c);
void damage(uchar c,int,int,int,int);
void draw_label(int, int, int, int, Fl_Align) const;
void measure_label(int& xx, int& yy) {label_.measure(xx,yy);}
Fl_Window* window() const ;
// back compatability only:
Fl_Color color2() const {return (Fl_Color)color2_;}
void color2(unsigned a) {color2_ = a;}
};
// reserved type numbers (necessary for my cheapo RTTI) start here.
// grep the header files for "RESERVED_TYPE" to find the next available
// number.
#define FL_RESERVED_TYPE 100
#endif
//
// End of "$Id: Fl_Widget.H 5982 2007-11-19 16:21:48Z matt $".
//
| {
"pile_set_name": "Github"
} |
{
"culture": "tr",
"texts": {
"DisplayName:Abp.Mailing.DefaultFromAddress": "Varsayılan gönderici adresi",
"DisplayName:Abp.Mailing.DefaultFromDisplayName": "Varsayılan gönderici adı",
"DisplayName:Abp.Mailing.Smtp.Host": "Sunucu",
"DisplayName:Abp.Mailing.Smtp.Port": "Port",
"DisplayName:Abp.Mailing.Smtp.UserName": "Kullanıcı adı",
"DisplayName:Abp.Mailing.Smtp.Password": "Şifre",
"DisplayName:Abp.Mailing.Smtp.Domain": "Domain",
"DisplayName:Abp.Mailing.Smtp.EnableSsl": "SSL aktif",
"DisplayName:Abp.Mailing.Smtp.UseDefaultCredentials": "Varsayılan kimlik kullan",
"Description:Abp.Mailing.DefaultFromAddress": "Varsayılan gönderici adresi",
"Description:Abp.Mailing.DefaultFromDisplayName": "Varsayılan gönderici adı",
"Description:Abp.Mailing.Smtp.Host": "SMTP üzerinden e-posta göndermek için kullanılacak sunucunun IP adresi ya da adı.",
"Description:Abp.Mailing.Smtp.Port": "Sunucunun SMTP portu.",
"Description:Abp.Mailing.Smtp.UserName": "Varsayılan kimlik kullanılmaması durumunda kullanılacak kullanıcı adı.",
"Description:Abp.Mailing.Smtp.Password": "Varsayılan kimlik kullanılmaması durumunda kullanılacak şifre.",
"Description:Abp.Mailing.Smtp.Domain": "Kimlik bilgilerinin doğrulanacağı sunucu/domain.",
"Description:Abp.Mailing.Smtp.EnableSsl": "Email gönderiminde SSL kullanılıp kullanılmayacağı.",
"Description:Abp.Mailing.Smtp.UseDefaultCredentials": "Varsayılan kimlik bilgilerinin kullanılıp kullanılmayacağı.",
"TextTemplate:StandardEmailTemplates.Layout": "Varsayılan e-posta layout şablonu",
"TextTemplate:StandardEmailTemplates.Message": "Basit bir mesaj göndermek için e-posta şablonu"
}
} | {
"pile_set_name": "Github"
} |
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2012 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(* Evgeny Makarov, INRIA, 2007 *)
(************************************************************************)
Require Export NAddOrder.
Module NMulOrderProp (Import N : NAxiomsMiniSig').
Include NAddOrderProp N.
(** Theorems that are either not valid on Z or have different proofs
on N and Z *)
Theorem square_lt_mono : forall n m, n < m <-> n * n < m * m.
Proof.
intros n m; split; intro;
[apply square_lt_mono_nonneg | apply square_lt_simpl_nonneg];
try assumption; apply le_0_l.
Qed.
Theorem square_le_mono : forall n m, n <= m <-> n * n <= m * m.
Proof.
intros n m; split; intro;
[apply square_le_mono_nonneg | apply square_le_simpl_nonneg];
try assumption; apply le_0_l.
Qed.
Theorem mul_le_mono_l : forall n m p, n <= m -> p * n <= p * m.
Proof.
intros; apply mul_le_mono_nonneg_l. apply le_0_l. assumption.
Qed.
Theorem mul_le_mono_r : forall n m p, n <= m -> n * p <= m * p.
Proof.
intros; apply mul_le_mono_nonneg_r. apply le_0_l. assumption.
Qed.
Theorem mul_lt_mono : forall n m p q, n < m -> p < q -> n * p < m * q.
Proof.
intros; apply mul_lt_mono_nonneg; try assumption; apply le_0_l.
Qed.
Theorem mul_le_mono : forall n m p q, n <= m -> p <= q -> n * p <= m * q.
Proof.
intros; apply mul_le_mono_nonneg; try assumption; apply le_0_l.
Qed.
Theorem lt_0_mul' : forall n m, n * m > 0 <-> n > 0 /\ m > 0.
Proof.
intros n m; split; [intro H | intros [H1 H2]].
apply lt_0_mul in H. destruct H as [[H1 H2] | [H1 H2]]. now split.
false_hyp H1 nlt_0_r.
now apply mul_pos_pos.
Qed.
Notation mul_pos := lt_0_mul' (only parsing).
Theorem eq_mul_1 : forall n m, n * m == 1 <-> n == 1 /\ m == 1.
Proof.
intros n m.
split; [| intros [H1 H2]; now rewrite H1, H2, mul_1_l].
intro H; destruct (lt_trichotomy n 1) as [H1 | [H1 | H1]].
apply lt_1_r in H1. rewrite H1, mul_0_l in H. order'.
rewrite H1, mul_1_l in H; now split.
destruct (eq_0_gt_0_cases m) as [H2 | H2].
rewrite H2, mul_0_r in H. order'.
apply (mul_lt_mono_pos_r m) in H1; [| assumption]. rewrite mul_1_l in H1.
assert (H3 : 1 < n * m) by now apply (lt_1_l m).
rewrite H in H3; false_hyp H3 lt_irrefl.
Qed.
(** Alternative name : *)
Definition mul_eq_1 := eq_mul_1.
End NMulOrderProp.
| {
"pile_set_name": "Github"
} |
## 2017-09-10
#### python
* [allenai / allennlp](https://github.com/allenai/allennlp):An open-source NLP research library, built on PyTorch.
* [tensorflow / agents](https://github.com/tensorflow/agents):A library of RL tools
* [NVIDIA / DeepRecommender](https://github.com/NVIDIA/DeepRecommender):Deep learning for recommender systems
* [ansible / awx](https://github.com/ansible/awx):AWX Project
* [satwikkansal / wtfpython](https://github.com/satwikkansal/wtfpython):A collection of interesting, subtle, and tricky Python snippets.
* [khanrc / tf.gans-comparison](https://github.com/khanrc/tf.gans-comparison):Implementations of (theoretical) generative adversarial networks and comparison without cherry-picking
* [xoreaxeaxeax / sandsifter](https://github.com/xoreaxeaxeax/sandsifter):The x86 processor fuzzer
* [mazen160 / struts-pwn_CVE-2017-9805](https://github.com/mazen160/struts-pwn_CVE-2017-9805):An exploit for Apache Struts CVE-2017-9805
* [rg3 / youtube-dl](https://github.com/rg3/youtube-dl):Command-line program to download videos from YouTube.com and other video sites
* [vulnersCom / api](https://github.com/vulnersCom/api):Vulners Python API wrapper
* [pytorch / pytorch](https://github.com/pytorch/pytorch):Tensors and Dynamic neural networks in Python with strong GPU acceleration
* [tensorflow / models](https://github.com/tensorflow/models):Models built with TensorFlow
* [python / cpython](https://github.com/python/cpython):The Python programming language
* [vinta / awesome-python](https://github.com/vinta/awesome-python):A curated list of awesome Python frameworks, libraries, software and resources
* [fchollet / keras](https://github.com/fchollet/keras):Deep Learning library for Python. Runs on TensorFlow, Theano, or CNTK.
* [ofek / hatch](https://github.com/ofek/hatch):A modern project, package, and virtual env manager for Python
* [django / django](https://github.com/django/django):The Web framework for perfectionists with deadlines.
* [mli / gluon-tutorials-zh](https://github.com/mli/gluon-tutorials-zh):通过MXNet/Gluon来动手学习深度学习
* [LewisVo / Awesome-Linux-Software](https://github.com/LewisVo/Awesome-Linux-Software):🐧 A list of awesome applications, software, tools and other materials for Linux distros.
* [scikit-learn / scikit-learn](https://github.com/scikit-learn/scikit-learn):scikit-learn: machine learning in Python
* [ablator / ablator](https://github.com/ablator/ablator):Ablator is a Service that enables you to roll out functionalities at your own pace, and perform good A/B testing.
* [soimort / you-get](https://github.com/soimort/you-get):⏬ Dumb downloader that scrapes the web
* [XX-net / XX-Net](https://github.com/XX-net/XX-Net):a web proxy tool
* [donnemartin / system-design-primer](https://github.com/donnemartin/system-design-primer):Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.
* [studioml / studio](https://github.com/studioml/studio):Studio: Simplify and expedite model building process
#### swift
* [mergesort / FeedbackEffect](https://github.com/mergesort/FeedbackEffect):A μ library for playing sounds and providing haptic feedback with ease
* [inquisitiveSoft / XCAssetPacker](https://github.com/inquisitiveSoft/XCAssetPacker):A command line tool for converting a folder of images into an .xcasset package for Xcode
* [lhc70000 / iina](https://github.com/lhc70000/iina):The modern video player for macOS.
* [Kofktu / KUIPopOver](https://github.com/Kofktu/KUIPopOver):Easy to use PopOver in iOS
* [olucurious / Awesome-ARKit](https://github.com/olucurious/Awesome-ARKit):A curated list of awesome ARKit projects and resources. Feel free to contribute!
* [vsouza / awesome-ios](https://github.com/vsouza/awesome-ios):A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects
* [nmdias / FeedKit](https://github.com/nmdias/FeedKit):An RSS, Atom and JSON Feed parser written in Swift
* [smdls / C0](https://github.com/smdls/C0):2D Animation Tool for macOS.
* [insidegui / WWDC](https://github.com/insidegui/WWDC):The unofficial WWDC app for macOS
* [shadowsocks / ShadowsocksX-NG](https://github.com/shadowsocks/ShadowsocksX-NG):Next Generation of ShadowsocksX
* [raywenderlich / swift-algorithm-club](https://github.com/raywenderlich/swift-algorithm-club):Algorithms and data structures in Swift, with explanations!
* [dkhamsing / open-source-ios-apps](https://github.com/dkhamsing/open-source-ios-apps):📱 Collaborative List of Open-Source iOS Apps
* [ProjectDent / ARKit-CoreLocation](https://github.com/ProjectDent/ARKit-CoreLocation):Combines the high accuracy of AR with the scale of GPS data.
* [matteocrippa / awesome-swift](https://github.com/matteocrippa/awesome-swift):A collaborative list of awesome swift resources. Feel free to contribute!
* [CosmicMind / Material](https://github.com/CosmicMind/Material):A Material Design library for creating beautiful applications.
* [SwiftKickMobile / SwiftMessages](https://github.com/SwiftKickMobile/SwiftMessages):A very flexible message bar for iOS written in Swift.
* [ReactiveX / RxSwift](https://github.com/ReactiveX/RxSwift):Reactive Programming in Swift
* [RobertGummesson / BuildTimeAnalyzer-for-Xcode](https://github.com/RobertGummesson/BuildTimeAnalyzer-for-Xcode):Build Time Analyzer for Swift
* [February12 / YLImagePickerController](https://github.com/February12/YLImagePickerController):选择相册和拍照 支持多种裁剪
* [danielgindi / Charts](https://github.com/danielgindi/Charts):Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.
* [vapor / vapor](https://github.com/vapor/vapor):💧 A server-side Swift web framework.
* [patchthecode / JTAppleCalendar](https://github.com/patchthecode/JTAppleCalendar):The Unofficial Apple iOS Swift Calendar View. iOS calendar Library. iOS calendar Control. 100% Customizable
* [artemnovichkov / iOS-11-by-Examples](https://github.com/artemnovichkov/iOS-11-by-Examples):👨🏻💻 Examples of new iOS 11 APIs
* [sergdort / CleanArchitectureRxSwift](https://github.com/sergdort/CleanArchitectureRxSwift):Example of Clean Architecture of iOS app using RxSwift
* [CosmicMind / Samples](https://github.com/CosmicMind/Samples):Sample projects using Material, Graph, and Algorithm.
#### javascript
* [fastify / fastify](https://github.com/fastify/fastify):Fast and low overhead web framework, for Node.js
* [Okazari / Rythm.js](https://github.com/Okazari/Rythm.js):A javascript library that makes your page dance.
* [maierfelix / Iroh](https://github.com/maierfelix/Iroh):☕ Dynamic analysis tool - Intercept, record and analyze JavaScript at runtime
* [wojtekmaj / react-pdf](https://github.com/wojtekmaj/react-pdf):Easily display PDF files in your React application.
* [stasm / innerself](https://github.com/stasm/innerself):A tiny view + state management solution using innerHTML
* [vuejs / vue](https://github.com/vuejs/vue):A progressive, incrementally-adoptable JavaScript framework for building UI on the web.
* [GoogleChrome / puppeteer](https://github.com/GoogleChrome/puppeteer):Headless Chrome Node API
* [mikeal / r2](https://github.com/mikeal/r2):HTTP client. Spiritual successor to request.
* [toniov / gcal-cli](https://github.com/toniov/gcal-cli):Google Calendar command line tool for Node.js
* [facebook / react](https://github.com/facebook/react):A declarative, efficient, and flexible JavaScript library for building user interfaces.
* [ApoorvSaxena / lozad.js](https://github.com/ApoorvSaxena/lozad.js):Highly performant, light ~0.5kb and configurable lazy loader in pure JS with no dependencies for images, iframes and more
* [twbs / bootstrap](https://github.com/twbs/bootstrap):The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
* [idyll-lang / idyll](https://github.com/idyll-lang/idyll):Interactive Document Language
* [mzabriskie / axios](https://github.com/mzabriskie/axios):Promise based HTTP client for the browser and node.js
* [facebookincubator / create-react-app](https://github.com/facebookincubator/create-react-app):Create React apps with no build configuration.
* [evenchange4 / micro-medium-api](https://github.com/evenchange4/micro-medium-api):Microservice for fetching the latest posts of Medium with GraphQL.
* [resin-io / etcher](https://github.com/resin-io/etcher):Flash OS images to SD cards & USB drives, safely and easily.
* [airbnb / javascript](https://github.com/airbnb/javascript):JavaScript Style Guide
* [nitin42 / react-imgpro](https://github.com/nitin42/react-imgpro):📷 Image Processing Component for React
* [nodejs / node](https://github.com/nodejs/node):Node.js JavaScript runtime ✨ 🐢 🚀 ✨
* [hakimel / reveal.js](https://github.com/hakimel/reveal.js):The HTML Presentation Framework
* [callemall / material-ui](https://github.com/callemall/material-ui):React Components that Implement Google's Material Design.
* [denysdovhan / wtfjs](https://github.com/denysdovhan/wtfjs):A list of funny and tricky JavaScript examples
* [facebook / react-native](https://github.com/facebook/react-native):A framework for building native apps with React.
* [tanepiper / takeoff](https://github.com/tanepiper/takeoff):An opinionated rapid development environment using docker for convenience.
#### go
* [coyove / goflyway](https://github.com/coyove/goflyway):HTTP tunnel in Go
* [coreos / bbolt](https://github.com/coreos/bbolt):An embedded key/value database for Go.
* [golang / go](https://github.com/golang/go):The Go programming language
* [ethereum / go-ethereum](https://github.com/ethereum/go-ethereum):Official Go implementation of the Ethereum protocol
* [jirfag / go-queryset](https://github.com/jirfag/go-queryset):100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood.
* [gin-gonic / gin](https://github.com/gin-gonic/gin):Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
* [avelino / awesome-go](https://github.com/avelino/awesome-go):A curated list of awesome Go frameworks, libraries and software
* [kubernetes / kubernetes](https://github.com/kubernetes/kubernetes):Production-Grade Container Scheduling and Management
* [boltdb / bolt](https://github.com/boltdb/bolt):An embedded key/value database for Go.
* [fatedier / frp](https://github.com/fatedier/frp):A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet.
* [gogits / gogs](https://github.com/gogits/gogs):Gogs is a painless self-hosted Git service.
* [mholt / caddy](https://github.com/mholt/caddy):Fast, cross-platform HTTP/2 web server with automatic HTTPS
* [alexellis / derek](https://github.com/alexellis/derek):derek - a serverless 🤖 to manage PRs and issues
* [alexellis / faas](https://github.com/alexellis/faas):Functions as a Service (OpenFaaS) - a serverless framework for Docker & Kubernetes
* [astaxie / build-web-application-with-golang](https://github.com/astaxie/build-web-application-with-golang):A golang ebook intro how to build a web with golang
* [gopherchina / meetup](https://github.com/gopherchina/meetup):meetup in China
* [gohugoio / hugo](https://github.com/gohugoio/hugo):A Fast and Flexible Static Site Generator built with love in GoLang.
* [syncthing / syncthing](https://github.com/syncthing/syncthing):Open Source Continuous File Synchronization
* [grafana / grafana](https://github.com/grafana/grafana):The tool for beautiful monitoring and metric analytics & dashboards for Graphite, InfluxDB & Prometheus & More
* [moby / moby](https://github.com/moby/moby):Moby Project - a collaborative project for the container ecosystem to assemble container-based systems
* [esimov / stackblur-go](https://github.com/esimov/stackblur-go):A fast almost Gaussian Blur implementation in Go
* [cznic / file](https://github.com/cznic/file):Package file handles write-ahead logs and space management of os.File-like entities.
* [containous / traefik](https://github.com/containous/traefik):Træfik, a modern reverse proxy
* [minio / minio](https://github.com/minio/minio):Minio is an open source object storage server compatible with Amazon S3 APIs
* [go-kit / kit](https://github.com/go-kit/kit):A standard library for microservices.
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2014-10-21 Martin Siggel <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file is automatically created from tigl.h on 2017-05-26.
* If you experience any bugs please contact the authors
*/
package de.dlr.sc.tigl3;
import java.util.ArrayList;
public enum TiglSymmetryAxis {
TIGL_NO_SYMMETRY(0),
TIGL_X_Y_PLANE(1),
TIGL_X_Z_PLANE(2),
TIGL_Y_Z_PLANE(3);
private static ArrayList<TiglSymmetryAxis> codes = new ArrayList<>();
static {
codes.add(TIGL_NO_SYMMETRY);
codes.add(TIGL_X_Y_PLANE);
codes.add(TIGL_X_Z_PLANE);
codes.add(TIGL_Y_Z_PLANE);
}
private final int code;
private TiglSymmetryAxis(final int value) {
code = value;
}
public static TiglSymmetryAxis getEnum(final int value) {
return codes.get(Integer.valueOf(value));
}
public int getValue() {
return code;
}
}; | {
"pile_set_name": "Github"
} |
{
"_args": [
[
{
"name": "resolve",
"raw": "[email protected]",
"rawSpec": "1.1.7",
"scope": null,
"spec": "1.1.7",
"type": "version"
},
"/Volumes/case/workspace/silk/core-device/pub"
]
],
"_from": "[email protected]",
"_id": "[email protected]",
"_inCache": true,
"_installable": true,
"_location": "/resolve",
"_nodeVersion": "4.2.1",
"_npmUser": {
"email": "[email protected]",
"name": "substack"
},
"_npmVersion": "3.4.1",
"_phantomChildren": {},
"_requested": {
"name": "resolve",
"raw": "[email protected]",
"rawSpec": "1.1.7",
"scope": null,
"spec": "1.1.7",
"type": "version"
},
"_requiredBy": [
"/"
],
"_resolved": "http://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz",
"_shasum": "203114d82ad2c5ed9e8e0411b3932875e889e97b",
"_shrinkwrap": null,
"_spec": "[email protected]",
"_where": "/Volumes/case/workspace/silk/core-device/pub",
"author": {
"email": "[email protected]",
"name": "James Halliday",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/node-resolve/issues"
},
"dependencies": {},
"description": "resolve like require.resolve() on behalf of files asynchronously and synchronously",
"devDependencies": {
"tap": "0.4.13",
"tape": "^3.5.0"
},
"directories": {},
"dist": {
"shasum": "203114d82ad2c5ed9e8e0411b3932875e889e97b",
"tarball": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz"
},
"gitHead": "bb37f0d4400e4d7835375be4bd3ad1264bac3689",
"homepage": "https://github.com/substack/node-resolve#readme",
"keywords": [
"resolve",
"require",
"node",
"module"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"email": "[email protected]",
"name": "substack"
}
],
"name": "resolve",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/substack/node-resolve.git"
},
"scripts": {
"test": "tape test/*.js"
},
"version": "1.1.7"
}
| {
"pile_set_name": "Github"
} |
define("ace/mode/logiql_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var LogiQLHighlightRules = function() {
this.$rules = { start:
[ { token: 'comment.block',
regex: '/\\*',
push:
[ { token: 'comment.block', regex: '\\*/', next: 'pop' },
{ defaultToken: 'comment.block' } ]
},
{ token: 'comment.single',
regex: '//.*'
},
{ token: 'constant.numeric',
regex: '\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?[fd]?'
},
{ token: 'string',
regex: '"',
push:
[ { token: 'string', regex: '"', next: 'pop' },
{ defaultToken: 'string' } ]
},
{ token: 'constant.language',
regex: '\\b(true|false)\\b'
},
{ token: 'entity.name.type.logicblox',
regex: '`[a-zA-Z_:]+(\\d|\\a)*\\b'
},
{ token: 'keyword.start', regex: '->', comment: 'Constraint' },
{ token: 'keyword.start', regex: '-->', comment: 'Level 1 Constraint'},
{ token: 'keyword.start', regex: '<-', comment: 'Rule' },
{ token: 'keyword.start', regex: '<--', comment: 'Level 1 Rule' },
{ token: 'keyword.end', regex: '\\.', comment: 'Terminator' },
{ token: 'keyword.other', regex: '!', comment: 'Negation' },
{ token: 'keyword.other', regex: ',', comment: 'Conjunction' },
{ token: 'keyword.other', regex: ';', comment: 'Disjunction' },
{ token: 'keyword.operator', regex: '<=|>=|!=|<|>', comment: 'Equality'},
{ token: 'keyword.other', regex: '@', comment: 'Equality' },
{ token: 'keyword.operator', regex: '\\+|-|\\*|/', comment: 'Arithmetic operations'},
{ token: 'keyword', regex: '::', comment: 'Colon colon' },
{ token: 'support.function',
regex: '\\b(agg\\s*<<)',
push:
[ { include: '$self' },
{ token: 'support.function',
regex: '>>',
next: 'pop' } ]
},
{ token: 'storage.modifier',
regex: '\\b(lang:[\\w:]*)'
},
{ token: [ 'storage.type', 'text' ],
regex: '(export|sealed|clauses|block|alias|alias_all)(\\s*\\()(?=`)'
},
{ token: 'entity.name',
regex: '[a-zA-Z_][a-zA-Z_0-9:]*(@prev|@init|@final)?(?=(\\(|\\[))'
},
{ token: 'variable.parameter',
regex: '([a-zA-Z][a-zA-Z_0-9]*|_)\\s*(?=(,|\\.|<-|->|\\)|\\]|=))'
} ] }
this.normalizeRules();
};
oop.inherits(LogiQLHighlightRules, TextHighlightRules);
exports.LogiQLHighlightRules = LogiQLHighlightRules;
});
define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidgetRange = function(session, foldStyle, row) {
var range = this.indentationBlock(session, row);
if (range)
return range;
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1 || line[startLevel] != "#")
return;
var startColumn = line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
line = session.getLine(row);
var level = line.search(re);
if (level == -1)
continue;
if (line[level] != "#")
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
var indent = line.search(/\S/);
var next = session.getLine(row + 1);
var prev = session.getLine(row - 1);
var prevIndent = prev.search(/\S/);
var nextIndent = next.search(/\S/);
if (indent == -1) {
session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : "";
return "";
}
if (prevIndent == -1) {
if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") {
session.foldWidgets[row - 1] = "";
session.foldWidgets[row + 1] = "";
return "start";
}
} else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") {
if (session.getLine(row - 2).search(/\S/) == -1) {
session.foldWidgets[row - 1] = "start";
session.foldWidgets[row + 1] = "";
return "";
}
}
if (prevIndent!= -1 && prevIndent < indent)
session.foldWidgets[row - 1] = "start";
else
session.foldWidgets[row - 1] = "";
if (indent < nextIndent)
return "start";
else
return "";
};
}).call(FoldMode.prototype);
});
define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define("ace/mode/logiql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/logiql_highlight_rules","ace/mode/folding/coffee","ace/token_iterator","ace/range","ace/mode/behaviour/cstyle","ace/mode/matching_brace_outdent"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var LogiQLHighlightRules = require("./logiql_highlight_rules").LogiQLHighlightRules;
var FoldMode = require("./folding/coffee").FoldMode;
var TokenIterator = require("../token_iterator").TokenIterator;
var Range = require("../range").Range;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Mode = function() {
this.HighlightRules = LogiQLHighlightRules;
this.foldingRules = new FoldMode();
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (/comment|string/.test(endState))
return indent;
if (tokens.length && tokens[tokens.length - 1].type == "comment.single")
return indent;
var match = line.match();
if (/(-->|<--|<-|->|{)\s*$/.test(line))
indent += tab;
return indent;
};
this.checkOutdent = function(state, line, input) {
if (this.$outdent.checkOutdent(line, input))
return true;
if (input !== "\n" && input !== "\r\n")
return false;
if (!/^\s+/.test(line))
return false;
return true;
};
this.autoOutdent = function(state, doc, row) {
if (this.$outdent.autoOutdent(doc, row))
return;
var prevLine = doc.getLine(row);
var match = prevLine.match(/^\s+/);
var column = prevLine.lastIndexOf(".") + 1;
if (!match || !row || !column) return 0;
var line = doc.getLine(row + 1);
var startRange = this.getMatching(doc, {row: row, column: column});
if (!startRange || startRange.start.row == row) return 0;
column = match[0].length;
var indent = this.$getIndent(doc.getLine(startRange.start.row));
doc.replace(new Range(row + 1, 0, row + 1, column), indent);
};
this.getMatching = function(session, row, column) {
if (row == undefined)
row = session.selection.lead
if (typeof row == "object") {
column = row.column;
row = row.row;
}
var startToken = session.getTokenAt(row, column);
var KW_START = "keyword.start", KW_END = "keyword.end";
var tok;
if (!startToken)
return;
if (startToken.type == KW_START) {
var it = new TokenIterator(session, row, column);
it.step = it.stepForward;
} else if (startToken.type == KW_END) {
var it = new TokenIterator(session, row, column);
it.step = it.stepBackward;
} else
return;
while (tok = it.step()) {
if (tok.type == KW_START || tok.type == KW_END)
break;
}
if (!tok || tok.type == startToken.type)
return;
var col = it.getCurrentTokenColumn();
var row = it.getCurrentTokenRow();
return new Range(row, col, row, col + tok.value.length);
};
this.$id = "ace/mode/logiql";
}).call(Mode.prototype);
exports.Mode = Mode;
});
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/src.iml" filepath="$PROJECT_DIR$/.idea/src.iml" />
</modules>
</component>
</project> | {
"pile_set_name": "Github"
} |
/* $NetBSD: if_ieee1394.h,v 1.6 2005/12/10 23:21:38 elad Exp $ */
/*
* Copyright (c) 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Atsushi Onoe.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _NET_IF_IEEE1394_H_
#define _NET_IF_IEEE1394_H_
/* hardware address information for arp / nd */
struct ieee1394_hwaddr {
u_int8_t iha_uid[8]; /* node unique ID */
u_int8_t iha_maxrec; /* max_rec in the config ROM */
u_int8_t iha_speed; /* min of link/PHY speed */
u_int8_t iha_offset[6]; /* unicast FIFO address */
};
/*
* BPF wants to see one of these.
*/
struct ieee1394_bpfhdr {
uint8_t ibh_dhost[8];
uint8_t ibh_shost[8];
uint16_t ibh_type;
};
#ifdef _KERNEL
/* pseudo header */
struct ieee1394_header {
u_int8_t ih_uid[8]; /* dst/src uid */
u_int8_t ih_maxrec; /* dst maxrec for tx */
u_int8_t ih_speed; /* speed */
u_int8_t ih_offset[6]; /* dst offset */
};
/* unfragment encapsulation header */
struct ieee1394_unfraghdr {
u_int16_t iuh_ft; /* fragment type == 0 */
u_int16_t iuh_etype; /* ether_type */
};
/* fragmented encapsulation header */
struct ieee1394_fraghdr {
u_int16_t ifh_ft_size; /* fragment type, data size-1 */
u_int16_t ifh_etype_off; /* etype for first fragment */
/* offset for subseq frag */
u_int16_t ifh_dgl; /* datagram label */
u_int16_t ifh_reserved;
};
#define IEEE1394_FT_SUBSEQ 0x8000
#define IEEE1394_FT_MORE 0x4000
#define IEEE1394MTU 1500
#define IEEE1394_GASP_LEN 8 /* GASP header for Stream */
#define IEEE1394_ADDR_LEN 8
#define IEEE1394_CRC_LEN 4
struct ieee1394_reass_pkt {
LIST_ENTRY(ieee1394_reass_pkt) rp_next;
struct mbuf *rp_m;
u_int16_t rp_size;
u_int16_t rp_etype;
u_int16_t rp_off;
u_int16_t rp_dgl;
u_int16_t rp_len;
u_int16_t rp_ttl;
};
struct ieee1394_reassq {
LIST_ENTRY(ieee1394_reassq) rq_node;
LIST_HEAD(, ieee1394_reass_pkt) rq_pkt;
u_int32_t fr_id;
};
struct ieee1394com {
struct ifnet fc_if;
struct ieee1394_hwaddr ic_hwaddr;
u_int16_t ic_dgl;
LIST_HEAD(, ieee1394_reassq) ic_reassq;
};
const char *ieee1394_sprintf(const u_int8_t *);
void ieee1394_input(struct ifnet *, struct mbuf *, u_int16_t);
void ieee1394_ifattach(struct ifnet *, const struct ieee1394_hwaddr *);
void ieee1394_ifdetach(struct ifnet *);
int ieee1394_ioctl(struct ifnet *, u_long, caddr_t);
struct mbuf * ieee1394_fragment(struct ifnet *, struct mbuf *, int, u_int16_t);
void ieee1394_drain(struct ifnet *);
void ieee1394_watchdog(struct ifnet *);
#endif /* _KERNEL */
#endif /* !_NET_IF_IEEE1394_H_ */
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2000-2018 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.ui.declarative;
@SuppressWarnings("serial")
/**
* An exception that is used when reading or writing a design fails.
*
* @since 7.4
* @author Vaadin Ltd
*/
public class DesignException extends RuntimeException {
public DesignException() {
super();
}
public DesignException(String message) {
super(message);
}
public DesignException(String message, Throwable e) {
super(message, e);
}
}
| {
"pile_set_name": "Github"
} |
#region Copyright (C) 2007-2018 Team MediaPortal
/*
Copyright (C) 2007-2018 Team MediaPortal
http://www.team-mediaportal.com
This file is part of MediaPortal 2
MediaPortal 2 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MediaPortal 2 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MediaPortal 2. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace MediaPortal.Extensions.OnlineLibraries.Libraries.MusicBrainzV2.Data
{
//{
// "created": "2016-04-27T11:11:27.118Z",
// "count": 1,
// "offset": 0,
// "artists": [
// {
// "id": "8538e728-ca0b-4321-b7e5-cff6565dd4c0",
// "type": "Group",
// "score": "100",
// "name": "Depeche Mode",
// "sort-name": "Depeche Mode",
// "country": "GB",
// "area": {
// "id": "8a754a16-0027-3a29-b6d7-2b40ea0481ed",
// "name": "United Kingdom",
// "sort-name": "United Kingdom"
// },
// "begin-area": {
// "id": "9b4cb463-9777-46c3-8190-e1cb3da2749f",
// "name": "Basildon",
// "sort-name": "Basildon"
// },
// "life-span": {
// "begin": "1980",
// "ended": null
// },
// "aliases": [
// {
// "sort-name": "Depech Mode",
// "name": "Depech Mode",
// "locale": null,
// "type": null,
// "primary": null,
// "begin-date": null,
// "end-date": null
// },
// {
// "sort-name": "DM",
// "name": "DM",
// "locale": null,
// "type": "Search hint",
// "primary": null,
// "begin-date": null,
// "end-date": null
// }
// ],
// "tags": [
// {
// "count": 1,
// "name": "electronica"
// },
// {
// "count": 1,
// "name": "post punk"
// },
// {
// "count": 1,
// "name": "alternative dance"
// },
// {
// "count": 6,
// "name": "electronic"
// },
// {
// "count": 1,
// "name": "dark wave"
// },
// {
// "count": 0,
// "name": "britannique"
// },
// {
// "count": 4,
// "name": "british"
// },
// {
// "count": 1,
// "name": "english"
// },
// {
// "count": 2,
// "name": "uk"
// },
// {
// "count": 0,
// "name": "rock and indie"
// },
// {
// "count": 1,
// "name": "electronic rock"
// },
// {
// "count": 1,
// "name": "remix"
// },
// {
// "count": 0,
// "name": "synth pop"
// },
// {
// "count": 2,
// "name": "alternative rock"
// },
// {
// "count": 0,
// "name": "barrel"
// },
// {
// "count": 6,
// "name": "synthpop"
// },
// {
// "count": 4,
// "name": "new wave"
// },
// {
// "count": 1,
// "name": "new romantic"
// },
// {
// "count": 1,
// "name": "downtempo"
// },
// {
// "count": 0,
// "name": "producteur"
// },
// {
// "count": 0,
// "name": "producer"
// },
// {
// "count": 1,
// "name": "synth-pop"
// }
// ]
// }
// ]
//}
[DataContract]
public class TrackArtistResult
{
[DataMember(Name = "artists")]
public List<TrackArtist> Results { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
/**
* @author Richard Davey <[email protected]>
* @author Florian Mertens
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Get the shortest distance from a Line to the given Point.
*
* @function Phaser.Geom.Line.GetShortestDistance
* @since 3.16.0
*
* @generic {Phaser.Geom.Point} O - [out,$return]
*
* @param {Phaser.Geom.Line} line - The line to get the distance from.
* @param {(Phaser.Geom.Point|object)} point - The point to get the shortest distance to.
*
* @return {number} The shortest distance from the line to the point.
*/
var GetShortestDistance = function (line, point)
{
var x1 = line.x1;
var y1 = line.y1;
var x2 = line.x2;
var y2 = line.y2;
var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
if (L2 === 0)
{
return false;
}
var s = (((y1 - point.y) * (x2 - x1)) - ((x1 - point.x) * (y2 - y1))) / L2;
return Math.abs(s) * Math.sqrt(L2);
};
module.exports = GetShortestDistance;
| {
"pile_set_name": "Github"
} |
// Code generated by protoc-gen-validate. DO NOT EDIT.
// source: envoy/config/filter/http/fault/v2/fault.proto
package envoy_config_filter_http_fault_v2
import (
"bytes"
"errors"
"fmt"
"net"
"net/mail"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/golang/protobuf/ptypes"
)
// ensure the imports are used
var (
_ = bytes.MinRead
_ = errors.New("")
_ = fmt.Print
_ = utf8.UTFMax
_ = (*regexp.Regexp)(nil)
_ = (*strings.Reader)(nil)
_ = net.IPv4len
_ = time.Duration(0)
_ = (*url.URL)(nil)
_ = (*mail.Address)(nil)
_ = ptypes.DynamicAny{}
)
// define the regex for a UUID once up-front
var _fault_uuidPattern = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
// Validate checks the field values on FaultAbort with the rules defined in the
// proto definition for this message. If any rules are violated, an error is returned.
func (m *FaultAbort) Validate() error {
if m == nil {
return nil
}
if v, ok := interface{}(m.GetPercentage()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return FaultAbortValidationError{
field: "Percentage",
reason: "embedded message failed validation",
cause: err,
}
}
}
switch m.ErrorType.(type) {
case *FaultAbort_HttpStatus:
if val := m.GetHttpStatus(); val < 200 || val >= 600 {
return FaultAbortValidationError{
field: "HttpStatus",
reason: "value must be inside range [200, 600)",
}
}
default:
return FaultAbortValidationError{
field: "ErrorType",
reason: "value is required",
}
}
return nil
}
// FaultAbortValidationError is the validation error returned by
// FaultAbort.Validate if the designated constraints aren't met.
type FaultAbortValidationError struct {
field string
reason string
cause error
key bool
}
// Field function returns field value.
func (e FaultAbortValidationError) Field() string { return e.field }
// Reason function returns reason value.
func (e FaultAbortValidationError) Reason() string { return e.reason }
// Cause function returns cause value.
func (e FaultAbortValidationError) Cause() error { return e.cause }
// Key function returns key value.
func (e FaultAbortValidationError) Key() bool { return e.key }
// ErrorName returns error name.
func (e FaultAbortValidationError) ErrorName() string { return "FaultAbortValidationError" }
// Error satisfies the builtin error interface
func (e FaultAbortValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sFaultAbort.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = FaultAbortValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = FaultAbortValidationError{}
// Validate checks the field values on HTTPFault with the rules defined in the
// proto definition for this message. If any rules are violated, an error is returned.
func (m *HTTPFault) Validate() error {
if m == nil {
return nil
}
if v, ok := interface{}(m.GetDelay()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return HTTPFaultValidationError{
field: "Delay",
reason: "embedded message failed validation",
cause: err,
}
}
}
if v, ok := interface{}(m.GetAbort()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return HTTPFaultValidationError{
field: "Abort",
reason: "embedded message failed validation",
cause: err,
}
}
}
// no validation rules for UpstreamCluster
for idx, item := range m.GetHeaders() {
_, _ = idx, item
if v, ok := interface{}(item).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return HTTPFaultValidationError{
field: fmt.Sprintf("Headers[%v]", idx),
reason: "embedded message failed validation",
cause: err,
}
}
}
}
if v, ok := interface{}(m.GetMaxActiveFaults()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return HTTPFaultValidationError{
field: "MaxActiveFaults",
reason: "embedded message failed validation",
cause: err,
}
}
}
if v, ok := interface{}(m.GetResponseRateLimit()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return HTTPFaultValidationError{
field: "ResponseRateLimit",
reason: "embedded message failed validation",
cause: err,
}
}
}
// no validation rules for DelayPercentRuntime
// no validation rules for AbortPercentRuntime
// no validation rules for DelayDurationRuntime
// no validation rules for AbortHttpStatusRuntime
// no validation rules for MaxActiveFaultsRuntime
// no validation rules for ResponseRateLimitPercentRuntime
return nil
}
// HTTPFaultValidationError is the validation error returned by
// HTTPFault.Validate if the designated constraints aren't met.
type HTTPFaultValidationError struct {
field string
reason string
cause error
key bool
}
// Field function returns field value.
func (e HTTPFaultValidationError) Field() string { return e.field }
// Reason function returns reason value.
func (e HTTPFaultValidationError) Reason() string { return e.reason }
// Cause function returns cause value.
func (e HTTPFaultValidationError) Cause() error { return e.cause }
// Key function returns key value.
func (e HTTPFaultValidationError) Key() bool { return e.key }
// ErrorName returns error name.
func (e HTTPFaultValidationError) ErrorName() string { return "HTTPFaultValidationError" }
// Error satisfies the builtin error interface
func (e HTTPFaultValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sHTTPFault.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = HTTPFaultValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = HTTPFaultValidationError{}
| {
"pile_set_name": "Github"
} |
#include "genericicondelegate.h"
#include "pluginlist.h"
#include <QList>
#include <QPixmapCache>
GenericIconDelegate::GenericIconDelegate(QObject *parent, int role, int logicalIndex, int compactSize)
: IconDelegate(parent)
, m_Role(role)
, m_LogicalIndex(logicalIndex)
, m_CompactSize(compactSize)
, m_Compact(false)
{
}
void GenericIconDelegate::columnResized(int logicalIndex, int, int newSize)
{
if (logicalIndex == m_LogicalIndex) {
m_Compact = newSize < m_CompactSize;
}
}
QList<QString> GenericIconDelegate::getIcons(const QModelIndex &index) const
{
QList<QString> result;
if (index.isValid()) {
for (const QVariant &var : index.data(m_Role).toList()) {
if (!m_Compact || !var.toString().isEmpty()) {
result.append(var.toString());
}
}
}
return result;
}
size_t GenericIconDelegate::getNumIcons(const QModelIndex &index) const
{
return index.data(m_Role).toList().count();
}
| {
"pile_set_name": "Github"
} |
// Autogenerated by hob
window.cls || (window.cls = {});
cls.WindowManager || (cls.WindowManager = {});
cls.WindowManager["2.0"] || (cls.WindowManager["2.0"] = {});
cls.WindowManager["2.0"].WindowID = function(arr)
{
this.windowID = arr[0];
};
| {
"pile_set_name": "Github"
} |
<?php
/**
* OSSMail test class.
*
* @copyright YetiForce Sp. z o.o
* @license YetiForce Public License 3.0 (licenses/LicenseEN.txt or yetiforce.com)
* @author Tomasz Kur <[email protected]>
*/
namespace tests\Settings;
class OSSMail extends \Tests\Base
{
/**
* Testing change configuration for Roundcube.
*/
public function testChangeConfig()
{
$configurator = new \App\ConfigFile('module', 'OSSMail');
$configurator->set('des_key', 'YetiForce_Test');
$configurator->set('default_host', ['ssl://imap.gmail.com', 'ssl://imap.YT_Test.com']);
$configurator->create();
$this->assertSame('YetiForce_Test', \App\Config::module('OSSMail', 'des_key'));
$this->assertCount(0, array_diff(\App\Config::module('OSSMail', 'default_host'), ['ssl://imap.gmail.com', 'ssl://imap.YT_Test.com']));
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<plugin pluginId="Gallio.AutoCAD.UI"
recommendedInstallationPath="AutoCAD"
xmlns="http://www.gallio.org/">
<traits>
<name>AutoCAD Integration Plugin UI</name>
<version>3.2.0.0</version>
<description>AutoCAD plugin UI components.</description>
<icon>plugin://Gallio.AutoCAD/Resources/Gallio.AutoCAD.ico</icon>
</traits>
<dependencies>
<dependency pluginId="Gallio" />
<dependency pluginId="Gallio.UI" />
<dependency pluginId="Gallio.AutoCAD" />
</dependencies>
<files>
<file path="Gallio.AutoCAD.UI.plugin" />
<file path="Gallio.AutoCAD.UI.dll" />
</files>
<assemblies>
<assembly fullName="Gallio.AutoCAD.UI, Version=3.2.0.0, Culture=neutral, PublicKeyToken=eb9cfa67ee6ab36e"
codeBase="Gallio.AutoCAD.UI.dll"
qualifyPartialName="true" />
</assemblies>
<components>
<component componentId="Gallio.AutoCAD.UI.ControlPanel.RootPaneProvider"
serviceId="Gallio.UI.PreferencePaneProvider">
<traits>
<path>AutoCAD</path>
<icon>plugin://Gallio.AutoCAD/Resources/Gallio.AutoCAD.ico</icon>
</traits>
</component>
<component componentId="Gallio.AutoCAD.UI.ControlPanel.StartupPreferencePaneProvider"
serviceId="Gallio.UI.PreferencePaneProvider"
componentType="Gallio.AutoCAD.UI.ControlPanel.StartupPreferencePaneProvider, Gallio.AutoCAD.UI">
<traits>
<path>AutoCAD/Startup</path>
<icon>plugin://Gallio.AutoCAD/Resources/Gallio.AutoCAD.ico</icon>
<scope>User</scope>
</traits>
</component>
</components>
</plugin> | {
"pile_set_name": "Github"
} |
/*
Copyright Rene Rivera 2013
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_PREDEF_OTHER_H
#define BOOST_PREDEF_OTHER_H
#include <boost/predef/other/endian.h>
/*#include <boost/predef/other/.h>*/
#endif
| {
"pile_set_name": "Github"
} |
package client // import "github.com/docker/docker/client"
import (
"context"
"net/url"
"github.com/docker/docker/api/types"
)
// NodeRemove removes a Node.
func (cli *Client) NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error {
query := url.Values{}
if options.Force {
query.Set("force", "1")
}
resp, err := cli.delete(ctx, "/nodes/"+nodeID, query, nil)
defer ensureReaderClosed(resp)
return wrapResponseError(err, resp, "node", nodeID)
}
| {
"pile_set_name": "Github"
} |
## 
:cn: [点击进入简体中文版](https://github.com/JackJiang2011/beautyeye/blob/master/README.md)
:bulb: BeautyEye has migrated from [Google Code](https://code.google.com/p/beautyeye/) since 2015-01-30.
BeautyEye is a cross platform Java Swing look and feel;<br>
Benefit from basic GUI technology of Android, BeautyEye is so different from other look and feel.<br>
BeautyEye is open source and free.
## Source code online
Click here: [http://www.52im.net/thread-112-1-1.html](http://www.52im.net/thread-112-1-1.html)。
## Latest Release
#### :page_facing_up: v3.7 release note
Release time: `2015-11-13 17:23`<br>
1. Resolved text components can not edit on JPopupMenu; <br>
2. Resolved issue that JFormattedTextField has not ui. <br>
> BeautyEye first code since 2012-05, v3.0 released date is 2012-09-11, latest version released date is 2015-11-13. [More release notes](https://github.com/JackJiang2011/beautyeye/wiki/BeautyEye-release-notes)
## Compatibility
BeautyEye can be run at java 1.5,1.6,1.7 and 1.8 or later.
[See compatibility test](https://github.com/JackJiang2011/beautyeye/wiki/Compatibility_test_results).
## Feature
* Cross-platform;
* Main ui style;
* Better compatibility.
## Demos
<b>Tip:</b> Ensure has install JRE(java1.5+).
* :paperclip: [Download demo jar\(Swingsets2\)](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/demo/excute_jar/SwingSets2\(BeautyEyeLNFDemo\).jar)
* :paperclip: [Download demo jar\(Swingsets3\)](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/demo2/SwingSets3(BeautyEyeLNFDemo).jar) <font color="#FF6600"> \[Recommend:thumbsup:\]</font>
## Download
:paperclip: .zip package:[Download now!](https://github.com/JackJiang2011/beautyeye/archive/v3.6.zip) (included demos, api docs , dist jar and so on).
## Development Guide
#### :triangular_flag_on_post: First step: Import *`beautyeye_lnf.jar`*
you can found dist jar *`beautyeye_lnf.jar`* at *“`/dist/`”*。
#### :triangular_flag_on_post: Second step: Code like this:
```Java
public static void main(String[] args)
{
try
{
org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
}
catch(Exception e)
{
//TODO exception
}
..................... Your code .........................
..................... Your code .........................
}
```
:green_book: Introduction:[BeautyEye L&F brief introduction](https://github.com/JackJiang2011/beautyeye/wiki/BeautyEye-L&F%E7%AE%80%E6%98%8E%E5%BC%80%E5%8F%91%E8%80%85%E6%8C%87%E5%8D%97).
## License
Open source and free.
## Contact
* Issues mail to :love_letter: `[email protected]`; </li>
* Welcome to Java Swing QQ:`259448663` <a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=9971fb1d1845edc87bdec92ad03f329c1d1f280b1cfe73b6d03c13b0f7f8aba1"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="Java Swing技术交流" title="Java Swing技术交流"></a>;
* [Twitter](https://twitter.com/JackJiang2011/).
## About Author

## Preview
#### :triangular_flag_on_post: Part 1/2:[Original image](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/preview/be_lnf_preview_36.png)

#### :triangular_flag_on_post: Part 2/2:[Original image](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/preview/be_lnf_preview2_36.png)

## More Screenshots
#### :triangular_flag_on_post: Case :one::SwingSets2
:point_right: [See more](https://github.com/JackJiang2011/beautyeye/wiki/Screenshots-all-in-one)
#### :triangular_flag_on_post: Case :two::SwingSets3

:paperclip: [download jar\(Swingsets3\)](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/demo2/SwingSets3(BeautyEyeLNFDemo).jar)
#### :triangular_flag_on_post: Case :three::DriodUIBuilder

:point_right: DroidUIBuilder: [see more](https://github.com/JackJiang2011/DroidUIBuilder)
#### :triangular_flag_on_post: Sace :four::Draw9patch


## Wiki
:notebook_with_decorative_cover: [See more](https://github.com/JackJiang2011/beautyeye/wiki)
## Other projects
* **DroidUIBuilder**:一款开源Android GUI设计工具(已于2012年底停止开发),[:octocat: see more](https://github.com/JackJiang2011/DroidUIBuilder)。<br>
* **Swing9patch**:一组很酷的Java Swing可重用组件或UI效果,[:octocat: see more](https://github.com/JackJiang2011/Swing9patch)。<br>
| {
"pile_set_name": "Github"
} |
<group name="ha_sles" version="10" release="215"
pattern:ordernumber="1050"
pattern:category="Base Technologies"
pattern:summary="High Availability"
pattern:description="Provide tools to ensure a high degree of operational continuity and reduce the downtimes of your system."
pattern:visible="true"
>
<pattern name="basesystem" relationship="required" />
<group relationship="required">
<package name="drbd" />
<package name="heartbeat" />
<package name="heartbeat-ldirectord" />
<package name="ocfs2console" />
<package name="ocfs2-tools" />
</group>
</group>
| {
"pile_set_name": "Github"
} |
# Copyright 2013 the V8 project authors. All rights reserved.
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Tests that ToString on a possible-non-cell value works.
On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,42"
PASS "" + foo("foo", i % 2 ? "hello" : 42) is "foo,hello"
PASS successfullyParsed is true
TEST COMPLETE
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
/******************************************************************************
*
* Copyright(c) 2007 - 2017 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
*****************************************************************************/
#define _RTW_IOCTL_SET_C_
#include <drv_types.h>
#include <hal_data.h>
extern void indicate_wx_scan_complete_event(_adapter *padapter);
#define IS_MAC_ADDRESS_BROADCAST(addr) \
(\
((addr[0] == 0xff) && (addr[1] == 0xff) && \
(addr[2] == 0xff) && (addr[3] == 0xff) && \
(addr[4] == 0xff) && (addr[5] == 0xff)) ? _TRUE : _FALSE \
)
u8 rtw_validate_bssid(u8 *bssid)
{
u8 ret = _TRUE;
if (is_zero_mac_addr(bssid)
|| is_broadcast_mac_addr(bssid)
|| is_multicast_mac_addr(bssid)
)
ret = _FALSE;
return ret;
}
u8 rtw_validate_ssid(NDIS_802_11_SSID *ssid)
{
#ifdef CONFIG_VALIDATE_SSID
u8 i;
#endif
u8 ret = _TRUE;
if (ssid->SsidLength > 32) {
ret = _FALSE;
goto exit;
}
#ifdef CONFIG_VALIDATE_SSID
for (i = 0; i < ssid->SsidLength; i++) {
/* wifi, printable ascii code must be supported */
if (!((ssid->Ssid[i] >= 0x20) && (ssid->Ssid[i] <= 0x7e))) {
ret = _FALSE;
break;
}
}
#endif /* CONFIG_VALIDATE_SSID */
exit:
return ret;
}
u8 rtw_do_join(_adapter *padapter);
u8 rtw_do_join(_adapter *padapter)
{
_irqL irqL;
_list *plist, *phead;
u8 *pibss = NULL;
struct mlme_priv *pmlmepriv = &(padapter->mlmepriv);
struct sitesurvey_parm parm;
_queue *queue = &(pmlmepriv->scanned_queue);
u8 ret = _SUCCESS;
_enter_critical_bh(&(pmlmepriv->scanned_queue.lock), &irqL);
phead = get_list_head(queue);
plist = get_next(phead);
pmlmepriv->cur_network.join_res = -2;
set_fwstate(pmlmepriv, _FW_UNDER_LINKING);
pmlmepriv->pscanned = plist;
pmlmepriv->to_join = _TRUE;
rtw_init_sitesurvey_parm(padapter, &parm);
_rtw_memcpy(&parm.ssid[0], &pmlmepriv->assoc_ssid, sizeof(NDIS_802_11_SSID));
parm.ssid_num = 1;
if (_rtw_queue_empty(queue) == _TRUE) {
_exit_critical_bh(&(pmlmepriv->scanned_queue.lock), &irqL);
_clr_fwstate_(pmlmepriv, _FW_UNDER_LINKING);
/* when set_ssid/set_bssid for rtw_do_join(), but scanning queue is empty */
/* we try to issue sitesurvey firstly */
if (pmlmepriv->LinkDetectInfo.bBusyTraffic == _FALSE
|| rtw_to_roam(padapter) > 0
) {
u8 ssc_chk = rtw_sitesurvey_condition_check(padapter, _FALSE);
if ((ssc_chk == SS_ALLOW) || (ssc_chk == SS_DENY_BUSY_TRAFFIC) ){
/* submit site_survey_cmd */
ret = rtw_sitesurvey_cmd(padapter, &parm);
if (_SUCCESS != ret)
pmlmepriv->to_join = _FALSE;
} else {
/*if (ssc_chk == SS_DENY_BUDDY_UNDER_SURVEY)*/
pmlmepriv->to_join = _FALSE;
ret = _FAIL;
}
} else {
pmlmepriv->to_join = _FALSE;
ret = _FAIL;
}
goto exit;
} else {
int select_ret;
_exit_critical_bh(&(pmlmepriv->scanned_queue.lock), &irqL);
select_ret = rtw_select_and_join_from_scanned_queue(pmlmepriv);
if (select_ret == _SUCCESS) {
pmlmepriv->to_join = _FALSE;
_set_timer(&pmlmepriv->assoc_timer, MAX_JOIN_TIMEOUT);
} else {
if (check_fwstate(pmlmepriv, WIFI_ADHOC_STATE) == _TRUE) {
/* submit createbss_cmd to change to a ADHOC_MASTER */
/* pmlmepriv->lock has been acquired by caller... */
WLAN_BSSID_EX *pdev_network = &(padapter->registrypriv.dev_network);
/*pmlmepriv->fw_state = WIFI_ADHOC_MASTER_STATE;*/
init_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE);
pibss = padapter->registrypriv.dev_network.MacAddress;
_rtw_memset(&pdev_network->Ssid, 0, sizeof(NDIS_802_11_SSID));
_rtw_memcpy(&pdev_network->Ssid, &pmlmepriv->assoc_ssid, sizeof(NDIS_802_11_SSID));
rtw_update_registrypriv_dev_network(padapter);
rtw_generate_random_ibss(pibss);
if (rtw_create_ibss_cmd(padapter, 0) != _SUCCESS) {
ret = _FALSE;
goto exit;
}
pmlmepriv->to_join = _FALSE;
} else {
/* can't associate ; reset under-linking */
_clr_fwstate_(pmlmepriv, _FW_UNDER_LINKING);
/* when set_ssid/set_bssid for rtw_do_join(), but there are no desired bss in scanning queue */
/* we try to issue sitesurvey firstly */
if (pmlmepriv->LinkDetectInfo.bBusyTraffic == _FALSE
|| rtw_to_roam(padapter) > 0
) {
u8 ssc_chk = rtw_sitesurvey_condition_check(padapter, _FALSE);
if ((ssc_chk == SS_ALLOW) || (ssc_chk == SS_DENY_BUSY_TRAFFIC)){
/* RTW_INFO(("rtw_do_join() when no desired bss in scanning queue\n"); */
ret = rtw_sitesurvey_cmd(padapter, &parm);
if (_SUCCESS != ret)
pmlmepriv->to_join = _FALSE;
} else {
/*if (ssc_chk == SS_DENY_BUDDY_UNDER_SURVEY) {
} else {*/
ret = _FAIL;
pmlmepriv->to_join = _FALSE;
}
} else {
ret = _FAIL;
pmlmepriv->to_join = _FALSE;
}
}
}
}
exit:
return ret;
}
u8 rtw_set_802_11_bssid(_adapter *padapter, u8 *bssid)
{
_irqL irqL;
u8 status = _SUCCESS;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
RTW_PRINT("set bssid:%pM\n", bssid);
if ((bssid[0] == 0x00 && bssid[1] == 0x00 && bssid[2] == 0x00 && bssid[3] == 0x00 && bssid[4] == 0x00 && bssid[5] == 0x00) ||
(bssid[0] == 0xFF && bssid[1] == 0xFF && bssid[2] == 0xFF && bssid[3] == 0xFF && bssid[4] == 0xFF && bssid[5] == 0xFF)) {
status = _FAIL;
goto exit;
}
_enter_critical_bh(&pmlmepriv->lock, &irqL);
RTW_INFO("Set BSSID under fw_state=0x%08x\n", get_fwstate(pmlmepriv));
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY) == _TRUE)
goto handle_tkip_countermeasure;
else if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING) == _TRUE)
goto release_mlme_lock;
if (check_fwstate(pmlmepriv, _FW_LINKED | WIFI_ADHOC_MASTER_STATE) == _TRUE) {
if (_rtw_memcmp(&pmlmepriv->cur_network.network.MacAddress, bssid, ETH_ALEN) == _TRUE) {
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE) == _FALSE)
goto release_mlme_lock;/* it means driver is in WIFI_ADHOC_MASTER_STATE, we needn't create bss again. */
} else {
rtw_disassoc_cmd(padapter, 0, 0);
if (check_fwstate(pmlmepriv, _FW_LINKED) == _TRUE)
rtw_indicate_disconnect(padapter, 0, _FALSE);
rtw_free_assoc_resources_cmd(padapter, _TRUE, 0);
if ((check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) == _TRUE)) {
_clr_fwstate_(pmlmepriv, WIFI_ADHOC_MASTER_STATE);
set_fwstate(pmlmepriv, WIFI_ADHOC_STATE);
}
}
}
handle_tkip_countermeasure:
if (rtw_handle_tkip_countermeasure(padapter, __func__) == _FAIL) {
status = _FAIL;
goto release_mlme_lock;
}
_rtw_memset(&pmlmepriv->assoc_ssid, 0, sizeof(NDIS_802_11_SSID));
_rtw_memcpy(&pmlmepriv->assoc_bssid, bssid, ETH_ALEN);
pmlmepriv->assoc_by_bssid = _TRUE;
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY) == _TRUE)
pmlmepriv->to_join = _TRUE;
else
status = rtw_do_join(padapter);
release_mlme_lock:
_exit_critical_bh(&pmlmepriv->lock, &irqL);
exit:
return status;
}
u8 rtw_set_802_11_ssid(_adapter *padapter, NDIS_802_11_SSID *ssid)
{
_irqL irqL;
u8 status = _SUCCESS;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_network *pnetwork = &pmlmepriv->cur_network;
RTW_PRINT("set ssid [%s] fw_state=0x%08x\n",
ssid->Ssid, get_fwstate(pmlmepriv));
if (!rtw_is_hw_init_completed(padapter)) {
status = _FAIL;
goto exit;
}
_enter_critical_bh(&pmlmepriv->lock, &irqL);
RTW_INFO("Set SSID under fw_state=0x%08x\n", get_fwstate(pmlmepriv));
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY) == _TRUE)
goto handle_tkip_countermeasure;
else if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING) == _TRUE)
goto release_mlme_lock;
if (check_fwstate(pmlmepriv, _FW_LINKED | WIFI_ADHOC_MASTER_STATE) == _TRUE) {
if ((pmlmepriv->assoc_ssid.SsidLength == ssid->SsidLength) &&
(_rtw_memcmp(&pmlmepriv->assoc_ssid.Ssid, ssid->Ssid, ssid->SsidLength) == _TRUE)) {
if ((check_fwstate(pmlmepriv, WIFI_STATION_STATE) == _FALSE)) {
if (rtw_is_same_ibss(padapter, pnetwork) == _FALSE) {
/* if in WIFI_ADHOC_MASTER_STATE | WIFI_ADHOC_STATE, create bss or rejoin again */
rtw_disassoc_cmd(padapter, 0, 0);
if (check_fwstate(pmlmepriv, _FW_LINKED) == _TRUE)
rtw_indicate_disconnect(padapter, 0, _FALSE);
rtw_free_assoc_resources_cmd(padapter, _TRUE, 0);
if (check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) == _TRUE) {
_clr_fwstate_(pmlmepriv, WIFI_ADHOC_MASTER_STATE);
set_fwstate(pmlmepriv, WIFI_ADHOC_STATE);
}
} else {
goto release_mlme_lock;/* it means driver is in WIFI_ADHOC_MASTER_STATE, we needn't create bss again. */
}
}
#ifdef CONFIG_LPS
else
rtw_lps_ctrl_wk_cmd(padapter, LPS_CTRL_JOINBSS, 0);
#endif
} else {
rtw_disassoc_cmd(padapter, 0, 0);
if (check_fwstate(pmlmepriv, _FW_LINKED) == _TRUE)
rtw_indicate_disconnect(padapter, 0, _FALSE);
rtw_free_assoc_resources_cmd(padapter, _TRUE, 0);
if (check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) == _TRUE) {
_clr_fwstate_(pmlmepriv, WIFI_ADHOC_MASTER_STATE);
set_fwstate(pmlmepriv, WIFI_ADHOC_STATE);
}
}
}
handle_tkip_countermeasure:
if (rtw_handle_tkip_countermeasure(padapter, __func__) == _FAIL) {
status = _FAIL;
goto release_mlme_lock;
}
if (rtw_validate_ssid(ssid) == _FALSE) {
status = _FAIL;
goto release_mlme_lock;
}
_rtw_memcpy(&pmlmepriv->assoc_ssid, ssid, sizeof(NDIS_802_11_SSID));
pmlmepriv->assoc_by_bssid = _FALSE;
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY) == _TRUE)
pmlmepriv->to_join = _TRUE;
else
status = rtw_do_join(padapter);
release_mlme_lock:
_exit_critical_bh(&pmlmepriv->lock, &irqL);
exit:
return status;
}
u8 rtw_set_802_11_connect(_adapter *padapter, u8 *bssid, NDIS_802_11_SSID *ssid)
{
_irqL irqL;
u8 status = _SUCCESS;
bool bssid_valid = _TRUE;
bool ssid_valid = _TRUE;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if (!ssid || rtw_validate_ssid(ssid) == _FALSE)
ssid_valid = _FALSE;
if (!bssid || rtw_validate_bssid(bssid) == _FALSE)
bssid_valid = _FALSE;
if (ssid_valid == _FALSE && bssid_valid == _FALSE) {
RTW_INFO(FUNC_ADPT_FMT" ssid:%p, ssid_valid:%d, bssid:%p, bssid_valid:%d\n",
FUNC_ADPT_ARG(padapter), ssid, ssid_valid, bssid, bssid_valid);
status = _FAIL;
goto exit;
}
if (!rtw_is_hw_init_completed(padapter)) {
status = _FAIL;
goto exit;
}
_enter_critical_bh(&pmlmepriv->lock, &irqL);
RTW_PRINT(FUNC_ADPT_FMT" fw_state=0x%08x\n",
FUNC_ADPT_ARG(padapter), get_fwstate(pmlmepriv));
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY) == _TRUE)
goto handle_tkip_countermeasure;
else if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING) == _TRUE)
goto release_mlme_lock;
handle_tkip_countermeasure:
if (rtw_handle_tkip_countermeasure(padapter, __func__) == _FAIL) {
status = _FAIL;
goto release_mlme_lock;
}
if (ssid && ssid_valid)
_rtw_memcpy(&pmlmepriv->assoc_ssid, ssid, sizeof(NDIS_802_11_SSID));
else
_rtw_memset(&pmlmepriv->assoc_ssid, 0, sizeof(NDIS_802_11_SSID));
if (bssid && bssid_valid) {
_rtw_memcpy(&pmlmepriv->assoc_bssid, bssid, ETH_ALEN);
pmlmepriv->assoc_by_bssid = _TRUE;
} else
pmlmepriv->assoc_by_bssid = _FALSE;
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY) == _TRUE)
pmlmepriv->to_join = _TRUE;
else
status = rtw_do_join(padapter);
release_mlme_lock:
_exit_critical_bh(&pmlmepriv->lock, &irqL);
exit:
return status;
}
u8 rtw_set_802_11_infrastructure_mode(_adapter *padapter,
NDIS_802_11_NETWORK_INFRASTRUCTURE networktype, u8 flags)
{
_irqL irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_network *cur_network = &pmlmepriv->cur_network;
NDIS_802_11_NETWORK_INFRASTRUCTURE *pold_state = &(cur_network->network.InfrastructureMode);
u8 ap2sta_mode = _FALSE;
u8 ret = _TRUE;
u8 is_linked = _FALSE, is_adhoc_master = _FALSE;
if (*pold_state != networktype) {
/* RTW_INFO("change mode, old_mode=%d, new_mode=%d, fw_state=0x%x\n", *pold_state, networktype, get_fwstate(pmlmepriv)); */
if (*pold_state == Ndis802_11APMode
|| *pold_state == Ndis802_11_mesh
) {
/* change to other mode from Ndis802_11APMode/Ndis802_11_mesh */
cur_network->join_res = -1;
ap2sta_mode = _TRUE;
#ifdef CONFIG_NATIVEAP_MLME
stop_ap_mode(padapter);
#endif
}
_enter_critical_bh(&pmlmepriv->lock, &irqL);
is_linked = check_fwstate(pmlmepriv, _FW_LINKED);
is_adhoc_master = check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE);
/* flags = 0, means enqueue cmd and no wait */
if (flags != 0)
_exit_critical_bh(&pmlmepriv->lock, &irqL);
if ((is_linked == _TRUE) || (*pold_state == Ndis802_11IBSS))
rtw_disassoc_cmd(padapter, 0, flags);
if ((is_linked == _TRUE) ||
(is_adhoc_master == _TRUE))
rtw_free_assoc_resources_cmd(padapter, _TRUE, flags);
if ((*pold_state == Ndis802_11Infrastructure) || (*pold_state == Ndis802_11IBSS)) {
if (is_linked == _TRUE) {
rtw_indicate_disconnect(padapter, 0, _FALSE); /*will clr Linked_state; before this function, we must have checked whether issue dis-assoc_cmd or not*/
}
}
/* flags = 0, means enqueue cmd and no wait */
if (flags != 0)
_enter_critical_bh(&pmlmepriv->lock, &irqL);
*pold_state = networktype;
_clr_fwstate_(pmlmepriv, ~WIFI_NULL_STATE);
switch (networktype) {
case Ndis802_11IBSS:
set_fwstate(pmlmepriv, WIFI_ADHOC_STATE);
break;
case Ndis802_11Infrastructure:
set_fwstate(pmlmepriv, WIFI_STATION_STATE);
if (ap2sta_mode)
rtw_init_bcmc_stainfo(padapter);
break;
case Ndis802_11APMode:
set_fwstate(pmlmepriv, WIFI_AP_STATE);
#ifdef CONFIG_NATIVEAP_MLME
start_ap_mode(padapter);
/* rtw_indicate_connect(padapter); */
#endif
break;
#ifdef CONFIG_RTW_MESH
case Ndis802_11_mesh:
set_fwstate(pmlmepriv, WIFI_MESH_STATE);
start_ap_mode(padapter);
break;
#endif
case Ndis802_11AutoUnknown:
case Ndis802_11InfrastructureMax:
break;
case Ndis802_11Monitor:
set_fwstate(pmlmepriv, WIFI_MONITOR_STATE);
break;
default:
ret = _FALSE;
rtw_warn_on(1);
}
/* SecClearAllKeys(adapter); */
_exit_critical_bh(&pmlmepriv->lock, &irqL);
}
return ret;
}
u8 rtw_set_802_11_disassociate(_adapter *padapter)
{
_irqL irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
_enter_critical_bh(&pmlmepriv->lock, &irqL);
if (check_fwstate(pmlmepriv, _FW_LINKED) == _TRUE) {
rtw_disassoc_cmd(padapter, 0, 0);
rtw_indicate_disconnect(padapter, 0, _FALSE);
/* modify for CONFIG_IEEE80211W, none 11w can use it */
rtw_free_assoc_resources_cmd(padapter, _TRUE, 0);
if (_FAIL == rtw_pwr_wakeup(padapter))
RTW_INFO("%s(): rtw_pwr_wakeup fail !!!\n", __FUNCTION__);
}
_exit_critical_bh(&pmlmepriv->lock, &irqL);
return _TRUE;
}
#if 1
u8 rtw_set_802_11_bssid_list_scan(_adapter *padapter, struct sitesurvey_parm *pparm)
{
_irqL irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
u8 res = _TRUE;
_enter_critical_bh(&pmlmepriv->lock, &irqL);
res = rtw_sitesurvey_cmd(padapter, pparm);
_exit_critical_bh(&pmlmepriv->lock, &irqL);
return res;
}
#else
u8 rtw_set_802_11_bssid_list_scan(_adapter *padapter, struct sitesurvey_parm *pparm)
{
_irqL irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
u8 res = _TRUE;
if (padapter == NULL) {
res = _FALSE;
goto exit;
}
if (!rtw_is_hw_init_completed(padapter)) {
res = _FALSE;
goto exit;
}
if ((check_fwstate(pmlmepriv, _FW_UNDER_SURVEY | _FW_UNDER_LINKING) == _TRUE) ||
(pmlmepriv->LinkDetectInfo.bBusyTraffic == _TRUE)) {
/* Scan or linking is in progress, do nothing. */
res = _TRUE;
} else {
if (rtw_is_scan_deny(padapter)) {
RTW_INFO(FUNC_ADPT_FMT": scan deny\n", FUNC_ADPT_ARG(padapter));
indicate_wx_scan_complete_event(padapter);
return _SUCCESS;
}
_enter_critical_bh(&pmlmepriv->lock, &irqL);
res = rtw_sitesurvey_cmd(padapter, pparm);
_exit_critical_bh(&pmlmepriv->lock, &irqL);
}
exit:
return res;
}
#endif
#ifdef CONFIG_RTW_ACS
u8 rtw_set_acs_sitesurvey(_adapter *adapter)
{
struct rf_ctl_t *rfctl = adapter_to_rfctl(adapter);
struct sitesurvey_parm parm;
u8 uch;
u8 ch_num = 0;
int i;
BAND_TYPE band;
u8 (*center_chs_num)(u8) = NULL;
u8 (*center_chs)(u8, u8) = NULL;
u8 ret = _FAIL;
if (!rtw_mi_get_ch_setting_union(adapter, &uch, NULL, NULL))
goto exit;
_rtw_memset(&parm, 0, sizeof(struct sitesurvey_parm));
parm.scan_mode = SCAN_PASSIVE;
parm.bw = CHANNEL_WIDTH_20;
parm.acs = 1;
for (band = BAND_ON_2_4G; band < BAND_MAX; band++) {
if (band == BAND_ON_2_4G) {
center_chs_num = center_chs_2g_num;
center_chs = center_chs_2g;
} else
#ifdef CONFIG_IEEE80211_BAND_5GHZ
if (band == BAND_ON_5G) {
center_chs_num = center_chs_5g_num;
center_chs = center_chs_5g;
} else
#endif
{
center_chs_num = NULL;
center_chs = NULL;
}
if (!center_chs_num || !center_chs)
continue;
if (rfctl->ch_sel_within_same_band) {
if (rtw_is_2g_ch(uch) && band != BAND_ON_2_4G)
continue;
#ifdef CONFIG_IEEE80211_BAND_5GHZ
if (rtw_is_5g_ch(uch) && band != BAND_ON_5G)
continue;
#endif
}
ch_num = center_chs_num(CHANNEL_WIDTH_20);
for (i = 0; i < ch_num && parm.ch_num < RTW_CHANNEL_SCAN_AMOUNT; i++) {
parm.ch[parm.ch_num].hw_value = center_chs(CHANNEL_WIDTH_20, i);
parm.ch[parm.ch_num].flags = RTW_IEEE80211_CHAN_PASSIVE_SCAN;
parm.ch_num++;
}
}
ret = rtw_set_802_11_bssid_list_scan(adapter, &parm);
exit:
return ret;
}
#endif /* CONFIG_RTW_ACS */
u8 rtw_set_802_11_authentication_mode(_adapter *padapter, NDIS_802_11_AUTHENTICATION_MODE authmode)
{
struct security_priv *psecuritypriv = &padapter->securitypriv;
int res;
u8 ret;
psecuritypriv->ndisauthtype = authmode;
if (psecuritypriv->ndisauthtype > 3)
psecuritypriv->dot11AuthAlgrthm = dot11AuthAlgrthm_8021X;
#ifdef CONFIG_WAPI_SUPPORT
if (psecuritypriv->ndisauthtype == 6)
psecuritypriv->dot11AuthAlgrthm = dot11AuthAlgrthm_WAPI;
#endif
res = rtw_set_auth(padapter, psecuritypriv);
if (res == _SUCCESS)
ret = _TRUE;
else
ret = _FALSE;
return ret;
}
u8 rtw_set_802_11_add_wep(_adapter *padapter, NDIS_802_11_WEP *wep)
{
u8 bdefaultkey;
u8 btransmitkey;
sint keyid, res;
struct security_priv *psecuritypriv = &(padapter->securitypriv);
u8 ret = _SUCCESS;
bdefaultkey = (wep->KeyIndex & 0x40000000) > 0 ? _FALSE : _TRUE; /* for ??? */
btransmitkey = (wep->KeyIndex & 0x80000000) > 0 ? _TRUE : _FALSE; /* for ??? */
keyid = wep->KeyIndex & 0x3fffffff;
if (keyid >= 4) {
ret = _FALSE;
goto exit;
}
switch (wep->KeyLength) {
case 5:
psecuritypriv->dot11PrivacyAlgrthm = _WEP40_;
break;
case 13:
psecuritypriv->dot11PrivacyAlgrthm = _WEP104_;
break;
default:
psecuritypriv->dot11PrivacyAlgrthm = _NO_PRIVACY_;
break;
}
_rtw_memcpy(&(psecuritypriv->dot11DefKey[keyid].skey[0]), &(wep->KeyMaterial), wep->KeyLength);
psecuritypriv->dot11DefKeylen[keyid] = wep->KeyLength;
psecuritypriv->dot11PrivacyKeyIndex = keyid;
res = rtw_set_key(padapter, psecuritypriv, keyid, 1, _TRUE);
if (res == _FAIL)
ret = _FALSE;
exit:
return ret;
}
/*
* rtw_get_cur_max_rate -
* @adapter: pointer to _adapter structure
*
* Return 0 or 100Kbps
*/
u16 rtw_get_cur_max_rate(_adapter *adapter)
{
int j;
int i = 0;
u16 rate = 0, max_rate = 0;
struct mlme_priv *pmlmepriv = &adapter->mlmepriv;
WLAN_BSSID_EX *pcur_bss = &pmlmepriv->cur_network.network;
int sta_bssrate_len = 0;
unsigned char sta_bssrate[NumRates];
struct sta_info *psta = NULL;
u8 short_GI = 0;
#ifdef CONFIG_80211N_HT
u8 rf_type = 0;
#endif
#ifdef CONFIG_MP_INCLUDED
if (adapter->registrypriv.mp_mode == 1) {
if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == _TRUE)
return 0;
}
#endif
if ((check_fwstate(pmlmepriv, _FW_LINKED) != _TRUE)
&& (check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) != _TRUE))
return 0;
psta = rtw_get_stainfo(&adapter->stapriv, get_bssid(pmlmepriv));
if (psta == NULL)
return 0;
short_GI = query_ra_short_GI(psta, rtw_get_tx_bw_mode(adapter, psta));
#ifdef CONFIG_80211N_HT
if (is_supported_ht(psta->wireless_mode)) {
rtw_hal_get_hwreg(adapter, HW_VAR_RF_TYPE, (u8 *)(&rf_type));
max_rate = rtw_mcs_rate(rf_type
, (psta->cmn.bw_mode == CHANNEL_WIDTH_40) ? 1 : 0
, short_GI
, psta->htpriv.ht_cap.supp_mcs_set
);
}
#ifdef CONFIG_80211AC_VHT
else if (is_supported_vht(psta->wireless_mode))
max_rate = ((rtw_vht_mcs_to_data_rate(psta->cmn.bw_mode, short_GI, pmlmepriv->vhtpriv.vht_highest_rate) + 1) >> 1) * 10;
#endif /* CONFIG_80211AC_VHT */
else
#endif /* CONFIG_80211N_HT */
{
/*station mode show :station && ap support rate; softap :show ap support rate*/
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE) == _TRUE)
get_rate_set(adapter, sta_bssrate, &sta_bssrate_len);/*get sta rate and length*/
while ((pcur_bss->SupportedRates[i] != 0) && (pcur_bss->SupportedRates[i] != 0xFF)) {
rate = pcur_bss->SupportedRates[i] & 0x7F;/*AP support rates*/
/*RTW_INFO("%s rate=%02X \n", __func__, rate);*/
/*check STA support rate or not */
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE) == _TRUE) {
for (j = 0; j < sta_bssrate_len; j++) {
/* Avoid the proprietary data rate (22Mbps) of Handlink WSG-4000 AP */
if ((rate | IEEE80211_BASIC_RATE_MASK)
== (sta_bssrate[j] | IEEE80211_BASIC_RATE_MASK)) {
if (rate > max_rate) {
max_rate = rate;
}
break;
}
}
} else {
if (rate > max_rate)
max_rate = rate;
}
i++;
}
max_rate = max_rate * 10 / 2;
}
return max_rate;
}
/*
* rtw_set_scan_mode -
* @adapter: pointer to _adapter structure
* @scan_mode:
*
* Return _SUCCESS or _FAIL
*/
int rtw_set_scan_mode(_adapter *adapter, RT_SCAN_TYPE scan_mode)
{
if (scan_mode != SCAN_ACTIVE && scan_mode != SCAN_PASSIVE)
return _FAIL;
adapter->mlmepriv.scan_mode = scan_mode;
return _SUCCESS;
}
/*
* rtw_set_channel_plan -
* @adapter: pointer to _adapter structure
* @channel_plan:
*
* Return _SUCCESS or _FAIL
*/
int rtw_set_channel_plan(_adapter *adapter, u8 channel_plan)
{
/* handle by cmd_thread to sync with scan operation */
return rtw_set_chplan_cmd(adapter, RTW_CMDF_WAIT_ACK, channel_plan, 1);
}
/*
* rtw_set_country -
* @adapter: pointer to _adapter structure
* @country_code: string of country code
*
* Return _SUCCESS or _FAIL
*/
int rtw_set_country(_adapter *adapter, const char *country_code)
{
#ifdef CONFIG_RTW_IOCTL_SET_COUNTRY
return rtw_set_country_cmd(adapter, RTW_CMDF_WAIT_ACK, country_code, 1);
#else
RTW_INFO("%s(): not applied\n", __func__);
return _SUCCESS;
#endif
}
/*
* rtw_set_band -
* @adapter: pointer to _adapter structure
* @band: band to set
*
* Return _SUCCESS or _FAIL
*/
int rtw_set_band(_adapter *adapter, u8 band)
{
if (rtw_band_valid(band)) {
RTW_INFO(FUNC_ADPT_FMT" band:%d\n", FUNC_ADPT_ARG(adapter), band);
adapter->setband = band;
return _SUCCESS;
}
RTW_PRINT(FUNC_ADPT_FMT" band:%d fail\n", FUNC_ADPT_ARG(adapter), band);
return _FAIL;
}
| {
"pile_set_name": "Github"
} |
{% extends 'layouts/base.html' %}
{% block title %}Error {{ e.code }} {% endblock %}
{% block body %}
<h1>Error: {{ e.code }}</h1>
<h4>{{ e.description }}</h4>
{% endblock %}
| {
"pile_set_name": "Github"
} |
package com.argusapm.android.debug.tasks;
import com.argusapm.android.api.ApmTask;
import com.argusapm.android.core.IInfo;
import com.argusapm.android.core.job.activity.ActivityInfo;
import com.argusapm.android.debug.config.DebugConfig;
import com.argusapm.android.debug.output.OutputProxy;
import com.argusapm.android.debug.utils.DebugFloatWindowUtls;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Debug模块 Activity分析类
*
* @author ArgusAPM Team
*/
public class ActivityParseTask implements IParser {
/**
* 生命周期所用时间
*
* @param info
*/
@Override
public boolean parse(IInfo info) {
if (info instanceof ActivityInfo) {
ActivityInfo aInfo = (ActivityInfo) info;
if (aInfo == null) {
return false;
}
if (aInfo.lifeCycle == ActivityInfo.TYPE_FIRST_FRAME) {
saveWarningInfo(aInfo, DebugConfig.WARN_ACTIVITY_FRAME_VALUE);
DebugFloatWindowUtls.sendBroadcast(aInfo);
} else if (aInfo.lifeCycle == ActivityInfo.TYPE_CREATE) {
saveWarningInfo(aInfo, DebugConfig.WARN_ACTIVITY_CREATE_VALUE);
DebugFloatWindowUtls.sendBroadcast(aInfo);
} else if (aInfo.lifeCycle == ActivityInfo.TYPE_RESUME) {
saveWarningInfo(aInfo, DebugConfig.WARN_ACTIVITY_CREATE_VALUE);
DebugFloatWindowUtls.sendBroadcast(aInfo);
} else {
saveWarningInfo(aInfo, DebugConfig.WARN_ACTIVITY_CREATE_VALUE);
}
}
return true;
}
private void saveWarningInfo(ActivityInfo aInfo, int warningTime) {
if (aInfo.time < warningTime) {
return;
}
try {
JSONObject obj = aInfo.toJson();
obj.put("taskName", ApmTask.TASK_ACTIVITY);
OutputProxy.output("LifeCycle:" + aInfo.getLifeCycleString() + ",cost time:" + aInfo.time, obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| {
"pile_set_name": "Github"
} |
export { default } from 'shared/utils/queue';
| {
"pile_set_name": "Github"
} |
35d85143c3bd10badcad7d3e01bdbad074e4d62a9f04f9c8652da5f5259fed7d
3c2ef1901bee3a4866d68e16de37a270e4f16d166132f14da88b5d0bb5c5a369
6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918
87e58365cf5292ae0150b97d5bba026158e28a5c2fa32cb04cf4c6a0d0c97111
fa3cfb3f1bb823aa9501f88f1f95f732ee6fef2c3a48be7f1d38037b216a549f | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>lab-15-spring-data-elasticsearch</artifactId>
<dependencies>
<!-- 自动化配置 Spring Data Elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 方便等会写单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"pile_set_name": "Github"
} |
SGDK 1.51 (April 2020)
----------------------
COMPILER
* APPACK
- fixed build for 32 and 64 bit linux (thanks doragasu)
* LZ4W
- minor fix
* RESCOMP
- added new sprite optimization options to SPRITE resource (see rescomp.txt for details)
- minor tweak on binary export order (can save some bytes with LZ4W compression)
- fixed resource duplication bug
* XGMTOOL
- fixed VGM loop
LIBRARY
* fixed corrupted library binaries which were displaying a blank screen on some MD models
* MEMORY
- fixed a minor in memory packing operation
- added MEM_pack() here and there to avoid memory fragmentation
* VDP
- fixed getAdjustedVCounterInternal(..) which could return value > 255 in some rare situation
- moved VDP DMA busy checking on reset (better to do it before accessing VDP)
- VDP_setPlaneSize(..):
- added constraint on plane size
- fixed maps start address calculation (when VRAM setup is asked)
- minor change in VDP_drawImageEx(..) to do setTileMap(..) operation using CPU (DMA is actually slower here)
* added SYS_showFrameLoad() / SYS_hideFrameLoad() methods to monitor CPU frame load.
* always load font using CPU in reset process (safer)
* fixed String unit build when ENABLE_NEWLIB set (thanks doragasu)
* improved documentation in Joy unit (thanks Chilly Willy) and VDP (regarding DMA QUEUE usage specifically)
SAMPLE
* reduced memory usage on sample which use Bitmap mode by reducing DMA allocated memory
* SPRITE
- added SYS_showFrameLoad() showcase
SGDK 1.5 (April 2020)
---------------------
COMPILER
* RESCOMP
- added ALIGN directive (read rescomp.txt for more information about it)
- added UNGROUP directive (read rescomp.txt for more information about it)
- added 'compression' and 'far' field to BIN resource
- replaced Map structure export by TileMap
- minor optimization in building IMAGE tilemap
plain tiles are now ignored (taken from system tiles) when using a base tile index offset for tilemap (mapbase parameter in IMAGE resource)
- more flexible resource compilation
- ignore palette and priority for transparent pixel
- sprite can have their palette not starting at index 0
- reorganized resource data export order for better LZ4W compression and bank switch support
- added support for 1bpp and 2bpp indexed color images
- faster LZ4W tool call (embeded in rescomp now)
- preserve resource order for better BIN data compression with LZ4W
- more constrained sprite cutting process depending chosen optimization strategy
- minor fix to allow using bit 7 (color index >= 128) in IMAGE resource as priority bit in tilemap
- simplified / fixed binary compression block with alignment
- fixed a bug on possible duplicated resource export
- fixed Circle collision type export
- now return -1 as exit code on error
- replaced FileWriter by StringBuffer (faster and safer)
- minor changes and improvements to rescomp.txt file
* XGMTOOL
- fixed a small bug during sample conversion processing
* XGMROMBUILDER
- updated to last XGMTool and XGM driver version
* LZ4W
- fixed LZ4W compression which could failed in very are case
* BINTOS
- fixed data section (it was .text instead of .rodata)
* MAKEFILE
- updated 'release' target to generate symbol.txt file (always interesting to have)
- show more warnings
* forced no inlining of memset / memcpy methods to fix LTO agressive optimization issue
LIBRARY
* SYS
- added bank switch support using SSF2 mapper (allow ROM > 4MB)
- use ENABLE_BANK_SWITCH flag in config.h file to enable bank siwtch support in SGDK
- added FAR(..) directive to access a resource through bank switch if required
- added SYS_getBank(..) / SYS_setBank(..) methods
- moved RAM initialization to sys.c unit and added support for bank crossing (more control on it)
- minors changes to reset methods (simpler)
- added ROM and RAM constants (yeah, why not ^^)
* SPRITE
- added sprite frame change event callback (using SPR_setFrameChangeCallback(..) method)
- added SPR_loadAllFrames(..) to (pre)load all frames data of a SpriteDefinition to VRAM
- removed unpack buffer (replaced by DMA buffer and new DMA_QUEUE_COPY method)
- fixed a small issue with delayed update
- fixed a bug on SPR_setDefinition(..) (can display glitches as some sprites weren't always properly hidden)
- fixed internal sprite link (could occasionaly let some phantom and glitched sprites visible)
- added out of range index detection for animation and frame (debug build only)
* DMA
- added new DMA buffer for easier and better DMA queue management
- added 'bufferSize' parameter to DMA_initEx(..) function
- added DMA_setBufferSize(..) and DMA_setBufferSizeToDefault() functions to set the temporary DMA buffer size
- added new DMA_QUEUE_COPY transfer method (TransferMethod enum) to copy data to a temporary buffer before transfer actually occurs
- added DMA_allocateAndQueueDma(..) function which return a temporary buffer and queue a DMA transfer from it
- added DMA_allocateTemp(..) and DMA_releaseTemp(..) methods to allocate memory from DMA temporary buffer (use that safely)
- added DMA_copyAndQueueDma(..) function which copy data to transfer to a temporary buffer and queue the DMA transfer
- added a new generic DMA_transfer(..) function
- added DMA_doCPUCopy(..) function to do a CPU copy to VRAM/CRAM/VSRAM
- added DMA_getMaxQueueSize() and DMA_setMaxQueueSize() to get and set the queue size.
- passed the DMA queue flush loop in assembly for better control (and also faster operation as GCC was dumb about it)
- safer DMA operation on DMA_doDMA(..)
- added DMA_initEx(..) and simplified DMA_init()
- added new DMA_DISABLED flag in config.h to completely disable DMA support in SGDK (for debug purpose)
- fix for HALT_Z80_ON_DMA (stupid typo)
* VDP
- many refactoring (see refactoring section at bottom)
- TILE_USERMAXINDEX now take allocated VRAM for sprite engine in account !
- added TILE_SPRITEINDEX constant to get base tile index for the Sprite Engine
- added tilemap row update methods
- VDP_setTileMapDataRow(..) / VDP_setTileMapDataRowEx(..)
- VDP_setTileMapRow(..) / VDP_setTileMapRowEx(..)
- added tilemap column update methods
- VDP_setTileMapDataColumnFast(..) / VDP_setTileMapDataColumn(..) / VDP_setTileMapDataColumnEx(..)
- VDP_setTileMapColumn(..) / VDP_setTileMapColumnEx(..)
- added TransferMethod parameter to many tilemap set methods
- added tilemap wrapping support to VDP_setTileMap(..) and VDP_setTileMapEx(..) methods.
- added setupVram parameter to VDP_setPlaneSize(..) function
- removed vdpSpriteCacheQueue table (replaced by new DMA_QUEUE_COPY)
- re-introduced VDP_loadTileData(..) method in vdp_tile.c unit (no more assembly code for this one)
- moved font loading in VDP_resetScreen() method (fix)
* PALETTE
- fixed palette fading so it correctly trigger during vblank (avoid CRAM dot)
- fixed minor issue in palette fading (sometime not properly doing last fade step)
* MEMORY
- fixed MEM_getLargestFreeBlock(..) method
- added MEM_pack() method to help reducing memory fragmentation
- removed MEM_init() access as it's not safe to call it externally
- increased stack size to 0xA00
* MATHS
- fixed getLog2Int(..) method
- replaced sin tabs to use FIX32/FIX16 (thanks to FireRat for the generator)
* TYPES
- added new rorxx(..) / rolxx(..) functions which are correctly turned into ROR / ROL instruction when optimization are enabled
* Z80
- fixed Z80 enable restoration on DMA
* general cleanup and refactoring
SAMPLE
* Updated for SGDK 1.5 changes
* BENCHMARK
- added memory information at startup
- some changes to adapt to last SGDK
* SPRITE
- updated resources to use large backgrounds
- updated to support long scrolling > 512 px (vertical and horizontal) !
- as collision is not implemented, added physic settings using START button so we can play with vertical scrolling too
- enemies sprites frames preloaded and animated using new Sprite engine features
Showcase of SPR_loadAllFrames(..) and SPR_setFrameChangeCallback(..) methods
* XGMPlayer
- updated for easier integration in XGM ROM Builder tool
* added notes and tutorial references to README.txt
REFACTORING
* TILE_USERMAXINDEX now take allocated VRAM for sprite engine in account !
* _voidCallback --> VoidCallback
* _joyEventCallback --> JoyEventCallback
* PLAN_A --> BG_A
* PLAN_B --> BG_B
* PLAN_WINDOW --> WINDOW
* VDP_PLAN_A --> VDP_BG_A
* VDP_PLAN_B --> VDP_BG_B
* VDP_PLAN_WINDOW --> VDP_WINDOW
* all references to 'Plan' keyword --> 'Plane'
- VDPPlan --> VDPPlane
- VDP_clearPlan --> VDP_clearPlane
- VDP_getTextPlan --> VDP_getTextPlane
- VDP_setTextPlan --> VDP_setTextPlane
- VDP_setAPlanAddress --> VDP_setBGAAddress
- VDP_setBPlanAddress --> VDP_setBGBAddress
- VDP_setPlanSize --> VDP_setPlaneSize
* all references to 'Map' --> 'TileMap'
- Map --> TileMap
- unpackMap --> unpackTileMap
- allocateMap --> allocateTileMap
- VDP_setMap --> VDP_setTileMap
- VDP_setMapEx --> VDP_setTileMapEx
SGDK 1.41 (September 2019)
--------------------------
COMPILER
* RESCOMP
- added new sprite optimization options to SPRITE resource (see rescomp.txt for details)
- minor tweak on binary export order (can save some bytes with LZ4W compression)
- fixed resource duplication bug
* XGMTOOL
- fixed VGM loop
LIBRARY
* SYS
- Safer SYS_setInterruptMaskLevel() so interrupt mask is not lost after SYS_enablesInts() call
- fixed/updated SGDK logo display code
- renamed getFPS() / getFPS_f() to SYS_getFPS() / SYS_getFPSAsFloat()
* DMA
- fixed possible DMA failure on some Megadrive when Z80 access 68K BUS at same time we trigger DMA
- minor fix on autoInc restoration after DMA_flushQueue()
* VDP
- tweaked default VRAM configuration so window can be freely used anywhere.
- added VDP_getAdjustedVCounter() method to have a consistent [0..255] V-Counter (avoiding rollback issue)
- tweaked up VDP_resetScreen() method
- added VDP_setHVLatching() and VDP_setDMAEnabled() methods
* PALETTE
- fixed VDP_getPaletteColors() and VDP_getPalette(..) methods (regression)
- fixed a bug with all palette fading methods (regression)
- renamed vdp_pal unit to pal unit (so all palette methods are now called PAL_xxx)
* JOY
- added JOY_reset() method to reset controller detection without clearing JOY state change event callback
- safer JOY_setSupport(..) / gun controller implementation
- more permissive mouse id detection in mouse pooling code
- fixed an issue where an EA 4-way multitap could be incorrectly detected
* TIMER
- safer waitSubTick(..) implementation during VInt.
- fixed getSubTick() method to take care of HV counter latching when light guns are used.
* RESOURCE
- added 2 alternate SGDK logo (free feel to use it)
- minor change on library resources name
- fixed version and added alias for old resource names
* added ENABLE_NEWLIB define in config.h file for those who want to use newlib within SGDK (you need to build it by yourself)
* changed 'u16' to 'bool' where it makes sense to use 'bool' (internally they are the same type, it's just for readability).
* minors tweaks, changes and fixes here and there
SAMPLE
* XGMPlayer
- updated to make it work with last SGDK (sprite engine difference mainly)
* SOUND
- reintroduced cry SFX test for XGM driver
SGDK 1.4 (May 2019)
-------------------
COMPILER
* RESCOMP
- rewrote from scratch in java for easier evolution and easy multi OS support.
- added smart sprite cutting (detect empty space in sprite)
- many changes on SPRITE resource, don't forget to read the rescomp.txt file to see changes about this resource.
- can now disable map optimization for IMAGE resources (see rescomp.txt for more information)
* LZ4W
- added code sources (java)
- fixed compression using previous data block in ROM (updated packer to version 1.4)
* BINTOS
- fixed a stupid bug on path.
* added XGM ROM builder tool sources.
* removed RESCOMP (C version), WAVTORAW, TFMCOM and Z80DASM tools.
* added Visual Studio template.
LIBRARY
* SYS
- added SYS_setVIntAligned(..) method to force V-Int callback to align process on VBlank.
IMPORTANT: by default now SGDK *does* align the V-Int processing to VBlank so you need to disable it if you don't want it !
- added SYS_getCPULoad() to return CPU load estimation.
- added SYS_resetMissedFrames() / SYS_getMissedFrames() methods.
* DMA
- simplified DMA over capacity strategy
- minor change in debug log message
* SPRITE
- renamed SPR_init(..) to SPR_initEx(..) so now SPR_init() doesn't require any parameters by default.
- removed 'maxSprite' parameter from Sprite Engine initialization (alays use max available).
- added delayed frame update support.
- added SPR_FLAG_DISABLE_DELAYED_FRAME_UPDATE flag to disable the delayed frame update (when we are running out of DMA capacity).
- added SPR_setDelayedFrameUpdate() to change the delayed frame update state for a sprite.
- added SPR_FLAG_INSERT_HEAD flag to allow adding new sprite in first position (instead of last position by default)
- added SPR_defragVRAM() method to force VRAM defragmentation
- added SPR_addSpriteSafe(..) and SPR_addSpriteExSafe(..) methods (automatically do VRAM defrag if needed)
- fixed a bug where the last VDP sprite attribute weren't always correctly updated with visibility set to AUTO_SLOW.
- fixed a bug a sprite couldn't be allocated.
- fixed sprite visibility state when the number of used sprite changed.
- many changes to sprite structures (better handling of flip info, better ROM usage...)
* VDP
- added VDP_showCPULoad() method to display CPU load
- added VDP_waitVInt() method to wait until next VInt to happen.
- removed 'waitvsync' parameter for VDP_initFading(..) and VDP_doStepFading(..) methods (we always want VSync here)
- simplified / tweaked macros for VDP control writes
* VRAM
- added VRAM_getAllocated(..) and VRAM_getLargestFreeBlock(..) methods
* TYPE
- added bool type
- replaced u16 by bool where it needs to be
* MATHS
- updated fix32Mul() and fix32Div() definition (again, trying to find the best compromize)
- added new missing structures as Vect2D_f32, Mat2D_f32, Vect3D_xx...
- added f16 and f32 as shorcut of fix16 and fix32 types.
- added short typedefs (V2u16 = Vect2D_u16, V2f32 = Vect2D_f32, M2f16 = Mat2D_f16, M3f32 = Mat3D_f32)
* PALETTE
- removed index field from Palette structure
* JOY
- added checking for mouse / multipad read operation to avoid timeout operation when mouse or multipad is not present.
* Z80
- added volatile access for safety
* TIMER
- improved waitMs(..) method to be more accurate on small wait.
- tweaked getSubTick() method (need testing, possible regression)
* STRING
- fixed and optimized uintToStr() method
* TOOL
- memory allocation methods for unpacking now always use deep allocation regardless of the compression used (simpler and less bug prone)
- fixed LZ4W decompression using previous data block
* fixed variable initialization (last byte was not always properly initialized)
* added HALT_Z80_ON_IO define (config.h) to force Z80 halt on IO port access.
* new awesome SGDK logo (Thanks a tons to Lizardrive for making it !)
* removed useless sound drivers (MVS, TFM and VGM)
* removed old TILE_CACHE unit (replaced by VRAM unit)
* removed useless zlib
* many refactoring (sorry for that, you will need to update your old code)
* many tweaks / cleanup
SAMPLE
* updated all samples to take care of last changes made in SGDK
* BENCHMARK
- tweaked big sprite test to disable the delayed sprite update (new sprite engine feature)
- fixed sheet size (new rescomp don't allow it)
SGDK 1.34 (January 2018)
------------------------
LIBRARY
* DMA
- added DMA queue support for all (or almost all) methods supporting DMA operation
* SPRITE
- fixed timing issue when changing FRAME or ANIMATION manually.
- fixed sprite sorting when multiple depth were modified in a single SPR_update(..).
- safer sprite allocation / release.
* MEMORY
- added MEM_getLargestFreeBlock() to get the largest available block of memory.
* improved LZ4W compression (better compression rate, faster compression...)
* minors changes on method updating tilemap through X,Y position (safer)
* some cleanup
SAMPLE
* reworked benchmark sample to avoid out of memory error (^^)
SGDK 1.33 (November 2017)
-------------------------
LIBRARY
* DMA
- added HALT_Z80_ON_DMA flag in config.h to enable Z80 halt on DMA (avoid corruptions or sound issues on Tectoy MD).
- deprecated 'vdp_dma' unit now forward calls to 'dma' unit.
- added wait DMA checking (DMA fill or DMA copy operation) before doing a DMA operation.
* SPRITE
- simplified sprite sorting (always enabled, just need to use SPR_setDepth(..) method if needed)
- fixed a regression which was causing 1 frame latency in sprite update.
SAMPLE
* minor change to sound sample
SGDK 1.32 (October 2017)
------------------------
COMPILER
* added VS project for easier compilation with Visual Studio (thanks to lab313)
LIBRARY
* TIMER:
- fixed getSubTick() method (no more possible rollback)
- minor fix in getFPS() and getFPS_f() methods
* VDP:
- tweaked default VRAM memory layout
* BITMAP:
- changed get/setPixelXXX(..) methods so they now work on single pixel (not anymore doubled X pixel resolution)
- changed drawLine(..) method so it now work on single pixel (not anymore doubled X pixel resolution).
WARNING: drawLine(..) is not anymore doing clipping, use BMP_clipLine(..) first for that.
- added get/setPixelXXXFast(..) methods for fast get/set pixel operation (no clipping check)
* SOUND:
- fixed auto PCM selection when playing sample with driver 2ADPCM and 4PCM.
- fixed default tempo for PAL system with XGM driver
* SPRITE:
WARNING: you now require to set the sprite depth to use depth sorting (not anymore using the sprite Y position).
- replaced SPR_FLAG_AUTO_YSORTING by SPR_FLAG_AUTO_DEPTH_SORTING
- replaced SPR_setYSorting(..) method by SPR_setDepthSorting(..) / SPR_setZSorting(..)
- replaced SPR_sortOnYPos() by SPR_sortOnDepth()
- added void SPR_setDepth(..) / SPR_setZ(..) methods to set sprite depth
- fixed VDP_updateSprites() with DMA queue operation (prevent sprite table modifications before DMA occurs).
* STRING:
- added int16ToStr(..) and uint16ToStr(..) methods (faster than intToStr(..) or uintToStr(..) for 16 bit integer, thanks to clbr)
- optimized intToStr(..) and uintToStr(..) methods (thanks to clbr for that)
SAMPLE
* added XGM Player sample :)
* Bench:
- added some pixels / line draw tests
* Donuts:
- updated for new depth sorting refactoring
SGDK 1.31 (July 2017)
---------------------
DOCUMENTATION
* minor fix and updated to last version
COMPILER
* fixed debug build in 'build_lib' batch
LIBRARY
* JOY:
- fixed joy state variables declaration to avoid issues when GCC -O3 optimization level is used.
* SPRITE:
- added ALWAYS_ON_TOP flag to keep a sprite above others sprites whatever is sorting order.
- minor fix on sprite sort
SGDK 1.3 (June 2017)
--------------------
DOCUMENTATION
* updated to last version
COMPILER
* Updated to GCC 6.3 (thanks a tons to Gligli for that !)
- many bugs fix and new features compared to old GCC 3.4.6
- much better assembly code generation :)
- added LTO (Linker Time Optimization) support
* Modified makefile to enable LTO and improve optimization level.
* Rescomp:
- updated to handle structure changes in the Sprite Engine.
LIBRARY
* DMA:
- minor optimization to DMA_queue(..) method (thanks to HpMan)
* Memory:
- default stack size increased to 0x800 bytes (GCC 6.3 requires more stack memory :p)
* Sprite Engine:
- added automatic Y sorting (per sprite)
- added SPR_sort(..) for generic sorting
- added SPR_sortOnY(..) for generic sorting
- by default now sprite visibility is set to always ON (faster than automatic visibility)
- updated 'Collision' structure (hierarchical structure)
- some changes to internal structures to provide better performance
* VDP BG/Tile:
- fixed a minor bug in VDP_setTileMapDataEx(..) and VDP_setTileMapDataRectEx(..) methods (thanks to Alekmaul for reporting it)
* minors fixes...
SAMPLE
* Bench:
- fixed math tests for GCC 6.3
SGDK 1.22a (September 2016)
---------------------------
LIBRARY
* VDP: reintroduced the 16 plain system tiles.
SGDK 1.22 (September 2016)
--------------------------
DOCUMENTATION
* minors improvements and fixes
COMPILER
* Rescomp: fixed a minor issue in sprite resource
* XGMTool:
- added duration information to XD3 tag
- improved loop
* added the XGM ROM builder tool.
* removed GenRes from makefile
LIBRARY
* Sprite Engine:
- fixed sprite attribut update for non visible sprite
- fixed sprite list update in certain condition
* Sound:
- moved XGM driver method in a specific unit (xgm.c)
- added XGM_getElapsed(..) method to retrieve elapsed XGM music playing time (in number of frame)
- added XGM_setLoopNumber(..) to set the wanted number of loop in XGM music play.
- added interrupt protection for Z80 access
* Maths:
- reverted fix32Mul() and fix32Div() to previous version to avoid cumulative error
- added getApproximatedLog2(..) method for fast Log2 calculation (approximated)
- added getLog2Int(..) method for integer Log2 calculation
* Misc:
- moved QSort methods to tools
- added generic qsort with custom comparator callback
* VDP: more flexible VRAM tilemap configuration (window plan don't have to be first map).
* Bitmap mode: can now set bitmap mode in window plan
* changed to MIT license
* refactoring
SAMPLE
* Bench: added sprite donut animation test.
SGDK 1.21 (May 2016)
--------------------
LIBRARY
* SPRITE: fixed a bug causing corrupted sprite after SPR_release(..) operation
* TOOLS: reintroduced zlib_unpack(..) method (accidentally removed from header)
SAMPLE
* Bench:
- fixed a bug causing address error on real hardware during 'Sprite test'.
- added 2 tests in 'BG test'
SGDK 1.2 (May 2016)
-------------------
DOCUMENTATION
* several update and fixes here and there (some tags were not correctly recognized in later doxygen version).
COMPILER
* Rescomp: updated to version 1.5 (with updated documentation)
- updated SPRITE resource compilation to the new SGDK Sprite structures.
- fixed minor issue on IMAGE resource packing.
- now using constants for sound driver (less confusing, got annoying bug because of that).
- changed header 'define' name generation to avoid conflict between 2 identical named file.
- fixed a bug in tilemap optimization for flipped tiles.
- removed all packers not anymore used in SGDK.
- minor change to XGM resource to support extra parameter
- fixed a minor bug in sprite structure definition
* XGMTool: updated to version 1.64
- major structure changes for faster conversion / optimization operations
- improved VGM to XGM conversion.
- added options to disable some PCM auto processing
- new options available to handle specific case and improve conversion process
- added GD3 tag support.
- better handling of PAL/NTSC timing
- fixed pal information lost during XGC conversion.
- more accurate loop position
- fixed a minor issue in offset calculation.
- fixed VGM loop information export (when using VGM optimization)
* WavToRaw:
- fix 64-bit issues, it is still not endian safe.
- check for read errors.
* Appack: minor fix for silent parameter.
* Added new custom LZ4W packer (require Java to be installed).
* Removed GenRes tool (not anymore used and can confuse with rescomp).
* added GDB tool (not yet really used yet)
* Separated 'debug' and 'release' library build for easier profile switch.
LIBRARY
* BITMAP:
- allow to change the plan used for bitmap rendering
- added buffer preservation option (severe impact on performance)
- fixed minors issues on reset/initialization process
* DMA: added new DMA queue system in 'dma' unit, you can consider 'vdp_dma' unit as deprecated (still provided for backward compatibility).
- we can now limit the max transfer capabilities in a single frame with DMA_setMaxTransferSize(..)
- can now define the DMA queue size with DMA_init(..) method.
- added DMA_setIgnoreOverCapacity(..) to change DMA strategy when reaching max capacity.
* GRAPHIC:
- added news methods for allocation and compression stuff (see TOOLS section)
- added dynamic VRAM allocation ('vram' unit which replace 'tilecache' unit)
* PALETTE:
- fixed RGB24_TO_VDPCOLOR so it does what it says.
- better palette fading using rounding.
- fixed issue using sync fading locking interrupts (can cause XGM music lag).
* MATHS:
- added abs(..) method.
- fixed fix32ToRoundedInt() and fix32Round() defines (added parenthesis around)
- replaced distance_approx(..) by getApproximatedDistance(..)
- changed fix32 div/mul calculation strategy for better value preservation
* MEMORY:
- added MEM_getAllocated() to return current dynamically allocated memory.
- added MEM_dump() to dump in Gend KMod console the memory allocation table
* SOUND:
- renamed Z80_DRIVER_4PCM_ENV --> Z80_DRIVER_4PCM
* SPRITE: complete rewrite of sprite engine !
- many changes including the API.
- should be faster but will be more optimized in future.
* STRING:
- added isdigit(c), strnlen(..) and the very useful sprintf(..) ma
- added strncpy(..) method.
- replaced strreplace(..) --> strreplacechar(..)
- fixed fix32ToStr(..) and fix16ToStr(..) methods
* SYSTEM:
- tried to more more compatible with default GCC stdint.h definitions
- added SYS_setVIntPreCallback(..) so you can have your method called at VInt before any internal SGDK stuff are proceed.
- added SYS_isNTSC() and SYS_isPAL() methods for easy system determination.
- minor fix on SP register initialization (preserve value set in vector table)
- added SYS_hardReset() to force hard reset.
* TOOLS:
- added new LZ4W compression (very fast unpacking but average compression level)
- removed RLE, RLE_MAP and UFTC compression (LZ4W performs better in almost all cases).
- removed UnpackEx(..) method (useless now).
- added setRandomSeed(u16 seed) to initialize randomizer.
* VDP:
- renamed WPLAN / WINDOW / VDP_WINDOW --> VDP_PLAN_WINDOW
- renamed APLAN --> VDP_PLAN_A
- renamed BPLAN --> VDP_PLAN_B
- renamed SLIST / VDP_SPRITE_LIST --> VDP_SPRITE_TABLE
- renamed HSCRL / VDP_SCROLL_H --> VDP_HSCROLL_TABLE
- added planWidth / planHeight to replace VDP_getPlanWidth() / VDP_getPlanHeigth() for faster internal SGDK calculations.
- added windowWidth / windowHeight for faster internal SGDK calculations.
- added VDP_setWindowHPos(..) and VDP_setWindowVPos(..) methods to set window positions.
- fixed a bug with VDP_setBPlanAddress(..) method.
* VDP BG/TILE:
- replaced VDP_PLAN_A / VDP_PLAN_B constants by PLAN_A / PLAN_B in some methods.
- some methods now support PLAN_WINDOW parameter.
- added VDP_clearTextAreaBG(..), VDP_clearTextLineBG(..), VDP_clearTextArea(..) methods.
- modified VDP_drawTextBG(..) method.
- others minors changes.
* VDP SPRITE: major rewrite of 'vdp_sprite' unit (require project modifications) !
- replaced SpriteDef structure by VDPSprite structure (fit better hardware structure).
- added dynamic allocation of hardware sprite:
VDP_allocateSprites(..), VDP_releaseSprites(..), VDP_getAvailableSprites()
- VDP_updateSprites(..) can now use DMA queue.
- many others changes.
* XGM driver:
- better handling of main BUS contention with DMA
- added methods to improve BUS contention when using PSG sound in music.
- fixed PCM play status when PCM is used from XGM music.
- minor fix in driver code for better music frame sync.
- better pause/resume support.
- music sync is now handled on 68000 side for more flexibility (adjustable tempo).
* Z80:
- modified writeYM macros
* memory usage optimizations.
SAMPLE:
* Bench: added new sample for general test and benchmarking.
* Sound:
- minors changes about Z80 load information for XGM driver.
* Sprite:
- added basic enemies (no collision yet)
- added basic SFX
- updated to last SGDK
- some refactoring
SGDK 1.12 (March 2015)
----------------------
COMPILER
* XGMTool:
- minors changes and fixes.
LIBRARY
* SPRITE:
- added VDP_resetSpritesDirect() method.
* SOUND:
- minor fix to XGM driver (PCM in music was wrong in some case).
SGDK 1.11 (December 2014)
-------------------------
* CONTROLLER:
- fixed small issue in joystick code (Chilly Willy).
* SOUND:
- added Z80 CPU load information in XGM driver (experimental).
* Fixed small issue in joystick code (Chilly Willy).
SGDK 1.10 (December 2014)
-------------------------
COMPILER
* XGMTool:
- removed DAC enabled command (automatically handle by the XGM driver).
- added DAC enabled state (XGM driver uses it when no PCM are playing).
- now uses the VGM 1.60 'stream id' information to allow multi PCM channel for XGM conversion.
Note that each channel has its own priority as VGM music does not contains PCM priority information.
LIBRARY
* VDP:
- VDP_fade(..) method now automatically disables interrupts if needed.
* SPRITE:
- minor optimization in the Sprite Engine to quickly discard disabled sprites (visibility forced to off).
* SOUND:
- added automatic DAC enabled control (XGM driver).
- fixed issue with music pause operation on real hardware (XGM driver).
- minor tweak to reduce a bit the size of the Z80 drivers.
- removed Z80_DRIVER_4PCM which is useless (use Z80_DRIVER_4PCM_ENV driver instead).
* CONTROLLER:
- added Sega Phaser support (Chilly Willy).
* SYSTEM:
- disable library debug info.
* SAMPLE:
- updated 'Joy' sample to add Phaser test (Chilly Willy).
- updated 'Sound' sample to remove Z80_DRIVER_4PCM test and add an example of the MVS driver PCM SFX.
SGDK 1.01 (November 2014)
-------------------------
COMPILER
* fixed bugs in XGMTool.
* removed linear interpolation when converting WAV file.
* others minors changes.
SGDK 1.00 (November 2014)
-------------------------
COMPILER
* Rescomp:
- added support to XGM resource in rescomp.
* added xgmtool to convert VGM into XGM and compile XGM file.
* removed Genitile tool sources.
* updated wavtoraw to support sample interpolation.
LIBRARY
* VDP:
- added VDP_setScanMode(u16 mode) method to change the interlaced mode.
- added VDP_interruptFade() method to interrupt async palette fading.
* SPRITE:
- fixed a bug with SPR_init(..) method when using same definition, sometime timer could be not reseted and then animation is not working anymore.
- fixed declaration of VDP_setSprite(..) / VDP_setSpriteDirect(..) / VDP_setSpritePosition(..) methods.
* SOUND:
- Z80 memory is cleared before loading a custom driver.
- added Z80_read(..) and Z80_write(..) methods for simple Z80 RAM read/write operations.
- added XGM driver methods:
u8 SND_isPlaying_XGM();
void SND_startPlay_XGM(const u8 *song);
void SND_stopPlay_XGM();
void SND_resumePlay_XGM();
u8 SND_isPlayingPCM_XGM(const u16 channel_mask);
void SND_setPCM_XGM(const u8 id, const u8 *sample, const u32 len);
void SND_setPCMFast_XGM(const u8 id, const u8 *sample, const u32 len);
void SND_startPlayPCM_XGM(const u8 id, const u8 priority, const u16 channel);
void SND_stopPlayPCM_XGM(const u16 channel);
* MATH:
- minor fix in min/max defines.
* CONTROLLER:
- fixed declaration of JOY_readJoypadX/Y(..) methods (they should return s16 and not u16)
* SYSTEM:
- sega.s and rom_head.c files are now copied into the 'src/boot' project folder so they can easily be customized per project.
* SAMPLE:
- modified sound sample to add XGM driver example.
* some fixes in the doxygen documentation.
* others changes and improvements.
SGDK 0.96d (june 2014)
----------------------
LIBRARY
* removed direct VRam Map data unpacking as it was buggy.
SGDK 0.96c (june 2014)
----------------------
COMPILER
* Rescomp:
- fixed some issues on compression.
- now accept string to define which compression to use (AUTO, APLIB, RLE) in resource definition.
LIBRARY
* minors changes to Doxygen documentation.
SGDK 0.96 (may 2014)
--------------------
COMPILER
* Rescomp:
- improved BMP image support.
- byte data are now output in word format to avoid the GCC bug (compilation with "-g" flag fails when byte data is encountered).
- fixed issue on empty sprite animation detection.
- fixed path separator issue on old windows system.
- fixed compilation issues on unix system.
* Makefile:
- Added "release" and "debug" target to makefile (default is "release").
"debug" target allow you to use GDB interactive debugger through emulator supporting it.
* added appack tool sources code (compatibility for linux system).
* some cleanup in bintos tool (removed the useless sizealign command done by sizebnd tool).
LIBRARY
* VDP:
- fixed palette fading methods where the last frame colors weren't always correct.
- VDP_drawImage(..) and VDP_drawBitmap(..) now use dynamic VRAM tile index so they does not erase anymore the previous drawn image.
'curTileInd' variable which contains the VRAM tile index where next tile will be uploaded is public.
* TILE:
- fixed somes bugs in the tile cache engine.
- removed the MEM_free(..) call from the VInt callback (tile cache engine).
So we don't need anymore to disable interrupts at each memory allocation operation for safety ;)
* SPRITE:
- fixed somes bugs in the sprite engine.
- added SPR_setAlwaysVisible(..) and SPR_setNeverVisible(..) to force (not) visibility on sprite (sprite engine)
* BITMAP:
- minor performance improvement on the BMP_drawPolygon(..) method.
* SOUND:
- fixed YM2612 write methods (can have issue on MD2 system).
* DMA:
- fixed VRam Copy DMA.
* MATH:
- fixed 2D projection calculation in M3D_project_xxx(..) methods.
Now the camera distance is correctly taken in account for the final projection (adding a minor impact on performance).
* SYSTEM:
- fixed soft reset issues.
* TIMER:
- fixed a minor issue with getTime(..) method.
- waitSubTick(..) is now more accurate when called from V-Interrupt code.
* SAMPLE:
- minors changes and improvements on the Sonic Sprite sample.
- minors changes to 3D cube flat sample.
* DEBUG:
- added some KDebug log methods (KLog, KLog_Uxx, KLog_Sxx...)
* added strcmp(..) method.
* others changes and improvements.
SGDK 0.95 (feb 2014)
--------------------
COMPILER
* Major change on resource compilation:
A new resource compiler tool (rescomp) is used to compile all resource files.
It support many type of resources as BMP, PNG, WAV, PCM, VGM, TFM..
Read the rescomp.txt file to have more informations about it and look in the 'sound' and 'sprite' sample example.
You can also convert your old project by using the "rescomp -convert" command on the project folder to convert.
- added appack tool.
- minor fix in wavtoraw tool.
LIBRARY
* added GFX compression support (see tools.h file for doxygen documentation).
* VDP:
- added VDP_getBackgroundColor() and VDP_setBackgroundColor(..) methods.
- added VDP_get/setTextPlan(), VDP_get/setTextPalette() and VDP_get/setTextPriority() methods to change text drawing properties.
- added VDP_drawBitmap(..) and VDP_drawBitmapEx(..) methods to draw Bitmap resource.
- added VDP_drawImage(..) and VDP_drawImageEx(..) methods to draw Image resources.
- added VDP_loadTileSet(..) method to load TileSet resource.
- added VDP_setMap(..) and VDP_setMapEx(..) methods to load Map resources.
- lot of refactoring in the setTileMap methods...
- some tweaks.
* TILE:
- added new tile cache engine for easier tile allocation in VRAM.
See the tile_cache.h file for doxygen documentation.
* SPRITE:
- added sprite engine for easier sprite manipulation.
See the sprite_eng.h file for doxygen documentation and the included "sprite" sample for an example.
* SOUND:
- added TFC_isPlaying() command for the 68k TFM driver.
- fixed issue with consecutive play command on TFM Z80 driver.
- Improved VGM driver (thanks to kubilus1 and sigflup).
You can now pause, resume music and even better play PCM SFX !
- now clear Z80 memory on driver loading to avoid any problems with var initialization.
* DMA:
- minor change to VDP_doDMAEx(..) method, be careful if you use this method, the last parameter changed.
* JOY:
- added JOY_waitPressTime() and JOY_waitPressBtnTime() methods.
- JOY_waitPressBtn() and JOY_waitPress() now return button pressed info.
* MEMORY:
- fixed a minor buf with dynamic memory allocation.
* SYSTEM:
- added SYS_disableInts() and SYS_enableInts() methods.
- added SYS_isInInterrupt() to detect if we are in an interrupt callback.
- added SYS_getAndSetInterruptMaskLevel(..) method to "atomically" get and set interrupt mask level.
- added SYS_die(..) for fatal error handling.
* library font is now included as an image.
* added some logs for easier debugging (KDebug message).
* many others smalls improvements.
* lot of refactoring.
SGDK 0.94 (feb 2013):
---------------------
* Major rewrite of the Bitmap engine:
- Fixed 256x160 resolution.
- Removed all specifics flags as it now always use deferred flip operation with extended blank.
- Simpler and easier to use.
- Better performance (20 FPS in NTSC, 25 FPS in PAL).
- Backface culling now directly handled in the BMP_drawPolygon(..) method.
- Removed useless FF BMP engine (too complex, incomplete..)
- Many others changes you will discover :)
* Added "Bitmap" structure for better bitmap handling.
SGDK automatically convert 16 colors bitmap images to "Bitmap".
* Major rewrite of Maths3D engine:
- Added many 3D related structures (as matrix, transform..).
- More flexibility.
- Improved performance (not much).
* added DMA capability to VDP_setHorizontalScrollxxx(..) / VDP_setVerticalScrollTile(..) functions.
* Added VDP_doDMAEx(..) so we can specify if we modify the VRam step.
* Refactored palette functions.
* Fixed QSort function.
* Removed useless VRAM table (eat rom space for minor speed boost).
* Minors fixes/tweaks in memset and memcpy functions.
* Updated WavToRaw tool (now support any output rate).
* Added Genitile 1.7 sources.
* Minors tweaks on makefile.
* Fixed a minor issue in rom_head (Thanks Chilly Willy).
* Updated demo samples.
* Others minors changes or improvements. | {
"pile_set_name": "Github"
} |
/**
* Aptana Studio
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license-epl.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.editor.epl;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import com.aptana.editor.decorator.ProblemMarkerManager;
/**
* The activator class controls the plug-in life cycle
*/
public class EditorEplPlugin extends AbstractUIPlugin
{
// The plug-in ID
public static final String PLUGIN_ID = "com.aptana.editor.epl"; //$NON-NLS-1$
public static final String DEBUG_SCOPE = PLUGIN_ID + "/debug"; //$NON-NLS-1$
public static final boolean DEBUG = Boolean.valueOf(Platform.getDebugOption(DEBUG_SCOPE)).booleanValue();
// The shared instance
private static EditorEplPlugin plugin;
private ProblemMarkerManager fProblemMarkerManager;
/**
* The constructor
*/
public EditorEplPlugin()
{
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception
{
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception
{
plugin = null;
fProblemMarkerManager = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static EditorEplPlugin getDefault()
{
return plugin;
}
/**
* Returns the standard display to be used. The method first checks, if the thread calling this method has an
* associated display. If so, this display is returned. Otherwise the method returns the default display.
*
* @return returns the standard display to be used
*/
public static Display getStandardDisplay()
{
Display display;
display = Display.getCurrent();
if (display == null)
{
display = Display.getDefault();
}
return display;
}
/**
* Returns a {@link ProblemMarkerManager}
*
* @return {@link ProblemMarkerManager}
*/
public synchronized ProblemMarkerManager getProblemMarkerManager()
{
if (fProblemMarkerManager == null)
{
fProblemMarkerManager = new ProblemMarkerManager();
}
return fProblemMarkerManager;
}
}
| {
"pile_set_name": "Github"
} |
/*!
* jQuery UI CSS Framework 1.11.2
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/theming/
*
* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=highlight_soft&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=glass&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=glass&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
*/
/* Component containers
----------------------------------*/
.ui-widget {
font-family: Verdana,Arial,sans-serif;
font-size: 1.1em;
}
.ui-widget .ui-widget {
font-size: 1em;
}
.ui-widget input,
.ui-widget select,
.ui-widget textarea,
.ui-widget button {
font-family: Verdana,Arial,sans-serif;
font-size: 1em;
}
.ui-widget-content {
border: 1px solid #aaaaaa;
background: #ffffff url("images/ui-bg_flat_75_ffffff_40x100.png") 50% 50% repeat-x;
color: #222222;
}
.ui-widget-content a {
color: #222222;
}
.ui-widget-header {
border: 1px solid #aaaaaa;
background: #cccccc url("images/ui-bg_highlight-soft_75_cccccc_1x100.png") 50% 50% repeat-x;
color: #222222;
font-weight: bold;
}
.ui-widget-header a {
color: #222222;
}
/* Interaction states
----------------------------------*/
.ui-state-default,
.ui-widget-content .`default,
.ui-widget-header .ui-state-default {
border: 1px solid #d3d3d3;
background: #e6e6e6 url("images/ui-bg_glass_75_e6e6e6_1x400.png") 50% 50% repeat-x;
font-weight: normal;
color: #555555;
}
.ui-state-default a,
.ui-state-default a:link,
.ui-state-default a:visited {
color: #555555;
text-decoration: none;
}
.ui-state-hover,
.ui-widget-content .ui-state-hover,
.ui-widget-header .ui-state-hover,
.ui-state-focus,
.ui-widget-content .ui-state-focus,
.ui-widget-header .ui-state-focus {
border: 1px solid #999999;
background: #dadada url("images/ui-bg_glass_75_dadada_1x400.png") 50% 50% repeat-x;
font-weight: normal;
color: #212121;
}
.ui-state-hover a,
.ui-state-hover a:hover,
.ui-state-hover a:link,
.ui-state-hover a:visited,
.ui-state-focus a,
.ui-state-focus a:hover,
.ui-state-focus a:link,
.ui-state-focus a:visited {
color: #212121;
text-decoration: none;
}
.ui-state-active,
.ui-widget-content .ui-state-active,
.ui-widget-header .ui-state-active {
border: 1px solid #aaaaaa;
background: #ffffff url("images/ui-bg_glass_65_ffffff_1x400.png") 50% 50% repeat-x;
font-weight: normal;
color: #212121;
}
.ui-state-active a,
.ui-state-active a:link,
.ui-state-active a:visited {
color: #212121;
text-decoration: none;
}
/* Interaction Cues
----------------------------------*/
.ui-state-highlight,
.ui-widget-content .ui-state-highlight,
.ui-widget-header .ui-state-highlight {
border: 1px solid #fcefa1;
background: #fbf9ee url("images/ui-bg_glass_55_fbf9ee_1x400.png") 50% 50% repeat-x;
color: #363636;
}
.ui-state-highlight a,
.ui-widget-content .ui-state-highlight a,
.ui-widget-header .ui-state-highlight a {
color: #363636;
}
.ui-state-error,
.ui-widget-content .ui-state-error,
.ui-widget-header .ui-state-error {
border: 1px solid #cd0a0a;
background: #fef1ec url("images/ui-bg_glass_95_fef1ec_1x400.png") 50% 50% repeat-x;
color: #cd0a0a;
}
.ui-state-error a,
.ui-widget-content .ui-state-error a,
.ui-widget-header .ui-state-error a {
color: #cd0a0a;
}
.ui-state-error-text,
.ui-widget-content .ui-state-error-text,
.ui-widget-header .ui-state-error-text {
color: #cd0a0a;
}
.ui-priority-primary,
.ui-widget-content .ui-priority-primary,
.ui-widget-header .ui-priority-primary {
font-weight: bold;
}
.ui-priority-secondary,
.ui-widget-content .ui-priority-secondary,
.ui-widget-header .ui-priority-secondary {
opacity: .7;
filter:Alpha(Opacity=70); /* support: IE8 */
font-weight: normal;
}
.ui-state-disabled,
.ui-widget-content .ui-state-disabled,
.ui-widget-header .ui-state-disabled {
opacity: .35;
filter:Alpha(Opacity=35); /* support: IE8 */
background-image: none;
}
.ui-state-disabled .ui-icon {
filter:Alpha(Opacity=35); /* support: IE8 - See #6059 */
}
/* Icons
----------------------------------*/
/* states and images */
.ui-icon {
width: 16px;
height: 16px;
}
.ui-icon,
.ui-widget-content .ui-icon {
background-image: url("images/ui-icons_222222_256x240.png");
}
.ui-widget-header .ui-icon {
background-image: url("images/ui-icons_222222_256x240.png");
}
.ui-state-default .ui-icon {
background-image: url("images/ui-icons_888888_256x240.png");
}
.ui-state-hover .ui-icon,
.ui-state-focus .ui-icon {
background-image: url("images/ui-icons_454545_256x240.png");
}
.ui-state-active .ui-icon {
background-image: url("images/ui-icons_454545_256x240.png");
}
.ui-state-highlight .ui-icon {
background-image: url("images/ui-icons_2e83ff_256x240.png");
}
.ui-state-error .ui-icon,
.ui-state-error-text .ui-icon {
background-image: url("images/ui-icons_cd0a0a_256x240.png");
}
.ui-state-fail-text .ui-icon {
background-image: url("images/ui-icons_cd0a0a_256x240.png");
}
.ui-state-pass-text .ui-icon {
background-image: url("images/ui-icons_8DC262_256x240.png");
}
/* positioning */
.ui-icon-blank { background-position: 16px 16px; }
.ui-icon-carat-1-n { background-position: 0 0; }
.ui-icon-carat-1-ne { background-position: -16px 0; }
.ui-icon-carat-1-e { background-position: -32px 0; }
.ui-icon-carat-1-se { background-position: -48px 0; }
.ui-icon-carat-1-s { background-position: -64px 0; }
.ui-icon-carat-1-sw { background-position: -80px 0; }
.ui-icon-carat-1-w { background-position: -96px 0; }
.ui-icon-carat-1-nw { background-position: -112px 0; }
.ui-icon-carat-2-n-s { background-position: -128px 0; }
.ui-icon-carat-2-e-w { background-position: -144px 0; }
.ui-icon-triangle-1-n { background-position: 0 -16px; }
.ui-icon-triangle-1-ne { background-position: -16px -16px; }
.ui-icon-triangle-1-e { background-position: -32px -16px; }
.ui-icon-triangle-1-se { background-position: -48px -16px; }
.ui-icon-triangle-1-s { background-position: -64px -16px; }
.ui-icon-triangle-1-sw { background-position: -80px -16px; }
.ui-icon-triangle-1-w { background-position: -96px -16px; }
.ui-icon-triangle-1-nw { background-position: -112px -16px; }
.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
.ui-icon-arrow-1-n { background-position: 0 -32px; }
.ui-icon-arrow-1-ne { background-position: -16px -32px; }
.ui-icon-arrow-1-e { background-position: -32px -32px; }
.ui-icon-arrow-1-se { background-position: -48px -32px; }
.ui-icon-arrow-1-s { background-position: -64px -32px; }
.ui-icon-arrow-1-sw { background-position: -80px -32px; }
.ui-icon-arrow-1-w { background-position: -96px -32px; }
.ui-icon-arrow-1-nw { background-position: -112px -32px; }
.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
.ui-icon-arrow-4 { background-position: 0 -80px; }
.ui-icon-arrow-4-diag { background-position: -16px -80px; }
.ui-icon-extlink { background-position: -32px -80px; }
.ui-icon-newwin { background-position: -48px -80px; }
.ui-icon-refresh { background-position: -64px -80px; }
.ui-icon-shuffle { background-position: -80px -80px; }
.ui-icon-transfer-e-w { background-position: -96px -80px; }
.ui-icon-transferthick-e-w { background-position: -112px -80px; }
.ui-icon-folder-collapsed { background-position: 0 -96px; }
.ui-icon-folder-open { background-position: -16px -96px; }
.ui-icon-document { background-position: -32px -96px; }
.ui-icon-document-b { background-position: -48px -96px; }
.ui-icon-note { background-position: -64px -96px; }
.ui-icon-mail-closed { background-position: -80px -96px; }
.ui-icon-mail-open { background-position: -96px -96px; }
.ui-icon-suitcase { background-position: -112px -96px; }
.ui-icon-comment { background-position: -128px -96px; }
.ui-icon-person { background-position: -144px -96px; }
.ui-icon-print { background-position: -160px -96px; }
.ui-icon-trash { background-position: -176px -96px; }
.ui-icon-locked { background-position: -192px -96px; }
.ui-icon-unlocked { background-position: -208px -96px; }
.ui-icon-bookmark { background-position: -224px -96px; }
.ui-icon-tag { background-position: -240px -96px; }
.ui-icon-home { background-position: 0 -112px; }
.ui-icon-flag { background-position: -16px -112px; }
.ui-icon-calendar { background-position: -32px -112px; }
.ui-icon-cart { background-position: -48px -112px; }
.ui-icon-pencil { background-position: -64px -112px; }
.ui-icon-clock { background-position: -80px -112px; }
.ui-icon-disk { background-position: -96px -112px; }
.ui-icon-calculator { background-position: -112px -112px; }
.ui-icon-zoomin { background-position: -128px -112px; }
.ui-icon-zoomout { background-position: -144px -112px; }
.ui-icon-search { background-position: -160px -112px; }
.ui-icon-wrench { background-position: -176px -112px; }
.ui-icon-gear { background-position: -192px -112px; }
.ui-icon-heart { background-position: -208px -112px; }
.ui-icon-star { background-position: -224px -112px; }
.ui-icon-link { background-position: -240px -112px; }
.ui-icon-cancel { background-position: 0 -128px; }
.ui-icon-plus { background-position: -16px -128px; }
.ui-icon-plusthick { background-position: -32px -128px; }
.ui-icon-minus { background-position: -48px -128px; }
.ui-icon-minusthick { background-position: -64px -128px; }
.ui-icon-close { background-position: -80px -128px; }
.ui-icon-closethick { background-position: -96px -128px; }
.ui-icon-key { background-position: -112px -128px; }
.ui-icon-lightbulb { background-position: -128px -128px; }
.ui-icon-scissors { background-position: -144px -128px; }
.ui-icon-clipboard { background-position: -160px -128px; }
.ui-icon-copy { background-position: -176px -128px; }
.ui-icon-contact { background-position: -192px -128px; }
.ui-icon-image { background-position: -208px -128px; }
.ui-icon-video { background-position: -224px -128px; }
.ui-icon-script { background-position: -240px -128px; }
.ui-icon-alert { background-position: 0 -144px; } /* Yello Error Icon*/
.ui-icon-info { background-position: -16px -144px; } /*Blue Info Icon*/
.ui-icon-notice { background-position: -32px -144px; }
.ui-icon-help { background-position: -48px -144px; }
.ui-icon-check { background-position: -64px -144px; }
.ui-icon-bullet { background-position: -80px -144px; }
.ui-icon-radio-on { background-position: -96px -144px; }
.ui-icon-radio-off { background-position: -112px -144px; }
.ui-icon-pin-w { background-position: -128px -144px; }
.ui-icon-pin-s { background-position: -144px -144px; }
.ui-icon-play { background-position: 0 -160px; }
.ui-icon-pause { background-position: -16px -160px; }
.ui-icon-seek-next { background-position: -32px -160px; }
.ui-icon-seek-prev { background-position: -48px -160px; }
.ui-icon-seek-end { background-position: -64px -160px; }
.ui-icon-seek-start { background-position: -80px -160px; }
/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
.ui-icon-seek-first { background-position: -80px -160px; }
.ui-icon-stop { background-position: -96px -160px; }
.ui-icon-eject { background-position: -112px -160px; }
.ui-icon-volume-off { background-position: -128px -160px; }
.ui-icon-volume-on { background-position: -144px -160px; }
.ui-icon-power { background-position: 0 -176px; }
.ui-icon-signal-diag { background-position: -16px -176px; }
.ui-icon-signal { background-position: -32px -176px; }
.ui-icon-battery-0 { background-position: -48px -176px; }
.ui-icon-battery-1 { background-position: -64px -176px; }
.ui-icon-battery-2 { background-position: -80px -176px; }
.ui-icon-battery-3 { background-position: -96px -176px; }
.ui-icon-circle-plus { background-position: 0 -192px; }
.ui-icon-circle-minus { background-position: -16px -192px; }
.ui-icon-circle-close { background-position: -32px -192px; } /*Fail Icon*/
.ui-icon-circle-triangle-e { background-position: -48px -192px; }
.ui-icon-circle-triangle-s { background-position: -64px -192px; }
.ui-icon-circle-triangle-w { background-position: -80px -192px; }
.ui-icon-circle-triangle-n { background-position: -96px -192px; }
.ui-icon-circle-arrow-e { background-position: -112px -192px; }
.ui-icon-circle-arrow-s { background-position: -128px -192px; }
.ui-icon-circle-arrow-w { background-position: -144px -192px; }
.ui-icon-circle-arrow-n { background-position: -160px -192px; }
.ui-icon-circle-zoomin { background-position: -176px -192px; }
.ui-icon-circle-zoomout { background-position: -192px -192px; }
.ui-icon-circle-check { background-position: -208px -192px; }/* Pass Icon */
.ui-icon-circlesmall-plus { background-position: 0 -208px; }
.ui-icon-circlesmall-minus { background-position: -16px -208px; }
.ui-icon-circlesmall-close { background-position: -32px -208px; }
.ui-icon-squaresmall-plus { background-position: -48px -208px; }
.ui-icon-squaresmall-minus { background-position: -64px -208px; }
.ui-icon-squaresmall-close { background-position: -80px -208px; }
.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
/* Misc visuals
----------------------------------*/
/* Corner radius */
.ui-corner-all,
.ui-corner-top,
.ui-corner-left,
.ui-corner-tl {
border-top-left-radius: 4px;
}
.ui-corner-all,
.ui-corner-top,
.ui-corner-right,
.ui-corner-tr {
border-top-right-radius: 4px;
}
.ui-corner-all,
.ui-corner-bottom,
.ui-corner-left,
.ui-corner-bl {
border-bottom-left-radius: 4px;
}
.ui-corner-all,
.ui-corner-bottom,
.ui-corner-right,
.ui-corner-br {
border-bottom-right-radius: 4px;
}
/* Overlays */
.ui-widget-overlay {
background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x;
opacity: .3;
filter: Alpha(Opacity=30); /* support: IE8 */
}
.ui-widget-shadow {
margin: -8px 0 0 -8px;
padding: 8px;
background: #aaaaaa url("images/ui-bg_flat_0_aaaaaa_40x100.png") 50% 50% repeat-x;
opacity: .3;
filter: Alpha(Opacity=30); /* support: IE8 */
border-radius: 8px;
}
| {
"pile_set_name": "Github"
} |
10 x=320:y=200
20 color=TEST(x,y)
30 PRINT "Pen color at"; x; y; "is"; color
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env sh
cd /opt/bullet
./App_ExampleBrowser
| {
"pile_set_name": "Github"
} |
import {isIdentifierStart, isIdentifierChar} from "./identifier"
import {types as tt, keywords as keywordTypes} from "./tokentype"
import {Parser} from "./state"
import {SourceLocation} from "./locutil"
import {lineBreak, lineBreakG, isNewLine, nonASCIIwhitespace} from "./whitespace"
// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.
export class Token {
constructor(p) {
this.type = p.type
this.value = p.value
this.start = p.start
this.end = p.end
if (p.options.locations)
this.loc = new SourceLocation(p, p.startLoc, p.endLoc)
if (p.options.ranges)
this.range = [p.start, p.end]
}
}
// ## Tokenizer
const pp = Parser.prototype
// Are we running under Rhino?
const isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]"
// Move to the next token
pp.next = function() {
if (this.options.onToken)
this.options.onToken(new Token(this))
this.lastTokEnd = this.end
this.lastTokStart = this.start
this.lastTokEndLoc = this.endLoc
this.lastTokStartLoc = this.startLoc
this.nextToken()
}
pp.getToken = function() {
this.next()
return new Token(this)
}
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
pp[Symbol.iterator] = function () {
let self = this
return {next: function () {
let token = self.getToken()
return {
done: token.type === tt.eof,
value: token
}
}}
}
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
pp.setStrict = function(strict) {
this.strict = strict
if (this.type !== tt.num && this.type !== tt.string) return
this.pos = this.start
if (this.options.locations) {
while (this.pos < this.lineStart) {
this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1
--this.curLine
}
}
this.nextToken()
}
pp.curContext = function() {
return this.context[this.context.length - 1]
}
// Read a single token, updating the parser object's token-related
// properties.
pp.nextToken = function() {
let curContext = this.curContext()
if (!curContext || !curContext.preserveSpace) this.skipSpace()
this.start = this.pos
if (this.options.locations) this.startLoc = this.curPosition()
if (this.pos >= this.input.length) return this.finishToken(tt.eof)
if (curContext.override) return curContext.override(this)
else this.readToken(this.fullCharCodeAtPos())
}
pp.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
return this.readWord()
return this.getTokenFromCode(code)
}
pp.fullCharCodeAtPos = function() {
let code = this.input.charCodeAt(this.pos)
if (code <= 0xd7ff || code >= 0xe000) return code
let next = this.input.charCodeAt(this.pos + 1)
return (code << 10) + next - 0x35fdc00
}
pp.skipBlockComment = function() {
let startLoc = this.options.onComment && this.curPosition()
let start = this.pos, end = this.input.indexOf("*/", this.pos += 2)
if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
this.pos = end + 2
if (this.options.locations) {
lineBreakG.lastIndex = start
let match
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this.curLine
this.lineStart = match.index + match[0].length
}
}
if (this.options.onComment)
this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition())
}
pp.skipLineComment = function(startSkip) {
let start = this.pos
let startLoc = this.options.onComment && this.curPosition()
let ch = this.input.charCodeAt(this.pos+=startSkip)
while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
++this.pos
ch = this.input.charCodeAt(this.pos)
}
if (this.options.onComment)
this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.curPosition())
}
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp.skipSpace = function() {
loop: while (this.pos < this.input.length) {
let ch = this.input.charCodeAt(this.pos)
switch (ch) {
case 32: case 160: // ' '
++this.pos
break
case 13:
if (this.input.charCodeAt(this.pos + 1) === 10) {
++this.pos
}
case 10: case 8232: case 8233:
++this.pos
if (this.options.locations) {
++this.curLine
this.lineStart = this.pos
}
break
case 47: // '/'
switch (this.input.charCodeAt(this.pos + 1)) {
case 42: // '*'
this.skipBlockComment()
break
case 47:
this.skipLineComment(2)
break
default:
break loop
}
break
default:
if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this.pos
} else {
break loop
}
}
}
}
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
pp.finishToken = function(type, val) {
this.end = this.pos
if (this.options.locations) this.endLoc = this.curPosition()
let prevType = this.type
this.type = type
this.value = val
this.updateContext(prevType)
}
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp.readToken_dot = function() {
let next = this.input.charCodeAt(this.pos + 1)
if (next >= 48 && next <= 57) return this.readNumber(true)
let next2 = this.input.charCodeAt(this.pos + 2)
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3
return this.finishToken(tt.ellipsis)
} else {
++this.pos
return this.finishToken(tt.dot)
}
}
pp.readToken_slash = function() { // '/'
let next = this.input.charCodeAt(this.pos + 1)
if (this.exprAllowed) {++this.pos; return this.readRegexp();}
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.slash, 1)
}
pp.readToken_mult_modulo = function(code) { // '%*'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(code === 42 ? tt.star : tt.modulo, 1)
}
pp.readToken_pipe_amp = function(code) { // '|&'
let next = this.input.charCodeAt(this.pos + 1)
if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)
}
pp.readToken_caret = function() { // '^'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.bitwiseXOR, 1)
}
pp.readToken_plus_min = function(code) { // '+-'
let next = this.input.charCodeAt(this.pos + 1)
if (next === code) {
if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
// A `-->` line comment
this.skipLineComment(3)
this.skipSpace()
return this.nextToken()
}
return this.finishOp(tt.incDec, 2)
}
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.plusMin, 1)
}
pp.readToken_lt_gt = function(code) { // '<>'
let next = this.input.charCodeAt(this.pos + 1)
let size = 1
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tt.bitShift, size)
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) this.unexpected()
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4)
this.skipSpace()
return this.nextToken()
}
if (next === 61)
size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2
return this.finishOp(tt.relational, size)
}
pp.readToken_eq_excl = function(code) { // '=!'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2)
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
this.pos += 2
return this.finishToken(tt.arrow)
}
return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1)
}
pp.getTokenFromCode = function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(tt.parenL)
case 41: ++this.pos; return this.finishToken(tt.parenR)
case 59: ++this.pos; return this.finishToken(tt.semi)
case 44: ++this.pos; return this.finishToken(tt.comma)
case 91: ++this.pos; return this.finishToken(tt.bracketL)
case 93: ++this.pos; return this.finishToken(tt.bracketR)
case 123: ++this.pos; return this.finishToken(tt.braceL)
case 125: ++this.pos; return this.finishToken(tt.braceR)
case 58: ++this.pos; return this.finishToken(tt.colon)
case 63: ++this.pos; return this.finishToken(tt.question)
case 96: // '`'
if (this.options.ecmaVersion < 6) break
++this.pos
return this.finishToken(tt.backQuote)
case 48: // '0'
let next = this.input.charCodeAt(this.pos + 1)
if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(tt.prefix, 1)
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'")
}
pp.finishOp = function(type, size) {
let str = this.input.slice(this.pos, this.pos + size)
this.pos += size
return this.finishToken(type, str)
}
// Parse a regular expression. Some context-awareness is necessary,
// since a '/' inside a '[]' set does not end the expression.
function tryCreateRegexp(src, flags, throwErrorAt, parser) {
try {
return new RegExp(src, flags);
} catch (e) {
if (throwErrorAt !== undefined) {
if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message)
throw e
}
}
}
var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
pp.readRegexp = function() {
let escaped, inClass, start = this.pos
for (;;) {
if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression")
let ch = this.input.charAt(this.pos)
if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression")
if (!escaped) {
if (ch === "[") inClass = true
else if (ch === "]" && inClass) inClass = false
else if (ch === "/" && !inClass) break
escaped = ch === "\\"
} else escaped = false
++this.pos
}
let content = this.input.slice(start, this.pos)
++this.pos
// Need to use `readWord1` because '\uXXXX' sequences are allowed
// here (don't ask).
let mods = this.readWord1()
let tmp = content
if (mods) {
let validFlags = /^[gim]*$/
if (this.options.ecmaVersion >= 6) validFlags = /^[gimuy]*$/
if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag")
if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
// Replace each astral symbol and every Unicode escape sequence that
// possibly represents an astral symbol or a paired surrogate with a
// single ASCII symbol to avoid throwing on regular expressions that
// are only valid in combination with the `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it would
// be replaced by `[x-b]` which throws an error.
tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, (_match, code, offset) => {
code = Number("0x" + code)
if (code > 0x10FFFF) this.raise(start + offset + 3, "Code point out of bounds")
return "x"
});
tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x")
}
}
// Detect invalid regular expressions.
let value = null
// Rhino's regular expression parser is flaky and throws uncatchable exceptions,
// so don't do detection if we are running under Rhino
if (!isRhino) {
tryCreateRegexp(tmp, undefined, start, this);
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
value = tryCreateRegexp(content, mods)
}
return this.finishToken(tt.regexp, {pattern: content, flags: mods, value: value})
}
// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.
pp.readInt = function(radix, len) {
let start = this.pos, total = 0
for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
let code = this.input.charCodeAt(this.pos), val
if (code >= 97) val = code - 97 + 10; // a
else if (code >= 65) val = code - 65 + 10; // A
else if (code >= 48 && code <= 57) val = code - 48; // 0-9
else val = Infinity
if (val >= radix) break
++this.pos
total = total * radix + val
}
if (this.pos === start || len != null && this.pos - start !== len) return null
return total
}
pp.readRadixNumber = function(radix) {
this.pos += 2; // 0x
let val = this.readInt(radix)
if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix)
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
return this.finishToken(tt.num, val)
}
// Read an integer, octal integer, or floating-point number.
pp.readNumber = function(startsWithDot) {
let start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48
if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number")
let next = this.input.charCodeAt(this.pos)
if (next === 46) { // '.'
++this.pos
this.readInt(10)
isFloat = true
next = this.input.charCodeAt(this.pos)
}
if (next === 69 || next === 101) { // 'eE'
next = this.input.charCodeAt(++this.pos)
if (next === 43 || next === 45) ++this.pos; // '+-'
if (this.readInt(10) === null) this.raise(start, "Invalid number")
isFloat = true
}
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
let str = this.input.slice(start, this.pos), val
if (isFloat) val = parseFloat(str)
else if (!octal || str.length === 1) val = parseInt(str, 10)
else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number")
else val = parseInt(str, 8)
return this.finishToken(tt.num, val)
}
// Read a string value, interpreting backslash-escapes.
pp.readCodePoint = function() {
let ch = this.input.charCodeAt(this.pos), code
if (ch === 123) {
if (this.options.ecmaVersion < 6) this.unexpected()
let codePos = ++this.pos
code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos)
++this.pos
if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds")
} else {
code = this.readHexChar(4)
}
return code
}
function codePointToString(code) {
// UTF-16 Decoding
if (code <= 0xFFFF) return String.fromCharCode(code)
code -= 0x10000
return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}
pp.readString = function(quote) {
let out = "", chunkStart = ++this.pos
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant")
let ch = this.input.charCodeAt(this.pos)
if (ch === quote) break
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos)
out += this.readEscapedChar(false)
chunkStart = this.pos
} else {
if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant")
++this.pos
}
}
out += this.input.slice(chunkStart, this.pos++)
return this.finishToken(tt.string, out)
}
// Reads template string tokens.
pp.readTmplToken = function() {
let out = "", chunkStart = this.pos
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template")
let ch = this.input.charCodeAt(this.pos)
if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
if (this.pos === this.start && this.type === tt.template) {
if (ch === 36) {
this.pos += 2
return this.finishToken(tt.dollarBraceL)
} else {
++this.pos
return this.finishToken(tt.backQuote)
}
}
out += this.input.slice(chunkStart, this.pos)
return this.finishToken(tt.template, out)
}
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos)
out += this.readEscapedChar(true)
chunkStart = this.pos
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos)
++this.pos
switch (ch) {
case 13:
if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
case 10:
out += "\n";
break;
default:
out += String.fromCharCode(ch);
break;
}
if (this.options.locations) {
++this.curLine
this.lineStart = this.pos
}
chunkStart = this.pos
} else {
++this.pos
}
}
}
// Used to read escaped characters
pp.readEscapedChar = function(inTemplate) {
let ch = this.input.charCodeAt(++this.pos)
++this.pos
switch (ch) {
case 110: return "\n"; // 'n' -> '\n'
case 114: return "\r"; // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)); // 'x'
case 117: return codePointToString(this.readCodePoint()); // 'u'
case 116: return "\t"; // 't' -> '\t'
case 98: return "\b"; // 'b' -> '\b'
case 118: return "\u000b"; // 'v' -> '\u000b'
case 102: return "\f"; // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine }
return ""
default:
if (ch >= 48 && ch <= 55) {
let octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]
let octal = parseInt(octalStr, 8)
if (octal > 255) {
octalStr = octalStr.slice(0, -1)
octal = parseInt(octalStr, 8)
}
if (octalStr !== "0" && (this.strict || inTemplate)) {
this.raise(this.pos - 2, "Octal literal in strict mode")
}
this.pos += octalStr.length - 1
return String.fromCharCode(octal)
}
return String.fromCharCode(ch)
}
}
// Used to read character escape sequences ('\x', '\u', '\U').
pp.readHexChar = function(len) {
let codePos = this.pos
let n = this.readInt(16, len)
if (n === null) this.raise(codePos, "Bad character escape sequence")
return n
}
// Read an identifier, and return it as a string. Sets `this.containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.
pp.readWord1 = function() {
this.containsEsc = false
let word = "", first = true, chunkStart = this.pos
let astral = this.options.ecmaVersion >= 6
while (this.pos < this.input.length) {
let ch = this.fullCharCodeAtPos()
if (isIdentifierChar(ch, astral)) {
this.pos += ch <= 0xffff ? 1 : 2
} else if (ch === 92) { // "\"
this.containsEsc = true
word += this.input.slice(chunkStart, this.pos)
let escStart = this.pos
if (this.input.charCodeAt(++this.pos) != 117) // "u"
this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX")
++this.pos
let esc = this.readCodePoint()
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
this.raise(escStart, "Invalid Unicode escape")
word += codePointToString(esc)
chunkStart = this.pos
} else {
break
}
first = false
}
return word + this.input.slice(chunkStart, this.pos)
}
// Read an identifier or keyword token. Will check for reserved
// words when necessary.
pp.readWord = function() {
let word = this.readWord1()
let type = tt.name
if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.keywords.test(word))
type = keywordTypes[word]
return this.finishToken(type, word)
}
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// *
// * Copyright (C) 2013 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: org.unicode.cldr.icu.NewLdml2IcuConverter
// * Source File: <path>/common/main/ebu.xml
// *
// ***************************************************************************
/**
* ICU <specials> source: <path>/xml/main/ebu.xml
*/
ebu{
Countries{
AD{"Andora"}
AE{"Falme za Kiarabu"}
AF{"Afuganistani"}
AG{"Antigua na Barbuda"}
AI{"Anguilla"}
AL{"Albania"}
AM{"Armenia"}
AN{"Antili za Uholanzi"}
AO{"Angola"}
AR{"Ajentina"}
AS{"Samoa ya Marekani"}
AT{"Austria"}
AU{"Australia"}
AW{"Aruba"}
AZ{"Azabajani"}
BA{"Bosnia na Hezegovina"}
BB{"Babadosi"}
BD{"Bangladeshi"}
BE{"Ubelgiji"}
BF{"Bukinafaso"}
BG{"Bulgaria"}
BH{"Bahareni"}
BI{"Burundi"}
BJ{"Benini"}
BM{"Bermuda"}
BN{"Brunei"}
BO{"Bolivia"}
BR{"Brazili"}
BS{"Bahama"}
BT{"Butani"}
BW{"Botswana"}
BY{"Belarusi"}
BZ{"Belize"}
CA{"Kanada"}
CD{"Jamhuri ya Kidemokrasia ya Kongo"}
CF{"Jamhuri ya Afrika ya Kati"}
CG{"Kongo"}
CH{"Uswisi"}
CI{"Kodivaa"}
CK{"Visiwa vya Cook"}
CL{"Chile"}
CM{"Kameruni"}
CN{"China"}
CO{"Kolombia"}
CR{"Kostarika"}
CU{"Kuba"}
CV{"Kepuvede"}
CY{"Kuprosi"}
CZ{"Jamhuri ya Cheki"}
DE{"Ujerumani"}
DJ{"Jibuti"}
DK{"Denmaki"}
DM{"Dominika"}
DO{"Jamhuri ya Dominika"}
DZ{"Aljeria"}
EC{"Ekwado"}
EE{"Estonia"}
EG{"Misri"}
ER{"Eritrea"}
ES{"Hispania"}
ET{"Uhabeshi"}
FI{"Ufini"}
FJ{"Fiji"}
FK{"Visiwa vya Falkland"}
FM{"Mikronesia"}
FR{"Ufaransa"}
GA{"Gaboni"}
GB{"Uingereza"}
GD{"Grenada"}
GE{"Jojia"}
GF{"Gwiyana ya Ufaransa"}
GH{"Ghana"}
GI{"Jibralta"}
GL{"Grinlandi"}
GM{"Gambia"}
GN{"Gine"}
GP{"Gwadelupe"}
GQ{"Ginekweta"}
GR{"Ugiriki"}
GT{"Gwatemala"}
GU{"Gwam"}
GW{"Ginebisau"}
GY{"Guyana"}
HN{"Hondurasi"}
HR{"Korasia"}
HT{"Haiti"}
HU{"Hungaria"}
ID{"Indonesia"}
IE{"Ayalandi"}
IL{"Israeli"}
IN{"India"}
IO{"Eneo la Uingereza katika Bahari Hindi"}
IQ{"Iraki"}
IR{"Uajemi"}
IS{"Aislandi"}
IT{"Italia"}
JM{"Jamaika"}
JO{"Yordani"}
JP{"Japani"}
KE{"Kenya"}
KG{"Kirigizistani"}
KH{"Kambodia"}
KI{"Kiribati"}
KM{"Komoro"}
KN{"Santakitzi na Nevis"}
KP{"Korea Kaskazini"}
KR{"Korea Kusini"}
KW{"Kuwaiti"}
KY{"Visiwa vya Kayman"}
KZ{"Kazakistani"}
LA{"Laosi"}
LB{"Lebanoni"}
LC{"Santalusia"}
LI{"Lishenteni"}
LK{"Sirilanka"}
LR{"Liberia"}
LS{"Lesoto"}
LT{"Litwania"}
LU{"Lasembagi"}
LV{"Lativia"}
LY{"Libya"}
MA{"Moroko"}
MC{"Monako"}
MD{"Moldova"}
MG{"Bukini"}
MH{"Visiwa vya Marshal"}
MK{"Masedonia"}
ML{"Mali"}
MM{"Myama"}
MN{"Mongolia"}
MP{"Visiwa vya Mariana vya Kaskazini"}
MQ{"Martiniki"}
MR{"Moritania"}
MS{"Montserrati"}
MT{"Malta"}
MU{"Morisi"}
MV{"Modivu"}
MW{"Malawi"}
MX{"Meksiko"}
MY{"Malesia"}
MZ{"Msumbiji"}
NA{"Namibia"}
NC{"Nyukaledonia"}
NE{"Nijeri"}
NF{"Kisiwa cha Norfok"}
NG{"Nijeria"}
NI{"Nikaragwa"}
NL{"Uholanzi"}
NO{"Norwe"}
NP{"Nepali"}
NR{"Nauru"}
NU{"Niue"}
NZ{"Nyuzilandi"}
OM{"Omani"}
PA{"Panama"}
PE{"Peru"}
PF{"Polinesia ya Ufaransa"}
PG{"Papua"}
PH{"Filipino"}
PK{"Pakistani"}
PL{"Polandi"}
PM{"Santapieri na Mikeloni"}
PN{"Pitkairni"}
PR{"Pwetoriko"}
PS{"Ukingo wa Magharibi na Ukanda wa Gaza wa Palestina"}
PT{"Ureno"}
PW{"Palau"}
PY{"Paragwai"}
QA{"Katari"}
RE{"Riyunioni"}
RO{"Romania"}
RU{"Urusi"}
RW{"Rwanda"}
SA{"Saudi"}
SB{"Visiwa vya Solomon"}
SC{"Shelisheli"}
SD{"Sudani"}
SE{"Uswidi"}
SG{"Singapoo"}
SH{"Santahelena"}
SI{"Slovenia"}
SK{"Slovakia"}
SL{"Siera Leoni"}
SM{"Samarino"}
SN{"Senegali"}
SO{"Somalia"}
SR{"Surinamu"}
ST{"Sao Tome na Principe"}
SV{"Elsavado"}
SY{"Siria"}
SZ{"Uswazi"}
TC{"Visiwa vya Turki na Kaiko"}
TD{"Chadi"}
TG{"Togo"}
TH{"Tailandi"}
TJ{"Tajikistani"}
TK{"Tokelau"}
TL{"Timori ya Mashariki"}
TM{"Turukimenistani"}
TN{"Tunisia"}
TO{"Tonga"}
TR{"Uturuki"}
TT{"Trinidad na Tobago"}
TV{"Tuvalu"}
TW{"Taiwani"}
TZ{"Tanzania"}
UA{"Ukraini"}
UG{"Uganda"}
US{"Marekani"}
UY{"Urugwai"}
UZ{"Uzibekistani"}
VA{"Vatikani"}
VC{"Santavisenti na Grenadini"}
VE{"Venezuela"}
VG{"Visiwa vya Virgin vya Uingereza"}
VI{"Visiwa vya Virgin vya Marekani"}
VN{"Vietinamu"}
VU{"Vanuatu"}
WF{"Walis na Futuna"}
WS{"Samoa"}
YE{"Yemeni"}
YT{"Mayotte"}
ZA{"Afrika Kusini"}
ZM{"Zambia"}
ZW{"Zimbabwe"}
}
Version{"2.0.82.45"}
}
| {
"pile_set_name": "Github"
} |
from unittest import TestCase
from mock import Mock
from qrl.core.MessageRequest import MessageRequest
class TestMessageRequest(TestCase):
def setUp(self):
self.mr = MessageRequest()
self.test_data = {
"camel": "animal",
"bitcoin": "cryptocoin"
}
def test_validate(self):
# MessageRequest.validate() simply make sure self.params and an arg are the same dict.
# MessageRequest.params is None
result = self.mr.validate(self.test_data)
self.assertFalse(result)
# MessageRequest.params is the same as the argument
self.mr.params = self.test_data
result = self.mr.validate(self.test_data)
self.assertTrue(result)
# MessageRequest.params is missing a key compared to the argument
self.mr.params = {"bitcoin": "cryptocoin"}
result = self.mr.validate(self.test_data)
self.assertTrue(result)
self.mr.params = self.test_data
# the argument is missing a key that MessageRequest.params has
result = self.mr.validate({})
self.assertFalse(result)
# the argument has different data from MessageRequest.params
result = self.mr.validate({"camel": "cryptocoin", "bitcoin": "animal"})
self.assertFalse(result)
def test_add_peer(self):
msg_type = Mock(name='mock Message Type')
peer = Mock(name='mock P2PProtocol')
self.mr.add_peer(msg_type, peer, params=self.test_data)
self.assertEqual(self.mr.params, self.test_data)
self.assertEqual(self.mr.msg_type, msg_type)
self.assertEqual(self.mr.peers_connection_list, [peer])
| {
"pile_set_name": "Github"
} |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2014 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file close_code.h
*
* This file reverses the effects of begin_code.h and should be included
* after you finish any function and structure declarations in your headers
*/
#undef _begin_code_h
/* Reset structure packing at previous byte alignment */
#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__WATCOMC__) || defined(__BORLANDC__)
#ifdef __BORLANDC__
#pragma nopackwarning
#endif
#pragma pack(pop)
#endif /* Compiler needs structure packing set */
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Functions for directly invoking mmap() via syscall, avoiding the case where
// mmap() has been locally overridden.
#ifndef ABSL_BASE_INTERNAL_DIRECT_MMAP_H_
#define ABSL_BASE_INTERNAL_DIRECT_MMAP_H_
#include "absl/base/config.h"
#if ABSL_HAVE_MMAP
#include <sys/mman.h>
#ifdef __linux__
#include <sys/types.h>
#ifdef __BIONIC__
#include <sys/syscall.h>
#else
#include <syscall.h>
#endif
#include <linux/unistd.h>
#include <unistd.h>
#include <cerrno>
#include <cstdarg>
#include <cstdint>
#ifdef __mips__
// Include definitions of the ABI currently in use.
#ifdef __BIONIC__
// Android doesn't have sgidefs.h, but does have asm/sgidefs.h, which has the
// definitions we need.
#include <asm/sgidefs.h>
#else
#include <sgidefs.h>
#endif // __BIONIC__
#endif // __mips__
// SYS_mmap and SYS_munmap are not defined in Android.
#ifdef __BIONIC__
extern "C" void* __mmap2(void*, size_t, int, int, int, size_t);
#if defined(__NR_mmap) && !defined(SYS_mmap)
#define SYS_mmap __NR_mmap
#endif
#ifndef SYS_munmap
#define SYS_munmap __NR_munmap
#endif
#endif // __BIONIC__
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
// Platform specific logic extracted from
// https://chromium.googlesource.com/linux-syscall-support/+/master/linux_syscall_support.h
inline void* DirectMmap(void* start, size_t length, int prot, int flags, int fd,
off64_t offset) noexcept {
#if defined(__i386__) || defined(__ARM_ARCH_3__) || defined(__ARM_EABI__) || \
(defined(__mips__) && _MIPS_SIM == _MIPS_SIM_ABI32) || \
(defined(__PPC__) && !defined(__PPC64__)) || \
(defined(__s390__) && !defined(__s390x__))
// On these architectures, implement mmap with mmap2.
static int pagesize = 0;
if (pagesize == 0) {
#if defined(__wasm__) || defined(__asmjs__)
pagesize = getpagesize();
#else
pagesize = sysconf(_SC_PAGESIZE);
#endif
}
if (offset < 0 || offset % pagesize != 0) {
errno = EINVAL;
return MAP_FAILED;
}
#ifdef __BIONIC__
// SYS_mmap2 has problems on Android API level <= 16.
// Workaround by invoking __mmap2() instead.
return __mmap2(start, length, prot, flags, fd, offset / pagesize);
#else
return reinterpret_cast<void*>(
syscall(SYS_mmap2, start, length, prot, flags, fd,
static_cast<off_t>(offset / pagesize)));
#endif
#elif defined(__s390x__)
// On s390x, mmap() arguments are passed in memory.
unsigned long buf[6] = {reinterpret_cast<unsigned long>(start), // NOLINT
static_cast<unsigned long>(length), // NOLINT
static_cast<unsigned long>(prot), // NOLINT
static_cast<unsigned long>(flags), // NOLINT
static_cast<unsigned long>(fd), // NOLINT
static_cast<unsigned long>(offset)}; // NOLINT
return reinterpret_cast<void*>(syscall(SYS_mmap, buf));
#elif defined(__x86_64__)
// The x32 ABI has 32 bit longs, but the syscall interface is 64 bit.
// We need to explicitly cast to an unsigned 64 bit type to avoid implicit
// sign extension. We can't cast pointers directly because those are
// 32 bits, and gcc will dump ugly warnings about casting from a pointer
// to an integer of a different size. We also need to make sure __off64_t
// isn't truncated to 32-bits under x32.
#define MMAP_SYSCALL_ARG(x) ((uint64_t)(uintptr_t)(x))
return reinterpret_cast<void*>(
syscall(SYS_mmap, MMAP_SYSCALL_ARG(start), MMAP_SYSCALL_ARG(length),
MMAP_SYSCALL_ARG(prot), MMAP_SYSCALL_ARG(flags),
MMAP_SYSCALL_ARG(fd), static_cast<uint64_t>(offset)));
#undef MMAP_SYSCALL_ARG
#else // Remaining 64-bit aritectures.
static_assert(sizeof(unsigned long) == 8, "Platform is not 64-bit");
return reinterpret_cast<void*>(
syscall(SYS_mmap, start, length, prot, flags, fd, offset));
#endif
}
inline int DirectMunmap(void* start, size_t length) {
return static_cast<int>(syscall(SYS_munmap, start, length));
}
} // namespace base_internal
ABSL_NAMESPACE_END
} // namespace absl
#else // !__linux__
// For non-linux platforms where we have mmap, just dispatch directly to the
// actual mmap()/munmap() methods.
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
inline void* DirectMmap(void* start, size_t length, int prot, int flags, int fd,
off_t offset) {
return mmap(start, length, prot, flags, fd, offset);
}
inline int DirectMunmap(void* start, size_t length) {
return munmap(start, length);
}
} // namespace base_internal
ABSL_NAMESPACE_END
} // namespace absl
#endif // __linux__
#endif // ABSL_HAVE_MMAP
#endif // ABSL_BASE_INTERNAL_DIRECT_MMAP_H_
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* Deserializing an enum valued object
*/
public class EnumDeserializer extends AbstractDeserializer {
private Class _enumType;
private Method _valueOf;
public EnumDeserializer(Class cl)
{
// hessian/33b[34], hessian/3bb[78]
if (cl.isEnum())
_enumType = cl;
else if (cl.getSuperclass().isEnum())
_enumType = cl.getSuperclass();
else
throw new RuntimeException("Class " + cl.getName() + " is not an enum");
try {
_valueOf = _enumType.getMethod("valueOf",
new Class[] { Class.class, String.class });
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Class getType()
{
return _enumType;
}
public Object readMap(AbstractHessianInput in)
throws IOException
{
String name = null;
while (! in.isEnd()) {
String key = in.readString();
if (key.equals("name"))
name = in.readString();
else
in.readObject();
}
in.readMapEnd();
Object obj = create(name);
in.addRef(obj);
return obj;
}
@Override
public Object readObject(AbstractHessianInput in, Object []fields)
throws IOException
{
String []fieldNames = (String []) fields;
String name = null;
for (int i = 0; i < fieldNames.length; i++) {
if ("name".equals(fieldNames[i]))
name = in.readString();
else
in.readObject();
}
Object obj = create(name);
in.addRef(obj);
return obj;
}
private Object create(String name)
throws IOException
{
if (name == null)
throw new IOException(_enumType.getName() + " expects name.");
try {
return _valueOf.invoke(null, _enumType, name);
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
}
| {
"pile_set_name": "Github"
} |
Zlib in yo' browser.
| {
"pile_set_name": "Github"
} |
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\Barryvdh\Cors\HandleCors::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
'auth:api',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
<true/>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<doc>
<assembly>
<name>Microsoft.CodeDom.Providers.DotNetCompilerPlatform</name>
</assembly>
<members>
<member name="T:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider">
<summary>
Provides access to instances of the .NET Compiler Platform C# code generator and code compiler.
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider.#ctor">
<summary>
Default Constructor
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider.CreateCompiler">
<summary>
Gets an instance of the .NET Compiler Platform C# code compiler.
</summary>
<returns>An instance of the .NET Compiler Platform C# code compiler</returns>
</member>
<member name="T:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider">
<summary>
Provides access to instances of the .NET Compiler Platform VB code generator and code compiler.
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider.#ctor">
<summary>
Default Constructor
</summary>
</member>
<member name="M:Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider.CreateCompiler">
<summary>
Gets an instance of the .NET Compiler Platform VB code compiler.
</summary>
<returns>An instance of the .NET Compiler Platform VB code compiler</returns>
</member>
</members>
</doc>
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
// expected-no-diagnostics
template<typename T> int &f0(T&);
template<typename T> float &f0(T&&);
// Core issue 1164
void test_f0(int i) {
int &ir0 = f0(i);
float &fr0 = f0(5);
}
| {
"pile_set_name": "Github"
} |
# Copyright (c) Yiming Wang
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass, field
from omegaconf import II
from typing import List
import torch.optim.lr_scheduler
from fairseq.dataclass.utils import FairseqDataclass
from fairseq.optim.lr_scheduler import register_lr_scheduler
from fairseq.optim.lr_scheduler.reduce_lr_on_plateau import ReduceLROnPlateau
@dataclass
class ReduceLROnPlateauV2Config(FairseqDataclass):
lr_shrink: float = field(
default=0.1,
metadata={"help": "shrink factor for annealing, lr_new = (lr * lr_shrink)"},
)
lr_threshold: float = field(
default=1e-4,
metadata={
"help": "threshold for measuring the new optimum, to only focus on significant changes"
},
)
lr_patience: int = field(
default=0,
metadata={
"help": "number of epochs with no improvement after which learning rate will be reduced"
},
)
warmup_updates: int = field(
default=0,
metadata={"help": "warmup the learning rate linearly for the first N updates"},
)
warmup_init_lr: float = field(
default=-1,
metadata={
"help": "initial learning rate during warmup phase; default is args.lr"
},
)
final_lr_scale: float = field(
default=0.01,
metadata={"help": "final learning rate scale; default to 0.01"},
)
start_reduce_lr_epoch: int = field(
default=0,
metadata={"help": "start to reduce lr from the specified epoch"},
)
# TODO common vars at parent class
lr: List[float] = II("params.optimization.lr")
@register_lr_scheduler('reduce_lr_on_plateau_v2')
class ReduceLROnPlateauV2(ReduceLROnPlateau):
"""Decay the LR by a factor every time the validation loss plateaus, starting
from the epoch specified as args.start_reduce_lr_epoch.
We also support specifying a final lr which will be kept until the max number
of epochs is reached.
"""
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
self.lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
self.optimizer.optimizer, patience=args.lr_patience, factor=args.lr_shrink,
mode='max' if args.maximize_best_checkpoint_metric else 'min',
threshold=args.lr_threshold, min_lr=args.final_lr_scale * args.lr[0]
)
@staticmethod
def add_args(parser):
"""Add arguments to the parser for this LR scheduler."""
ReduceLROnPlateau.add_args(parser)
# fmt: off
parser.add_argument('--final-lr-scale', default=0.01, type=float, metavar='N',
help='final learning rate scale; default to 0.01')
parser.add_argument('--start-reduce-lr-epoch', default=0, type=int, metavar='N',
help='start to reduce lr from the specified epoch')
# fmt: on
def step(self, epoch, val_loss=None):
if epoch < self.args.start_reduce_lr_epoch:
self.lr_scheduler.last_epoch = epoch
self.optimizer.set_lr(self.args.lr[0])
return self.optimizer.get_lr()
return super().step(epoch, val_loss)
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?><metadata>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.0.4-SNAPSHOT</version>
<versioning>
<snapshot>
<localCopy>true</localCopy>
</snapshot>
<lastUpdated>20070427033345</lastUpdated>
</versioning>
</metadata> | {
"pile_set_name": "Github"
} |
University of Holy Quran and Islamic Siences
| {
"pile_set_name": "Github"
} |
{
"desc": "Option GTM380",
"control": 1,
"data": 0
}
| {
"pile_set_name": "Github"
} |
import React from 'react'
import styled from 'styled-components'
import Page from 'comps/Page/Page'
import readme from 'ui-src/components/EthIdenticon/README.md'
import { EthIdenticon } from '@aragon/ui'
import Container from '../components/Page/DemoContainer'
const ADDRESS = '0xcafE1A77e83698c83CA8931F54A755176eF75f2d'
const PageBadgeNumber = ({ title }) => (
<Page title={title} readme={readme}>
<Page.Demo opaque height={200}>
<Container centered css="height: 100vh">
<EthIdenticonRow>
<div>
<EthIdenticon address={ADDRESS} />
</div>
<div>
<EthIdenticon address={ADDRESS} scale={2} radius={25} />
</div>
<div>
<EthIdenticon address={ADDRESS} radius={8} scale={3} soften={0.7} />
</div>
</EthIdenticonRow>
</Container>
</Page.Demo>
</Page>
)
const EthIdenticonRow = styled.div`
display: flex;
align-items: center;
& > div {
display: flex;
align-items: center;
margin-right: 20px;
}
`
export default PageBadgeNumber
| {
"pile_set_name": "Github"
} |
// -----------------------------------------------------------------------
// <copyright file="FunctionAuthorizationManagerBase.cs" company="OSharp开源团队">
// Copyright (c) 2014-2020 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2020-02-26 23:05</last-date>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using OSharp.Authorization.Dtos;
using OSharp.Authorization.Entities;
using OSharp.Authorization.Events;
using OSharp.Authorization.Functions;
using OSharp.Collections;
using OSharp.Data;
using OSharp.Entity;
using OSharp.EventBuses;
using OSharp.Exceptions;
using OSharp.Extensions;
using OSharp.Identity.Entities;
using OSharp.Mapping;
namespace OSharp.Authorization
{
/// <summary>
/// 功能权限管理器基类
/// </summary>
/// <typeparam name="TFunction">功能类型</typeparam>
/// <typeparam name="TFunctionInputDto">功能输入DTO类型</typeparam>
/// <typeparam name="TModule">模块类型</typeparam>
/// <typeparam name="TModuleInputDto">模块输入类型</typeparam>
/// <typeparam name="TModuleKey">模块编号类型</typeparam>
/// <typeparam name="TModuleFunction">模块功能类型</typeparam>
/// <typeparam name="TModuleRole">模块角色类型</typeparam>
/// <typeparam name="TModuleUser">模块用户类型</typeparam>
/// <typeparam name="TUserRole">用户角色类型</typeparam>
/// <typeparam name="TUserRoleKey">用户角色编号类型</typeparam>
/// <typeparam name="TRole">角色类型</typeparam>
/// <typeparam name="TRoleKey">角色编号类型</typeparam>
/// <typeparam name="TUser">用户类型</typeparam>
/// <typeparam name="TUserKey">用户编号类型</typeparam>
public abstract class FunctionAuthorizationManagerBase<TFunction, TFunctionInputDto, TModule, TModuleInputDto, TModuleKey,
TModuleFunction, TModuleRole, TModuleUser, TUserRole, TUserRoleKey, TRole, TRoleKey, TUser, TUserKey>
: IFunctionStore<TFunction, TFunctionInputDto>,
IModuleStore<TModule, TModuleInputDto, TModuleKey>,
IModuleFunctionStore<TModuleFunction, TModuleKey>,
IModuleRoleStore<TModuleRole, TRoleKey, TModuleKey>,
IModuleUserStore<TModuleUser, TUserKey, TModuleKey>
where TFunction : IFunction
where TFunctionInputDto : FunctionInputDtoBase
where TModule : ModuleBase<TModuleKey>
where TModuleInputDto : ModuleInputDtoBase<TModuleKey>
where TModuleFunction : ModuleFunctionBase<TModuleKey>, new()
where TModuleRole : ModuleRoleBase<TModuleKey, TRoleKey>, new()
where TModuleUser : ModuleUserBase<TModuleKey, TUserKey>, new()
where TModuleKey : struct, IEquatable<TModuleKey>
where TUserRole : UserRoleBase<TUserRoleKey, TUserKey, TRoleKey>
where TUserRoleKey : IEquatable<TUserRoleKey>
where TRole : RoleBase<TRoleKey>
where TUser : UserBase<TUserKey>
where TRoleKey : IEquatable<TRoleKey>
where TUserKey : IEquatable<TUserKey>
{
private readonly IServiceProvider _provider;
/// <summary>
/// 初始化一个 SecurityManager 类型的新实例
/// </summary>
/// <param name="provider">服务提供程序</param>
protected FunctionAuthorizationManagerBase(IServiceProvider provider)
{
_provider = provider;
}
#region 属性
/// <summary>
/// 获取 事件总线
/// </summary>
protected IEventBus EventBus => _provider.GetService<IEventBus>();
/// <summary>
/// 获取 功能仓储
/// </summary>
protected IRepository<TFunction, Guid> FunctionRepository => _provider.GetService<IRepository<TFunction, Guid>>();
/// <summary>
/// 获取 模块仓储
/// </summary>
protected IRepository<TModule, TModuleKey> ModuleRepository => _provider.GetService<IRepository<TModule, TModuleKey>>();
/// <summary>
/// 获取 模块功能仓储
/// </summary>
protected IRepository<TModuleFunction, Guid> ModuleFunctionRepository => _provider.GetService<IRepository<TModuleFunction, Guid>>();
/// <summary>
/// 获取 模块角色仓储
/// </summary>
protected IRepository<TModuleRole, Guid> ModuleRoleRepository => _provider.GetService<IRepository<TModuleRole, Guid>>();
/// <summary>
/// 获取 模块用户仓储
/// </summary>
protected IRepository<TModuleUser, Guid> ModuleUserRepository => _provider.GetService<IRepository<TModuleUser, Guid>>();
/// <summary>
/// 获取 用户角色仓储
/// </summary>
protected IRepository<TUserRole, TUserRoleKey> UserRoleRepository => _provider.GetService<IRepository<TUserRole, TUserRoleKey>>();
/// <summary>
/// 获取 角色仓储
/// </summary>
protected IRepository<TRole, TRoleKey> RoleRepository => _provider.GetService<IRepository<TRole, TRoleKey>>();
/// <summary>
/// 获取 用户仓储
/// </summary>
protected IRepository<TUser, TUserKey> UserRepository => _provider.GetService<IRepository<TUser, TUserKey>>();
#endregion
#region Implementation of IFunctionStore<TFunction,in TFunctionInputDto>
/// <summary>
/// 获取 功能信息查询数据集
/// </summary>
public IQueryable<TFunction> Functions => FunctionRepository.QueryAsNoTracking();
/// <summary>
/// 检查功能信息是否存在
/// </summary>
/// <param name="predicate">检查谓语表达式</param>
/// <param name="id">更新的功能信息编号</param>
/// <returns>功能信息是否存在</returns>
public virtual Task<bool> CheckFunctionExists(Expression<Func<TFunction, bool>> predicate, Guid id = default(Guid))
{
return FunctionRepository.CheckExistsAsync(predicate, id);
}
/// <summary>
/// 更新功能信息
/// </summary>
/// <param name="dtos">包含更新信息的功能信息DTO信息</param>
/// <returns>业务操作结果</returns>
public virtual async Task<OperationResult> UpdateFunctions(params TFunctionInputDto[] dtos)
{
Check.Validate<TFunctionInputDto, Guid>(dtos, nameof(dtos));
OperationResult result = await FunctionRepository.UpdateAsync(dtos,
(dto, entity) =>
{
if (dto.IsLocked && entity.Area == "Admin" && entity.Controller == "Function"
&& (entity.Action == "Update" || entity.Action == "Read"))
{
throw new OsharpException($"功能信息“{entity.Name}”不能锁定");
}
if (dto.AuditEntityEnabled && !dto.AuditOperationEnabled && !entity.AuditOperationEnabled && !entity.AuditEntityEnabled)
{
dto.AuditOperationEnabled = true;
}
else if (!dto.AuditOperationEnabled && dto.AuditEntityEnabled && entity.AuditOperationEnabled && entity.AuditEntityEnabled)
{
dto.AuditEntityEnabled = false;
}
if (dto.AccessType != entity.AccessType)
{
entity.IsAccessTypeChanged = true;
}
return Task.FromResult(0);
});
if (result.Succeeded)
{
//功能信息缓存刷新事件
FunctionCacheRefreshEventData clearEventData = new FunctionCacheRefreshEventData();
EventBus.Publish(clearEventData);
//功能权限缓存刷新事件
FunctionAuthCacheRefreshEventData removeEventData = new FunctionAuthCacheRefreshEventData()
{
FunctionIds = dtos.Select(m => m.Id).ToArray()
};
EventBus.Publish(removeEventData);
}
return result;
}
#endregion Implementation of IFunctionStore<TFunction,in TFunctionInputDto>
#region Implementation of IModuleStore<TModule,in TModuleInputDto,in TModuleKey>
/// <summary>
/// 获取 模块信息查询数据集
/// </summary>
public IQueryable<TModule> Modules => ModuleRepository.QueryAsNoTracking();
/// <summary>
/// 检查模块信息是否存在
/// </summary>
/// <param name="predicate">检查谓语表达式</param>
/// <param name="id">更新的模块信息编号</param>
/// <returns>模块信息是否存在</returns>
public virtual Task<bool> CheckModuleExists(Expression<Func<TModule, bool>> predicate, TModuleKey id = default(TModuleKey))
{
return ModuleRepository.CheckExistsAsync(predicate, id);
}
/// <summary>
/// 添加模块信息
/// </summary>
/// <param name="dto">要添加的模块信息DTO信息</param>
/// <returns>业务操作结果</returns>
public virtual async Task<OperationResult> CreateModule(TModuleInputDto dto)
{
const string treePathItemFormat = "${0}$";
Check.NotNull(dto, nameof(dto));
if (dto.Name.Contains('.'))
{
return new OperationResult(OperationResultType.Error, $"模块名称“{dto.Name}”不能包含字符“-”");
}
var exist = Modules.Where(m => m.Name == dto.Name && m.ParentId != null && m.ParentId.Equals(dto.ParentId))
.SelectMany(m => Modules.Where(n => n.Id.Equals(m.ParentId)).Select(n => n.Name)).FirstOrDefault();
if (exist != null)
{
return new OperationResult(OperationResultType.Error, $"模块“{exist}”中已存在名称为“{dto.Name}”的子模块,不能重复添加。");
}
exist = Modules.Where(m => m.Code == dto.Code && m.ParentId != null && m.ParentId.Equals(dto.ParentId))
.SelectMany(m => Modules.Where(n => n.Id.Equals(m.ParentId)).Select(n => n.Name)).FirstOrDefault();
if (exist != null)
{
return new OperationResult(OperationResultType.Error, $"模块“{exist}”中已存在代码为“{dto.Code}”的子模块,不能重复添加。");
}
TModule entity = dto.MapTo<TModule>();
//排序码,不存在为1,否则同级最大+1
var peerModules = Modules.Where(m => m.ParentId.Equals(dto.ParentId)).Select(m => new { m.OrderCode }).ToArray();
if (peerModules.Length == 0)
{
entity.OrderCode = 1;
}
else
{
double maxCode = peerModules.Max(m => m.OrderCode);
entity.OrderCode = maxCode + 1;
}
//父模块
string parentTreePathString = null;
if (!Equals(dto.ParentId, default(TModuleKey)))
{
var parent = Modules.Where(m => m.Id.Equals(dto.ParentId)).Select(m => new { m.Id, m.TreePathString }).FirstOrDefault();
if (parent == null)
{
return new OperationResult(OperationResultType.Error, $"编号为“{dto.ParentId}”的父模块信息不存在");
}
entity.ParentId = dto.ParentId;
parentTreePathString = parent.TreePathString;
}
else
{
entity.ParentId = null;
}
if (await ModuleRepository.InsertAsync(entity) > 0)
{
entity.TreePathString = entity.ParentId == null
? treePathItemFormat.FormatWith(entity.Id)
: GetModuleTreePath(entity.Id, parentTreePathString, treePathItemFormat);
await ModuleRepository.UpdateAsync(entity);
return new OperationResult(OperationResultType.Success, $"模块“{dto.Name}”创建成功");
}
return OperationResult.NoChanged;
}
/// <summary>
/// 更新模块信息
/// </summary>
/// <param name="dto">包含更新信息的模块信息DTO信息</param>
/// <returns>业务操作结果</returns>
public virtual async Task<OperationResult> UpdateModule(TModuleInputDto dto)
{
const string treePathItemFormat = "${0}$";
Check.NotNull(dto, nameof(dto));
if (dto.Name.Contains('.'))
{
return new OperationResult(OperationResultType.Error, $"模块名称“{dto.Name}”不能包含字符“-”");
}
var exist1 = Modules.Where(m => m.Name == dto.Name && m.ParentId != null && m.ParentId.Equals(dto.ParentId) && !m.Id.Equals(dto.Id))
.SelectMany(m => Modules.Where(n => n.Id.Equals(m.ParentId)).Select(n => new { n.Id, n.Name })).FirstOrDefault();
if (exist1 != null)
{
return new OperationResult(OperationResultType.Error, $"模块“{exist1.Name}”中已存在名称为“{dto.Name}”的子模块,不能重复添加。");
}
var exist2 = Modules.Where(m => m.Code == dto.Code && m.ParentId != null && m.ParentId.Equals(dto.ParentId) && !m.Id.Equals(dto.Id))
.SelectMany(m => Modules.Where(n => n.Id.Equals(m.ParentId)).Select(n => new { n.Id, n.Name })).FirstOrDefault();
if (exist2 != null)
{
return new OperationResult(OperationResultType.Error, $"模块“{exist2.Name}”中已存在代码为“{dto.Code}”的子模块,不能重复添加。");
}
TModule entity = await ModuleRepository.GetAsync(dto.Id);
if (entity == null)
{
return new OperationResult(OperationResultType.Error, $"编号为“{dto.Id}”的模块信息不存在。");
}
entity = dto.MapTo(entity);
if (!Equals(dto.ParentId, default(TModuleKey)))
{
if (!entity.ParentId.Equals(dto.ParentId))
{
var parent = Modules.Where(m => m.Id.Equals(dto.ParentId)).Select(m => new { m.Id, m.TreePathString }).FirstOrDefault();
if (parent == null)
{
return new OperationResult(OperationResultType.Error, $"编号为“{dto.ParentId}”的父模块信息不存在");
}
entity.ParentId = dto.ParentId;
entity.TreePathString = GetModuleTreePath(entity.Id, parent.TreePathString, treePathItemFormat);
}
}
else
{
entity.ParentId = null;
entity.TreePathString = treePathItemFormat.FormatWith(entity.Id);
}
return await ModuleRepository.UpdateAsync(entity) > 0
? new OperationResult(OperationResultType.Success, $"模块“{dto.Name}”更新成功")
: OperationResult.NoChanged;
}
/// <summary>
/// 删除模块信息
/// </summary>
/// <param name="id">要删除的模块信息编号</param>
/// <returns>业务操作结果</returns>
public virtual async Task<OperationResult> DeleteModule(TModuleKey id)
{
TModule entity = await ModuleRepository.GetAsync(id);
if (entity == null)
{
return OperationResult.Success;
}
if (await ModuleRepository.CheckExistsAsync(m => m.ParentId.Equals(id)))
{
return new OperationResult(OperationResultType.Error, $"模块“{entity.Name}”的子模块不为空,不能删除");
}
//清除附属引用
await ModuleFunctionRepository.DeleteBatchAsync(m => m.ModuleId.Equals(id));
await ModuleRoleRepository.DeleteBatchAsync(m => m.ModuleId.Equals(id));
await ModuleUserRepository.DeleteBatchAsync(m => m.ModuleId.Equals(id));
OperationResult result = await ModuleRepository.DeleteAsync(entity) > 0
? new OperationResult(OperationResultType.Success, $"模块“{entity.Name}”删除成功")
: OperationResult.NoChanged;
if (result.Succeeded)
{
//功能权限缓存刷新事件
Guid[] functionIds = ModuleFunctionRepository.QueryAsNoTracking(m => m.Id.Equals(id)).Select(m => m.FunctionId).ToArray();
FunctionAuthCacheRefreshEventData removeEventData = new FunctionAuthCacheRefreshEventData() { FunctionIds = functionIds };
EventBus.Publish(removeEventData);
}
return result;
}
/// <summary>
/// 获取树节点及其子节点的所有模块编号
/// </summary>
/// <param name="rootIds">树节点</param>
/// <returns>模块编号集合</returns>
public virtual TModuleKey[] GetModuleTreeIds(params TModuleKey[] rootIds)
{
return rootIds.SelectMany(m => ModuleRepository.QueryAsNoTracking(n => n.TreePathString.Contains($"${m}$")).Select(n => n.Id)).Distinct()
.ToArray();
}
private static string GetModuleTreePath(TModuleKey currentId, string parentTreePath, string treePathItemFormat)
{
return $"{parentTreePath},{treePathItemFormat.FormatWith(currentId)}";
}
#endregion Implementation of IModuleStore<TModule,in TModuleInputDto,in TModuleKey>
#region Implementation of IModuleFunctionStore<TModuleFunction>
/// <summary>
/// 获取 模块功能信息查询数据集
/// </summary>
public IQueryable<TModuleFunction> ModuleFunctions => ModuleFunctionRepository.QueryAsNoTracking();
/// <summary>
/// 检查模块功能信息是否存在
/// </summary>
/// <param name="predicate">检查谓语表达式</param>
/// <param name="id">更新的模块功能信息编号</param>
/// <returns>模块功能信息是否存在</returns>
public virtual Task<bool> CheckModuleFunctionExists(Expression<Func<TModuleFunction, bool>> predicate, Guid id = default(Guid))
{
return ModuleFunctionRepository.CheckExistsAsync(predicate, id);
}
/// <summary>
/// 设置模块的功能信息
/// </summary>
/// <param name="moduleId">模块编号</param>
/// <param name="functionIds">要设置的功能编号</param>
/// <returns>业务操作结果</returns>
public virtual async Task<OperationResult> SetModuleFunctions(TModuleKey moduleId, Guid[] functionIds)
{
TModule module = await ModuleRepository.GetAsync(moduleId);
if (module == null)
{
return new OperationResult(OperationResultType.QueryNull, $"编号为“{moduleId}”的模块信息不存在");
}
Guid[] existFunctionIds = ModuleFunctionRepository.QueryAsNoTracking(m => m.ModuleId.Equals(moduleId)).Select(m => m.FunctionId).ToArray();
Guid[] addFunctionIds = functionIds.Except(existFunctionIds).ToArray();
Guid[] removeFunctionIds = existFunctionIds.Except(functionIds).ToArray();
List<string> addNames = new List<string>(), removeNames = new List<string>();
int count = 0;
foreach (Guid functionId in addFunctionIds)
{
TFunction function = await FunctionRepository.GetAsync(functionId);
if (function == null)
{
continue;
}
TModuleFunction moduleFunction = new TModuleFunction() { ModuleId = moduleId, FunctionId = functionId };
count = count + await ModuleFunctionRepository.InsertAsync(moduleFunction);
addNames.Add(function.Name);
}
foreach (Guid functionId in removeFunctionIds)
{
TFunction function = await FunctionRepository.GetAsync(functionId);
if (function == null)
{
continue;
}
TModuleFunction moduleFunction = ModuleFunctionRepository.QueryAsNoTracking()
.FirstOrDefault(m => m.ModuleId.Equals(moduleId) && m.FunctionId == functionId);
if (moduleFunction == null)
{
continue;
}
count = count + await ModuleFunctionRepository.DeleteAsync(moduleFunction);
removeNames.Add(function.Name);
}
if (count > 0)
{
//功能权限缓存刷新事件
FunctionAuthCacheRefreshEventData removeEventData = new FunctionAuthCacheRefreshEventData()
{
FunctionIds = addFunctionIds.Union(removeFunctionIds).Distinct().ToArray()
};
EventBus.Publish(removeEventData);
return new OperationResult(OperationResultType.Success,
$"模块“{module.Name}”添加功能“{addNames.ExpandAndToString()}”,移除功能“{removeNames.ExpandAndToString()}”操作成功");
}
return OperationResult.NoChanged;
}
#endregion Implementation of IModuleFunctionStore<TModuleFunction>
#region Implementation of IModuleRoleStore<TModuleRole>
/// <summary>
/// 获取 模块角色信息查询数据集
/// </summary>
public IQueryable<TModuleRole> ModuleRoles => ModuleRoleRepository.QueryAsNoTracking();
/// <summary>
/// 检查模块角色信息是否存在
/// </summary>
/// <param name="predicate">检查谓语表达式</param>
/// <param name="id">更新的模块角色信息编号</param>
/// <returns>模块角色信息是否存在</returns>
public virtual Task<bool> CheckModuleRoleExists(Expression<Func<TModuleRole, bool>> predicate, Guid id = default(Guid))
{
return ModuleRoleRepository.CheckExistsAsync(predicate, id);
}
/// <summary>
/// 设置角色的可访问模块
/// </summary>
/// <param name="roleId">角色编号</param>
/// <param name="moduleIds">要赋予的模块编号集合</param>
/// <returns>业务操作结果</returns>
public virtual async Task<OperationResult> SetRoleModules(TRoleKey roleId, TModuleKey[] moduleIds)
{
TRole role = await RoleRepository.GetAsync(roleId);
if (role == null)
{
return new OperationResult(OperationResultType.QueryNull, $"编号为“{roleId}”的角色信息不存在");
}
TModuleKey[] existModuleIds = ModuleRoleRepository.QueryAsNoTracking(m => m.RoleId.Equals(roleId)).Select(m => m.ModuleId).ToArray();
TModuleKey[] addModuleIds = moduleIds.Except(existModuleIds).ToArray();
TModuleKey[] removeModuleIds = existModuleIds.Except(moduleIds).ToArray();
List<string> addNames = new List<string>(), removeNames = new List<string>();
int count = 0;
foreach (TModuleKey moduleId in addModuleIds)
{
TModule module = await ModuleRepository.GetAsync(moduleId);
if (module == null)
{
return new OperationResult(OperationResultType.QueryNull, $"编号为“{moduleId}”的模块信息不存在");
}
TModuleRole moduleRole = new TModuleRole() { ModuleId = moduleId, RoleId = roleId };
count = count + await ModuleRoleRepository.InsertAsync(moduleRole);
addNames.Add(module.Name);
}
foreach (TModuleKey moduleId in removeModuleIds)
{
TModule module = await ModuleRepository.GetAsync(moduleId);
if (module == null)
{
return new OperationResult(OperationResultType.QueryNull, $"编号为“{moduleId}”的模块信息不存在");
}
TModuleRole moduleRole = ModuleRoleRepository.GetFirst(m => m.RoleId.Equals(roleId) && m.ModuleId.Equals(moduleId));
if (moduleRole == null)
{
continue;
}
count = count + await ModuleRoleRepository.DeleteAsync(moduleRole);
removeNames.Add(module.Name);
}
if (count > 0)
{
//功能权限缓存刷新事件
moduleIds = addModuleIds.Union(removeModuleIds).Distinct().ToArray();
Guid[] functionIds = ModuleFunctionRepository.QueryAsNoTracking(m => moduleIds.Contains(m.ModuleId))
.Select(m => m.FunctionId).Distinct().ToArray();
FunctionAuthCacheRefreshEventData removeEventData = new FunctionAuthCacheRefreshEventData() { FunctionIds = functionIds };
EventBus.Publish(removeEventData);
if (addNames.Count > 0 && removeNames.Count == 0)
{
return new OperationResult(OperationResultType.Success, $"角色“{role.Name}”添加模块“{addNames.ExpandAndToString()}”操作成功");
}
if (addNames.Count == 0 && removeNames.Count > 0)
{
return new OperationResult(OperationResultType.Success, $"角色“{role.Name}”移除模块“{removeNames.ExpandAndToString()}”操作成功");
}
return new OperationResult(OperationResultType.Success,
$"角色“{role.Name}”添加模块“{addNames.ExpandAndToString()}”,移除模块“{removeNames.ExpandAndToString()}”操作成功");
}
return OperationResult.NoChanged;
}
/// <summary>
/// 获取角色可访问模块编号
/// </summary>
/// <param name="roleId">角色编号</param>
/// <returns>模块编号集合</returns>
public virtual TModuleKey[] GetRoleModuleIds(TRoleKey roleId)
{
TModuleKey[] moduleIds = ModuleRoleRepository.QueryAsNoTracking(m => m.RoleId.Equals(roleId)).Select(m => m.ModuleId).Distinct().ToArray();
return GetModuleTreeIds(moduleIds);
}
#endregion Implementation of IModuleRoleStore<TModuleRole>
#region Implementation of IModuleUserStore<TModuleUser>
/// <summary>
/// 获取 模块用户信息查询数据集
/// </summary>
public IQueryable<TModuleUser> ModuleUsers => ModuleUserRepository.QueryAsNoTracking();
/// <summary>
/// 检查模块用户信息是否存在
/// </summary>
/// <param name="predicate">检查谓语表达式</param>
/// <param name="id">更新的模块用户信息编号</param>
/// <returns>模块用户信息是否存在</returns>
public virtual Task<bool> CheckModuleUserExists(Expression<Func<TModuleUser, bool>> predicate, Guid id = default(Guid))
{
return ModuleUserRepository.CheckExistsAsync(predicate, id);
}
/// <summary>
/// 设置用户的可访问模块
/// </summary>
/// <param name="userId">用户编号</param>
/// <param name="moduleIds">要赋给用户的模块编号集合</param>
/// <returns>业务操作结果</returns>
public virtual async Task<OperationResult> SetUserModules(TUserKey userId, TModuleKey[] moduleIds)
{
TUser user = await UserRepository.GetAsync(userId);
if (user == null)
{
return new OperationResult(OperationResultType.QueryNull, $"编号为“{userId}”的用户信息不存在");
}
TModuleKey[] existModuleIds = ModuleUserRepository.QueryAsNoTracking(m => m.UserId.Equals(userId)).Select(m => m.ModuleId).ToArray();
TModuleKey[] addModuleIds = moduleIds.Except(existModuleIds).ToArray();
TModuleKey[] removeModuleIds = existModuleIds.Except(moduleIds).ToArray();
List<string> addNames = new List<string>(), removeNames = new List<string>();
int count = 0;
foreach (TModuleKey moduleId in addModuleIds)
{
TModule module = await ModuleRepository.GetAsync(moduleId);
if (module == null)
{
return new OperationResult(OperationResultType.QueryNull, $"编号为“{moduleId}”的模块信息不存在");
}
TModuleUser moduleUser = new TModuleUser() { ModuleId = moduleId, UserId = userId };
count += await ModuleUserRepository.InsertAsync(moduleUser);
addNames.Add(module.Name);
}
foreach (TModuleKey moduleId in removeModuleIds)
{
TModule module = await ModuleRepository.GetAsync(moduleId);
if (module == null)
{
return new OperationResult(OperationResultType.QueryNull, $"编号为“{moduleId}”的模块信息不存在");
}
TModuleUser moduleUser = ModuleUserRepository.GetFirst(m => m.ModuleId.Equals(moduleId) && m.UserId.Equals(userId));
if (moduleUser == null)
{
continue;
}
count += await ModuleUserRepository.DeleteAsync(moduleUser);
removeNames.Add(module.Name);
}
if (count > 0)
{
//功能权限缓存刷新事件
FunctionAuthCacheRefreshEventData removeEventData = new FunctionAuthCacheRefreshEventData() { UserNames = new[] { user.UserName } };
EventBus.Publish(removeEventData);
if (addNames.Count > 0 && removeNames.Count == 0)
{
return new OperationResult(OperationResultType.Success, $"用户“{user.UserName}”添加模块“{addNames.ExpandAndToString()}”操作成功");
}
if (addNames.Count == 0 && removeNames.Count > 0)
{
return new OperationResult(OperationResultType.Success, $"用户“{user.UserName}”移除模块“{removeNames.ExpandAndToString()}”操作成功");
}
return new OperationResult(OperationResultType.Success,
$"用户“{user.UserName}”添加模块“{addNames.ExpandAndToString()}”,移除模块“{removeNames.ExpandAndToString()}”操作成功");
}
return OperationResult.NoChanged;
}
/// <summary>
/// 获取用户自己的可访问模块编号
/// </summary>
/// <param name="userId">用户编号</param>
/// <returns>模块编号集合</returns>
public virtual TModuleKey[] GetUserSelfModuleIds(TUserKey userId)
{
TModuleKey[] moduleIds = ModuleUserRepository.QueryAsNoTracking(m => m.UserId.Equals(userId)).Select(m => m.ModuleId).Distinct().ToArray();
return GetModuleTreeIds(moduleIds);
}
/// <summary>
/// 获取用户及其拥有角色可访问模块编号
/// </summary>
/// <param name="userId">用户编号</param>
/// <returns>模块编号集合</returns>
public virtual TModuleKey[] GetUserWithRoleModuleIds(TUserKey userId)
{
TModuleKey[] selfModuleIds = GetUserSelfModuleIds(userId);
TRoleKey[] roleIds = UserRoleRepository.QueryAsNoTracking(m => m.UserId.Equals(userId)).Select(m => m.RoleId).ToArray();
TModuleKey[] roleModuleIds = roleIds
.SelectMany(m => ModuleRoleRepository.QueryAsNoTracking(n => n.RoleId.Equals(m)).Select(n => n.ModuleId))
.Distinct().ToArray();
roleModuleIds = GetModuleTreeIds(roleModuleIds);
return roleModuleIds.Union(selfModuleIds).Distinct().ToArray();
}
#endregion Implementation of IModuleUserStore<TModuleUser>
}
} | {
"pile_set_name": "Github"
} |
```ocaml
# let empty = 0;;
val empty : int = 0
# let satisfies_identity_law = 10 + empty = 10;;
val satisfies_identity_law : bool = true
# let satisfies_associative_law = 1 + (2 + 3) = (1 + 2) + 3;;
val satisfies_associative_law : bool = true
```
| {
"pile_set_name": "Github"
} |
CORE
test.c
--show-vcc
main::1::node1!0@1#2\.\.data =
main::1::node2!0@1#2\.\.data =
^EXIT=0$
^SIGNAL=0$
--
main::1::node1!0@1#[3-9]\.\.children\[\[[01]\]\] =
--
This checks that mixed array and field accesses are executed using a field-sensitive
symbol (main::1::node1!0@1#2..data) rather than by assigning the whole struct and
expanding into field symbols (which would assign main::1::node1!0@1#3..children\[\[[01]\]\])
| {
"pile_set_name": "Github"
} |
---
title: Notes from the Road
author: tjfontaine
date: 2014-06-11T16:00:00.000Z
status: publish
category: Uncategorized
slug: notes-from-the-road
layout: blog-post.hbs
---
## Notes from the Road
As Project Lead for Node.js, I was excited to have the opportunity to go on the
road and bring production stories to all of our users. We've had amazing
speakers and turn out in San Francisco, Seattle, Portland, Boston, and New
York. But I wanted to make sure we reached more than just our coasts, so soon
we'll be in
[Minneapolis](http://www.joyent.com/noderoad/cities/minneapolis-6-17-2014) and
I'll be returning to my home state of Ohio and doing an event in
[Cincinnati](http://www.joyent.com/noderoad/cities/cincinnati-6-19-2014). The
Node.js community is all over the world, and hopefully Node on the Road can
reach as many of you as it can. Nominate your city to be a future stop on the
Node.js on the Road series
[here](http://www.joyent.com/noderoad/cities/suggest).
These Node on the Road events are successful because of the incredible support
from the community and the existing meetup organizations in their respective
cities. But the biggest advantage is that the project gets to solicit feedback
directly from our users about what is and isn't working for them in Node.js,
what modules they're using, and where they need Node to do better.
## Release schedules
Some of the feedback we've received has been about the upgrade process for
Node. Veteran Node.js alums will occasionally sit around campfires and tell the
stories of when things would break every release, or how long they stayed on
0.4 before upgrading to 0.6. Some production companies are still out there
running on 0.8 afraid to make the jump to 0.10. While other companies advise
people to avoid upgrading to a new release of a Node version until the patch
number hits double digits. It's those sorts of stories that make it important
for us to get the release for 0.12 right, from the get go.
Node is in a fantastic place right now, it's maturing quickly and finding its
footing in new environments with new users and new use cases. The expectation
for Node is getting higher each day with every release. There are multiple
interests at stake, keeping Node lean, keeping it up to date with languages and
standards, keeping it fast, and balanced with keeping it stable such that we
don't upset the adoption rate. That means Node needs to make the right choices
that balance the needs of all of our users without closing the doors to others.
All of these conversations are helping to shape the release process going
forward, and helping to scope just what does go into a release and how fast
people want to see those happen. In fact something we've been considering is
eliminating the confusion around our Stable/Unstable branches, and instead
moving to releases that are always stable. But it's important that the features
and changes that go into a release are shaped by user feedback, which is why
events like Node on the Road are vital.
## Better Documentation
Another key piece of feedback has consistently been around our documentation.
Users need us to clean up our API reference documentation, there are lots of
undocumented and under-documented methods and properties that are being used or
should be used. Node needs to include what errors may be delivered as part of
the operation of your application, as well as what methods will throw and under
what circumstances.
But mostly users are looking for more general purpose documentation that can
help both new and veteran Node.js users be more productive with Node. And the
people who are most equipped to provide that documentation are the users
themselves who've already been successful.
## Easier Contribution
Aside from soliciting feedback from users of Node.js and bringing production
stories to our users, Node on the Road has also been about highlighting the
various ways you as a member of the community can contribute. There are many
ways you can contribute from meetups and conferences, to publishing modules, to
finding issues in modules or core, to fixing issues in modules or core, or even
adding features to modules or core. Where ever you are passionate about Node.js
there are ways you can contribute back to Node.
Node.js has inherited many things from our largest dependency V8, we've adopted
their build system GYP, we use their test runner (which is unfortunately in
python), and when we were structuring the project we brought along the
Contributor License Agreement (CLA) that Google uses to manage contributions
for Chromium and V8. The CLA is there as a way for a project to audit itself
and to give itself the opportunity to relicense itself in the future if
necessary. Node.js though is distributed under the venerable
[MIT](http://opensource.org/licenses/MIT) license, and that's not going to
change. The MIT license is one of the most permissible open source licenses out
there, and has fostered a ton of development with Node.js and we want that to
continue.
In an effort to make it easier for users to contribute to Node.js the project
has decided to lift the requirement of signing the CLA before contributions are
eligible for integration. Having to sign the CLA could at times be a stumbling
block for a contribution. It could involve a long conversation with your legal
department to ultimately contribute typo corrections.
I'm excited to see what contributions will be coming from the community in the
future, excited to see where our users take Node.js, and excited to be
participating with all of you on this project.
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package expfmt contains tools for reading and writing Prometheus metrics.
package expfmt
// Format specifies the HTTP content type of the different wire protocols.
type Format string
// Constants to assemble the Content-Type values for the different wire protocols.
const (
TextVersion = "0.0.4"
ProtoType = `application/vnd.google.protobuf`
ProtoProtocol = `io.prometheus.client.MetricFamily`
ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";"
// The Content-Type values for the different wire protocols.
FmtUnknown Format = `<unknown>`
FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8`
FmtProtoDelim Format = ProtoFmt + ` encoding=delimited`
FmtProtoText Format = ProtoFmt + ` encoding=text`
FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text`
)
const (
hdrContentType = "Content-Type"
hdrAccept = "Accept"
)
| {
"pile_set_name": "Github"
} |
# List of Breaking Changes for 4.x
| {
"pile_set_name": "Github"
} |
package streamanalytics
import (
"context"
"fmt"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/services/streamanalytics/mgmt/2016-03-01/streamanalytics"
"github.com/hashicorp/go-azure-helpers/response"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmStreamAnalyticsReferenceInputBlob() *schema.Resource {
return &schema.Resource{
Create: resourceArmStreamAnalyticsReferenceInputBlobCreate,
Read: resourceArmStreamAnalyticsReferenceInputBlobRead,
Update: resourceArmStreamAnalyticsReferenceInputBlobUpdate,
Delete: resourceArmStreamAnalyticsReferenceInputBlobDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Read: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"stream_analytics_job_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"resource_group_name": azure.SchemaResourceGroupName(),
"date_format": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"path_pattern": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"storage_account_key": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"storage_account_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"storage_container_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"time_format": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"serialization": azure.SchemaStreamAnalyticsStreamInputSerialization(),
},
}
}
func getBlobReferenceInputProps(ctx context.Context, d *schema.ResourceData) (streamanalytics.Input, error) {
name := d.Get("name").(string)
containerName := d.Get("storage_container_name").(string)
dateFormat := d.Get("date_format").(string)
pathPattern := d.Get("path_pattern").(string)
storageAccountKey := d.Get("storage_account_key").(string)
storageAccountName := d.Get("storage_account_name").(string)
timeFormat := d.Get("time_format").(string)
serializationRaw := d.Get("serialization").([]interface{})
serialization, err := azure.ExpandStreamAnalyticsStreamInputSerialization(serializationRaw)
if err != nil {
return streamanalytics.Input{}, fmt.Errorf("Error expanding `serialization`: %+v", err)
}
props := streamanalytics.Input{
Name: utils.String(name),
Properties: &streamanalytics.ReferenceInputProperties{
Type: streamanalytics.TypeReference,
Datasource: &streamanalytics.BlobReferenceInputDataSource{
Type: streamanalytics.TypeBasicReferenceInputDataSourceTypeMicrosoftStorageBlob,
BlobReferenceInputDataSourceProperties: &streamanalytics.BlobReferenceInputDataSourceProperties{
Container: utils.String(containerName),
DateFormat: utils.String(dateFormat),
PathPattern: utils.String(pathPattern),
TimeFormat: utils.String(timeFormat),
StorageAccounts: &[]streamanalytics.StorageAccount{
{
AccountName: utils.String(storageAccountName),
AccountKey: utils.String(storageAccountKey),
},
},
},
},
Serialization: serialization,
},
}
return props, nil
}
func resourceArmStreamAnalyticsReferenceInputBlobCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).StreamAnalytics.InputsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
log.Printf("[INFO] preparing arguments for Azure Stream Analytics Reference Input Blob creation.")
name := d.Get("name").(string)
jobName := d.Get("stream_analytics_job_name").(string)
resourceGroup := d.Get("resource_group_name").(string)
if features.ShouldResourcesBeImported() && d.IsNewResource() {
existing, err := client.Get(ctx, resourceGroup, jobName, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing Stream Analytics Reference Input %q (Job %q / Resource Group %q): %s", name, jobName, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_stream_analytics_reference_input_blob", *existing.ID)
}
}
props, err := getBlobReferenceInputProps(ctx, d)
if err != nil {
return fmt.Errorf("Error creating the input props for resource creation: %v", err)
}
if _, err := client.CreateOrReplace(ctx, props, resourceGroup, jobName, name, "", ""); err != nil {
return fmt.Errorf("Error Creating Stream Analytics Reference Input Blob %q (Job %q / Resource Group %q): %+v", name, jobName, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, jobName, name)
if err != nil {
return fmt.Errorf("Error retrieving Stream Analytics Reference Input Blob %q (Job %q / Resource Group %q): %+v", name, jobName, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read ID of Stream Analytics Reference Input Blob %q (Job %q / Resource Group %q)", name, jobName, resourceGroup)
}
d.SetId(*read.ID)
return resourceArmStreamAnalyticsReferenceInputBlobRead(d, meta)
}
func resourceArmStreamAnalyticsReferenceInputBlobUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).StreamAnalytics.InputsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
log.Printf("[INFO] preparing arguments for Azure Stream Analytics Reference Input Blob creation.")
name := d.Get("name").(string)
jobName := d.Get("stream_analytics_job_name").(string)
resourceGroup := d.Get("resource_group_name").(string)
props, err := getBlobReferenceInputProps(ctx, d)
if err != nil {
return fmt.Errorf("Error creating the input props for resource update: %v", err)
}
if _, err := client.Update(ctx, props, resourceGroup, jobName, name, ""); err != nil {
return fmt.Errorf("Error Updating Stream Analytics Reference Input Blob %q (Job %q / Resource Group %q): %+v", name, jobName, resourceGroup, err)
}
return resourceArmStreamAnalyticsReferenceInputBlobRead(d, meta)
}
func resourceArmStreamAnalyticsReferenceInputBlobRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).StreamAnalytics.InputsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
jobName := id.Path["streamingjobs"]
name := id.Path["inputs"]
resp, err := client.Get(ctx, resourceGroup, jobName, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Reference Input Blob %q was not found in Stream Analytics Job %q / Resource Group %q - removing from state!", name, jobName, resourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving Reference Input Blob %q (Stream Analytics Job %q / Resource Group %q): %+v", name, jobName, resourceGroup, err)
}
d.Set("name", name)
d.Set("resource_group_name", resourceGroup)
d.Set("stream_analytics_job_name", jobName)
if props := resp.Properties; props != nil {
v, ok := props.AsReferenceInputProperties()
if !ok {
return fmt.Errorf("Error converting Reference Input Blob to a Reference Input: %+v", err)
}
blobInputDataSource, ok := v.Datasource.AsBlobReferenceInputDataSource()
if !ok {
return fmt.Errorf("Error converting Reference Input Blob to an Blob Stream Input: %+v", err)
}
d.Set("date_format", blobInputDataSource.DateFormat)
d.Set("path_pattern", blobInputDataSource.PathPattern)
d.Set("storage_container_name", blobInputDataSource.Container)
d.Set("time_format", blobInputDataSource.TimeFormat)
if accounts := blobInputDataSource.StorageAccounts; accounts != nil && len(*accounts) > 0 {
account := (*accounts)[0]
d.Set("storage_account_name", account.AccountName)
}
if err := d.Set("serialization", azure.FlattenStreamAnalyticsStreamInputSerialization(v.Serialization)); err != nil {
return fmt.Errorf("Error setting `serialization`: %+v", err)
}
}
return nil
}
func resourceArmStreamAnalyticsReferenceInputBlobDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).StreamAnalytics.InputsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
jobName := id.Path["streamingjobs"]
name := id.Path["inputs"]
if resp, err := client.Delete(ctx, resourceGroup, jobName, name); err != nil {
if !response.WasNotFound(resp.Response) {
return fmt.Errorf("Error deleting Reference Input Blob %q (Stream Analytics Job %q / Resource Group %q) %+v", name, jobName, resourceGroup, err)
}
}
return nil
}
| {
"pile_set_name": "Github"
} |
# From ftp://gcc.gnu.org/pub/binutils/releases/sha512.sum
sha512 dc5b6872ae01c07c12d38f3bb7ead06effc6da3265ac872e2d9c6104304f89f85f2645b029a43f308a7938a7299b1928d385205d0a2245674a621649032a138d binutils-2.28.1.tar.xz
sha512 d748d22306477d60d921078804d21943248c23fca0707aac9b016a352c01c75ca69e82624ae37fb0bbd03af3b17088a94f60dfe1a86a7ff82e18ece3c24f0fd0 binutils-2.29.1.tar.xz
sha512 e747ea20d8d79fcd21b9d9f6695059caa7189d60f19256da398e34b789fea9a133c32b192e9693b5828d27683739b0198431bf8b3e39fb3b04884cf89d9aa839 binutils-2.30.tar.xz
sha512 0fca326feb1d5f5fe505a827b20237fe3ec9c13eaf7ec7e35847fd71184f605ba1cefe1314b1b8f8a29c0aa9d88162849ee1c1a3e70c2f7407d88339b17edb30 binutils-2.31.1.tar.xz
# Locally calculated (fetched from Github)
sha512 a96dfcea6064fcd1aac1333ac0d631491bed8b0be9bdcf62f1447909c8f30d2cb8d9323ffeb7c9ad6b326ecddb72e3d28281684e73343189d0a4a37a11aef62f binutils-gdb-arc-2018.09-release.tar.gz
| {
"pile_set_name": "Github"
} |
# Usage
**If you want to use default theme, you can skip this step**
To achieve the level of customizability, React Native Material UI is using a single JS object called uiTheme that is passed in via context. By default, this uiTheme object is based on the lightTheme that you can find [here](https://github.com/xotahal/react-native-material-ui/blob/master/src/styles/themes/light.js). So, you can change almost everything very easily.
The uiTheme object contains the following keys (for more of them - check the code):
```js
spacing: {} // can be used to change the spacing of components.
fontFamily: {} // can be used to change the default font family.
palette: { // can be used to change the color of components.
primaryColor: blue500,
accentColor: red500,
...
}
typography: {} // can be used to change the typography of components
// you can change style of every each component
avatar: {}
button: {}
toolbar: {}
...
```
```js
import React, { Component } from 'react';
import { Navigator, NativeModules } from 'react-native';
import { COLOR, ThemeContext, getTheme } from 'react-native-material-ui';
// you can set your style right here, it'll be propagated to application
const uiTheme = {
palette: {
primaryColor: COLOR.green500,
},
toolbar: {
container: {
height: 50,
},
},
};
class Main extends Component {
render() {
return (
<ThemeContext.Provider value={getTheme(uiTheme)}>
<App />
</ThemeContext.Provider>
);
}
}
```
It means, if you want to change primary color of your application you can just pass to ThemeContext.Provider object with your own settings. The settings will be merged with default theme.
## What else?
Another great feature is, you can use the `theme` everywhere. Even in your own components. So if you built your own implementation of `Button` for example, look how you can get the primary color.
```js
import { withTheme } from 'react-native-material-ui'
class MyButton extends Component {
render() {
// it's really easy to get primary color everywhere in your app
const { primaryColor } = this.props.theme.palette;
return ...
}
}
export default withTheme(MyButton)
```
## Local changes
Of course, sometimes we need to change style of only one component. All `buttons` have a red background by default, but only facebook button should have blue background.
Every component have a `style` property. So you can very easily override whatever you want.
```js
<Button style={{ container: { backgroundColor: 'blue' } }} />
```
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WASMFunctionParser.h"
#if ENABLE(WEBASSEMBLY)
#include "JSCJSValueInlines.h"
#include "JSWASMModule.h"
#include "WASMFunctionCompiler.h"
#include "WASMFunctionB3IRGenerator.h"
#include "WASMFunctionSyntaxChecker.h"
#define PROPAGATE_ERROR() do { if (!m_errorMessage.isNull()) return 0; } while (0)
#define FAIL_WITH_MESSAGE(errorMessage) do { m_errorMessage = errorMessage; return 0; } while (0)
#define READ_FLOAT_OR_FAIL(result, errorMessage) do { if (!m_reader.readFloat(result)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_DOUBLE_OR_FAIL(result, errorMessage) do { if (!m_reader.readDouble(result)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_COMPACT_INT32_OR_FAIL(result, errorMessage) do { if (!m_reader.readCompactInt32(result)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_COMPACT_UINT32_OR_FAIL(result, errorMessage) do { if (!m_reader.readCompactUInt32(result)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_EXPRESSION_TYPE_OR_FAIL(result, errorMessage) do { if (!m_reader.readExpressionType(result)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_OP_STATEMENT_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, errorMessage) do { if (!m_reader.readOpStatement(hasImmediate, op, opWithImmediate, immediate)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_OP_EXPRESSION_I32_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, errorMessage) do { if (!m_reader.readOpExpressionI32(hasImmediate, op, opWithImmediate, immediate)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_OP_EXPRESSION_F32_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, errorMessage) do { if (!m_reader.readOpExpressionF32(hasImmediate, op, opWithImmediate, immediate)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_OP_EXPRESSION_F64_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, errorMessage) do { if (!m_reader.readOpExpressionF64(hasImmediate, op, opWithImmediate, immediate)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_OP_EXPRESSION_VOID_OR_FAIL(op, errorMessage) do { if (!m_reader.readOpExpressionVoid(op)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_VARIABLE_TYPES_OR_FAIL(hasImmediate, variableTypes, variableTypesWithImmediate, immediate, errorMessage) do { if (!m_reader.readVariableTypes(hasImmediate, variableTypes, variableTypesWithImmediate, immediate)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define READ_SWITCH_CASE_OR_FAIL(result, errorMessage) do { if (!m_reader.readSwitchCase(result)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define FAIL_IF_FALSE(condition, errorMessage) do { if (!(condition)) FAIL_WITH_MESSAGE(errorMessage); } while (0)
#define UNUSED 0
namespace JSC {
static String nameOfType(WASMType type)
{
switch (type) {
case WASMType::I32:
return "int32";
case WASMType::F32:
return "float32";
case WASMType::F64:
return "float64";
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
bool WASMFunctionParser::checkSyntax(JSWASMModule* module, const SourceCode& source, size_t functionIndex, unsigned startOffsetInSource, unsigned& endOffsetInSource, unsigned& stackHeight, String& errorMessage)
{
WASMFunctionParser parser(module, source, functionIndex);
WASMFunctionSyntaxChecker syntaxChecker;
parser.m_reader.setOffset(startOffsetInSource);
parser.parseFunction(syntaxChecker);
if (!parser.m_errorMessage.isNull()) {
errorMessage = parser.m_errorMessage;
return false;
}
endOffsetInSource = parser.m_reader.offset();
stackHeight = syntaxChecker.stackHeight();
return true;
}
void WASMFunctionParser::compile(VM& vm, CodeBlock* codeBlock, JSWASMModule* module, const SourceCode& source, size_t functionIndex)
{
WASMFunctionParser parser(module, source, functionIndex);
WASMFunctionCompiler compiler(vm, codeBlock, module, module->functionStackHeights()[functionIndex]);
parser.m_reader.setOffset(module->functionStartOffsetsInSource()[functionIndex]);
parser.parseFunction(compiler);
ASSERT(parser.m_errorMessage.isNull());
}
template <class Context>
bool WASMFunctionParser::parseFunction(Context& context)
{
const WASMSignature& signature = m_module->signatures()[m_module->functionDeclarations()[m_functionIndex].signatureIndex];
m_returnType = signature.returnType;
parseLocalVariables();
PROPAGATE_ERROR();
const Vector<WASMType>& arguments = signature.arguments;
for (size_t i = 0; i < arguments.size(); ++i)
m_localTypes.append(arguments[i]);
for (uint32_t i = 0; i < m_numberOfI32LocalVariables; ++i)
m_localTypes.append(WASMType::I32);
for (uint32_t i = 0; i < m_numberOfF32LocalVariables; ++i)
m_localTypes.append(WASMType::F32);
for (uint32_t i = 0; i < m_numberOfF64LocalVariables; ++i)
m_localTypes.append(WASMType::F64);
context.startFunction(arguments, m_numberOfI32LocalVariables, m_numberOfF32LocalVariables, m_numberOfF64LocalVariables);
parseBlockStatement(context);
PROPAGATE_ERROR();
context.endFunction();
return true;
}
bool WASMFunctionParser::parseLocalVariables()
{
m_numberOfI32LocalVariables = 0;
m_numberOfF32LocalVariables = 0;
m_numberOfF64LocalVariables = 0;
bool hasImmediate;
WASMVariableTypes variableTypes;
WASMVariableTypesWithImmediate variableTypesWithImmediate;
uint8_t immediate;
READ_VARIABLE_TYPES_OR_FAIL(hasImmediate, variableTypes, variableTypesWithImmediate, immediate, "Cannot read the types of local variables.");
if (!hasImmediate) {
if (static_cast<uint8_t>(variableTypes) & static_cast<uint8_t>(WASMVariableTypes::I32))
READ_COMPACT_UINT32_OR_FAIL(m_numberOfI32LocalVariables, "Cannot read the number of int32 local variables.");
if (static_cast<uint8_t>(variableTypes) & static_cast<uint8_t>(WASMVariableTypes::F32))
READ_COMPACT_UINT32_OR_FAIL(m_numberOfF32LocalVariables, "Cannot read the number of float32 local variables.");
if (static_cast<uint8_t>(variableTypes) & static_cast<uint8_t>(WASMVariableTypes::F64))
READ_COMPACT_UINT32_OR_FAIL(m_numberOfF64LocalVariables, "Cannot read the number of float64 local variables.");
} else
m_numberOfI32LocalVariables = immediate;
return true;
}
template <class Context>
ContextStatement WASMFunctionParser::parseStatement(Context& context)
{
bool hasImmediate;
WASMOpStatement op;
WASMOpStatementWithImmediate opWithImmediate;
uint8_t immediate;
READ_OP_STATEMENT_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, "Cannot read the statement opcode.");
if (!hasImmediate) {
switch (op) {
case WASMOpStatement::SetLocal:
parseSetLocal(context, WASMOpKind::Statement, WASMExpressionType::Void);
break;
case WASMOpStatement::SetGlobal:
parseSetGlobal(context, WASMOpKind::Statement, WASMExpressionType::Void);
break;
case WASMOpStatement::I32Store8:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::NoOffset);
break;
case WASMOpStatement::I32StoreWithOffset8:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::WithOffset);
break;
case WASMOpStatement::I32Store16:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::NoOffset);
break;
case WASMOpStatement::I32StoreWithOffset16:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::WithOffset);
break;
case WASMOpStatement::I32Store32:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::I32, WASMMemoryType::I32, MemoryAccessOffsetMode::NoOffset);
break;
case WASMOpStatement::I32StoreWithOffset32:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::I32, WASMMemoryType::I32, MemoryAccessOffsetMode::WithOffset);
break;
case WASMOpStatement::F32Store:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::F32, WASMMemoryType::F32, MemoryAccessOffsetMode::NoOffset);
break;
case WASMOpStatement::F32StoreWithOffset:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::F32, WASMMemoryType::F32, MemoryAccessOffsetMode::WithOffset);
break;
case WASMOpStatement::F64Store:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::F64, WASMMemoryType::F64, MemoryAccessOffsetMode::NoOffset);
break;
case WASMOpStatement::F64StoreWithOffset:
parseStore(context, WASMOpKind::Statement, WASMExpressionType::F64, WASMMemoryType::F64, MemoryAccessOffsetMode::WithOffset);
break;
case WASMOpStatement::CallInternal:
parseCallInternal(context, WASMOpKind::Statement, WASMExpressionType::Void);
break;
case WASMOpStatement::CallIndirect:
parseCallIndirect(context, WASMOpKind::Statement, WASMExpressionType::Void);
break;
case WASMOpStatement::CallImport:
parseCallImport(context, WASMOpKind::Statement, WASMExpressionType::Void);
break;
case WASMOpStatement::Return:
parseReturnStatement(context);
break;
case WASMOpStatement::Block:
parseBlockStatement(context);
break;
case WASMOpStatement::If:
parseIfStatement(context);
break;
case WASMOpStatement::IfElse:
parseIfElseStatement(context);
break;
case WASMOpStatement::While:
parseWhileStatement(context);
break;
case WASMOpStatement::Do:
parseDoStatement(context);
break;
case WASMOpStatement::Label:
parseLabelStatement(context);
break;
case WASMOpStatement::Break:
parseBreakStatement(context);
break;
case WASMOpStatement::BreakLabel:
parseBreakLabelStatement(context);
break;
case WASMOpStatement::Continue:
parseContinueStatement(context);
break;
case WASMOpStatement::ContinueLabel:
parseContinueLabelStatement(context);
break;
case WASMOpStatement::Switch:
parseSwitchStatement(context);
break;
default:
ASSERT_NOT_REACHED();
}
} else {
switch (opWithImmediate) {
case WASMOpStatementWithImmediate::SetLocal:
parseSetLocal(context, WASMOpKind::Statement, WASMExpressionType::Void, immediate);
break;
case WASMOpStatementWithImmediate::SetGlobal:
parseSetGlobal(context, WASMOpKind::Statement, WASMExpressionType::Void, immediate);
break;
default:
ASSERT_NOT_REACHED();
}
}
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseReturnStatement(Context& context)
{
ContextExpression expression = 0;
if (m_returnType != WASMExpressionType::Void) {
expression = parseExpression(context, m_returnType);
PROPAGATE_ERROR();
}
context.buildReturn(expression, m_returnType);
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseBlockStatement(Context& context)
{
uint32_t numberOfStatements;
READ_COMPACT_UINT32_OR_FAIL(numberOfStatements, "Cannot read the number of statements.");
for (uint32_t i = 0; i < numberOfStatements; ++i) {
parseStatement(context);
PROPAGATE_ERROR();
}
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseIfStatement(Context& context)
{
ContextJumpTarget end;
ContextExpression expression = parseExpressionI32(context);
PROPAGATE_ERROR();
context.jumpToTargetIf(Context::JumpCondition::Zero, expression, end);
parseStatement(context);
PROPAGATE_ERROR();
context.linkTarget(end);
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseIfElseStatement(Context& context)
{
ContextJumpTarget elseTarget;
ContextJumpTarget end;
ContextExpression expression = parseExpressionI32(context);
PROPAGATE_ERROR();
context.jumpToTargetIf(Context::JumpCondition::Zero, expression, elseTarget);
parseStatement(context);
PROPAGATE_ERROR();
context.jumpToTarget(end);
context.linkTarget(elseTarget);
parseStatement(context);
PROPAGATE_ERROR();
context.linkTarget(end);
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseWhileStatement(Context& context)
{
context.startLoop();
context.linkTarget(context.continueTarget());
ContextExpression expression = parseExpressionI32(context);
PROPAGATE_ERROR();
context.jumpToTargetIf(Context::JumpCondition::Zero, expression, context.breakTarget());
m_breakScopeDepth++;
m_continueScopeDepth++;
parseStatement(context);
PROPAGATE_ERROR();
m_continueScopeDepth--;
m_breakScopeDepth--;
context.jumpToTarget(context.continueTarget());
context.linkTarget(context.breakTarget());
context.endLoop();
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseDoStatement(Context& context)
{
context.startLoop();
ContextJumpTarget topOfLoop;
context.linkTarget(topOfLoop);
m_breakScopeDepth++;
m_continueScopeDepth++;
parseStatement(context);
PROPAGATE_ERROR();
m_continueScopeDepth--;
m_breakScopeDepth--;
context.linkTarget(context.continueTarget());
ContextExpression expression = parseExpressionI32(context);
PROPAGATE_ERROR();
context.jumpToTargetIf(Context::JumpCondition::NonZero, expression, topOfLoop);
context.linkTarget(context.breakTarget());
context.endLoop();
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseLabelStatement(Context& context)
{
context.startLabel();
m_labelDepth++;
parseStatement(context);
PROPAGATE_ERROR();
m_labelDepth--;
context.endLabel();
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseBreakStatement(Context& context)
{
FAIL_IF_FALSE(m_breakScopeDepth, "'break' is only valid inside a switch or loop statement.");
context.jumpToTarget(context.breakTarget());
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseBreakLabelStatement(Context& context)
{
uint32_t labelIndex;
READ_COMPACT_UINT32_OR_FAIL(labelIndex, "Cannot read the label index.");
FAIL_IF_FALSE(labelIndex < m_labelDepth, "The label index is incorrect.");
context.jumpToTarget(context.breakLabelTarget(labelIndex));
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseContinueStatement(Context& context)
{
FAIL_IF_FALSE(m_continueScopeDepth, "'continue' is only valid inside a loop statement.");
context.jumpToTarget(context.continueTarget());
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseContinueLabelStatement(Context& context)
{
uint32_t labelIndex;
READ_COMPACT_UINT32_OR_FAIL(labelIndex, "Cannot read the label index.");
FAIL_IF_FALSE(labelIndex < m_labelDepth, "The label index is incorrect.");
context.jumpToTarget(context.continueLabelTarget(labelIndex));
return UNUSED;
}
template <class Context>
ContextStatement WASMFunctionParser::parseSwitchStatement(Context& context)
{
context.startSwitch();
uint32_t numberOfCases;
READ_COMPACT_UINT32_OR_FAIL(numberOfCases, "Cannot read the number of cases.");
ContextExpression expression = parseExpressionI32(context);
PROPAGATE_ERROR();
ContextJumpTarget compare;
context.jumpToTarget(compare);
Vector<int64_t> cases;
Vector<ContextJumpTarget> targets;
cases.reserveInitialCapacity(numberOfCases);
targets.reserveInitialCapacity(numberOfCases);
bool hasDefault = false;
ContextJumpTarget defaultTarget;
m_breakScopeDepth++;
for (uint32_t i = 0; i < numberOfCases; ++i) {
WASMSwitchCase switchCase;
READ_SWITCH_CASE_OR_FAIL(switchCase, "Cannot read the switch case.");
switch (switchCase) {
case WASMSwitchCase::CaseWithNoStatements:
case WASMSwitchCase::CaseWithStatement:
case WASMSwitchCase::CaseWithBlockStatement: {
uint32_t value;
READ_COMPACT_INT32_OR_FAIL(value, "Cannot read the value of the switch case.");
cases.uncheckedAppend(value);
ContextJumpTarget target;
context.linkTarget(target);
targets.uncheckedAppend(target);
if (switchCase == WASMSwitchCase::CaseWithStatement) {
parseStatement(context);
PROPAGATE_ERROR();
} else if (switchCase == WASMSwitchCase::CaseWithBlockStatement) {
parseBlockStatement(context);
PROPAGATE_ERROR();
}
break;
}
case WASMSwitchCase::DefaultWithNoStatements:
case WASMSwitchCase::DefaultWithStatement:
case WASMSwitchCase::DefaultWithBlockStatement: {
FAIL_IF_FALSE(i == numberOfCases - 1, "The default case must be the last case.");
hasDefault = true;
context.linkTarget(defaultTarget);
if (switchCase == WASMSwitchCase::DefaultWithStatement) {
parseStatement(context);
PROPAGATE_ERROR();
} else if (switchCase == WASMSwitchCase::DefaultWithBlockStatement) {
parseBlockStatement(context);
PROPAGATE_ERROR();
}
break;
}
default:
ASSERT_NOT_REACHED();
}
}
if (!hasDefault)
context.linkTarget(defaultTarget);
m_breakScopeDepth--;
context.jumpToTarget(context.breakTarget());
context.linkTarget(compare);
context.buildSwitch(expression, cases, targets, defaultTarget);
context.linkTarget(context.breakTarget());
context.endSwitch();
return UNUSED;
}
template <class Context>
ContextExpression WASMFunctionParser::parseExpression(Context& context, WASMExpressionType expressionType)
{
switch (expressionType) {
case WASMExpressionType::I32:
return parseExpressionI32(context);
case WASMExpressionType::F32:
return parseExpressionF32(context);
case WASMExpressionType::F64:
return parseExpressionF64(context);
case WASMExpressionType::Void:
return parseExpressionVoid(context);
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
template <class Context>
ContextExpression WASMFunctionParser::parseExpressionI32(Context& context)
{
bool hasImmediate;
WASMOpExpressionI32 op;
WASMOpExpressionI32WithImmediate opWithImmediate;
uint8_t immediate;
READ_OP_EXPRESSION_I32_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, "Cannot read the int32 expression opcode.");
if (!hasImmediate) {
switch (op) {
case WASMOpExpressionI32::ConstantPoolIndex:
return parseConstantPoolIndexExpressionI32(context);
case WASMOpExpressionI32::Immediate:
return parseImmediateExpressionI32(context);
case WASMOpExpressionI32::GetLocal:
return parseGetLocalExpression(context, WASMType::I32);
case WASMOpExpressionI32::GetGlobal:
return parseGetGlobalExpression(context, WASMType::I32);
case WASMOpExpressionI32::SetLocal:
return parseSetLocal(context, WASMOpKind::Expression, WASMExpressionType::I32);
case WASMOpExpressionI32::SetGlobal:
return parseSetGlobal(context, WASMOpKind::Expression, WASMExpressionType::I32);
case WASMOpExpressionI32::SLoad8:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::NoOffset, MemoryAccessConversion::SignExtend);
case WASMOpExpressionI32::SLoadWithOffset8:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::WithOffset, MemoryAccessConversion::SignExtend);
case WASMOpExpressionI32::ULoad8:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::NoOffset, MemoryAccessConversion::ZeroExtend);
case WASMOpExpressionI32::ULoadWithOffset8:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::WithOffset, MemoryAccessConversion::ZeroExtend);
case WASMOpExpressionI32::SLoad16:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::NoOffset, MemoryAccessConversion::SignExtend);
case WASMOpExpressionI32::SLoadWithOffset16:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::WithOffset, MemoryAccessConversion::SignExtend);
case WASMOpExpressionI32::ULoad16:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::NoOffset, MemoryAccessConversion::ZeroExtend);
case WASMOpExpressionI32::ULoadWithOffset16:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::WithOffset, MemoryAccessConversion::ZeroExtend);
case WASMOpExpressionI32::Load32:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I32, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionI32::LoadWithOffset32:
return parseLoad(context, WASMExpressionType::I32, WASMMemoryType::I32, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionI32::Store8:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionI32::StoreWithOffset8:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::I32, WASMMemoryType::I8, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionI32::Store16:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionI32::StoreWithOffset16:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::I32, WASMMemoryType::I16, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionI32::Store32:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::I32, WASMMemoryType::I32, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionI32::StoreWithOffset32:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::I32, WASMMemoryType::I32, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionI32::CallInternal:
return parseCallInternal(context, WASMOpKind::Expression, WASMExpressionType::I32);
case WASMOpExpressionI32::CallIndirect:
return parseCallIndirect(context, WASMOpKind::Expression, WASMExpressionType::I32);
case WASMOpExpressionI32::CallImport:
return parseCallImport(context, WASMOpKind::Expression, WASMExpressionType::I32);
case WASMOpExpressionI32::Conditional:
return parseConditional(context, WASMExpressionType::I32);
case WASMOpExpressionI32::Comma:
return parseComma(context, WASMExpressionType::I32);
case WASMOpExpressionI32::FromF32:
return parseConvertType(context, WASMExpressionType::F32, WASMExpressionType::I32, WASMTypeConversion::ConvertSigned);
case WASMOpExpressionI32::FromF64:
return parseConvertType(context, WASMExpressionType::F64, WASMExpressionType::I32, WASMTypeConversion::ConvertSigned);
case WASMOpExpressionI32::Negate:
case WASMOpExpressionI32::BitNot:
case WASMOpExpressionI32::CountLeadingZeros:
case WASMOpExpressionI32::LogicalNot:
case WASMOpExpressionI32::Abs:
return parseUnaryExpressionI32(context, op);
case WASMOpExpressionI32::Add:
case WASMOpExpressionI32::Sub:
case WASMOpExpressionI32::Mul:
case WASMOpExpressionI32::SDiv:
case WASMOpExpressionI32::UDiv:
case WASMOpExpressionI32::SMod:
case WASMOpExpressionI32::UMod:
case WASMOpExpressionI32::BitOr:
case WASMOpExpressionI32::BitAnd:
case WASMOpExpressionI32::BitXor:
case WASMOpExpressionI32::LeftShift:
case WASMOpExpressionI32::ArithmeticRightShift:
case WASMOpExpressionI32::LogicalRightShift:
return parseBinaryExpressionI32(context, op);
case WASMOpExpressionI32::EqualI32:
case WASMOpExpressionI32::NotEqualI32:
case WASMOpExpressionI32::SLessThanI32:
case WASMOpExpressionI32::ULessThanI32:
case WASMOpExpressionI32::SLessThanOrEqualI32:
case WASMOpExpressionI32::ULessThanOrEqualI32:
case WASMOpExpressionI32::SGreaterThanI32:
case WASMOpExpressionI32::UGreaterThanI32:
case WASMOpExpressionI32::SGreaterThanOrEqualI32:
case WASMOpExpressionI32::UGreaterThanOrEqualI32:
return parseRelationalI32ExpressionI32(context, op);
case WASMOpExpressionI32::EqualF32:
case WASMOpExpressionI32::NotEqualF32:
case WASMOpExpressionI32::LessThanF32:
case WASMOpExpressionI32::LessThanOrEqualF32:
case WASMOpExpressionI32::GreaterThanF32:
case WASMOpExpressionI32::GreaterThanOrEqualF32:
return parseRelationalF32ExpressionI32(context, op);
case WASMOpExpressionI32::EqualF64:
case WASMOpExpressionI32::NotEqualF64:
case WASMOpExpressionI32::LessThanF64:
case WASMOpExpressionI32::LessThanOrEqualF64:
case WASMOpExpressionI32::GreaterThanF64:
case WASMOpExpressionI32::GreaterThanOrEqualF64:
return parseRelationalF64ExpressionI32(context, op);
case WASMOpExpressionI32::SMin:
case WASMOpExpressionI32::UMin:
case WASMOpExpressionI32::SMax:
case WASMOpExpressionI32::UMax:
return parseMinOrMaxExpressionI32(context, op);
default:
ASSERT_NOT_REACHED();
}
} else {
switch (opWithImmediate) {
case WASMOpExpressionI32WithImmediate::ConstantPoolIndex:
return parseConstantPoolIndexExpressionI32(context, immediate);
case WASMOpExpressionI32WithImmediate::Immediate:
return parseImmediateExpressionI32(context, immediate);
case WASMOpExpressionI32WithImmediate::GetLocal:
return parseGetLocalExpression(context, WASMType::I32, immediate);
default:
ASSERT_NOT_REACHED();
}
}
return 0;
}
template <class Context>
ContextExpression WASMFunctionParser::parseConstantPoolIndexExpressionI32(Context& context, uint32_t constantPoolIndex)
{
FAIL_IF_FALSE(constantPoolIndex < m_module->i32Constants().size(), "The constant pool index is incorrect.");
return context.buildImmediateI32(m_module->i32Constants()[constantPoolIndex]);
}
template <class Context>
ContextExpression WASMFunctionParser::parseConstantPoolIndexExpressionI32(Context& context)
{
uint32_t constantPoolIndex;
READ_COMPACT_UINT32_OR_FAIL(constantPoolIndex, "Cannot read the constant pool index.");
return parseConstantPoolIndexExpressionI32(context, constantPoolIndex);
}
template <class Context>
ContextExpression WASMFunctionParser::parseImmediateExpressionI32(Context& context, uint32_t immediate)
{
return context.buildImmediateI32(immediate);
}
template <class Context>
ContextExpression WASMFunctionParser::parseImmediateExpressionI32(Context& context)
{
uint32_t immediate;
READ_COMPACT_UINT32_OR_FAIL(immediate, "Cannot read the immediate.");
return parseImmediateExpressionI32(context, immediate);
}
template <class Context>
ContextExpression WASMFunctionParser::parseUnaryExpressionI32(Context& context, WASMOpExpressionI32 op)
{
ContextExpression expression = parseExpressionI32(context);
PROPAGATE_ERROR();
return context.buildUnaryI32(expression, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseBinaryExpressionI32(Context& context, WASMOpExpressionI32 op)
{
ContextExpression left = parseExpressionI32(context);
PROPAGATE_ERROR();
ContextExpression right = parseExpressionI32(context);
PROPAGATE_ERROR();
return context.buildBinaryI32(left, right, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseRelationalI32ExpressionI32(Context& context, WASMOpExpressionI32 op)
{
ContextExpression left = parseExpressionI32(context);
PROPAGATE_ERROR();
ContextExpression right = parseExpressionI32(context);
PROPAGATE_ERROR();
return context.buildRelationalI32(left, right, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseRelationalF32ExpressionI32(Context& context, WASMOpExpressionI32 op)
{
ContextExpression left = parseExpressionF32(context);
PROPAGATE_ERROR();
ContextExpression right = parseExpressionF32(context);
PROPAGATE_ERROR();
return context.buildRelationalF32(left, right, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseRelationalF64ExpressionI32(Context& context, WASMOpExpressionI32 op)
{
ContextExpression left = parseExpressionF64(context);
PROPAGATE_ERROR();
ContextExpression right = parseExpressionF64(context);
PROPAGATE_ERROR();
return context.buildRelationalF64(left, right, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseMinOrMaxExpressionI32(Context& context, WASMOpExpressionI32 op)
{
uint32_t numberOfArguments;
READ_COMPACT_UINT32_OR_FAIL(numberOfArguments, "Cannot read the number of arguments to min/max.");
FAIL_IF_FALSE(numberOfArguments >= 2, "Min/max must be passed at least 2 arguments.");
ContextExpression current = parseExpressionI32(context);
PROPAGATE_ERROR();
for (uint32_t i = 1; i < numberOfArguments; ++i) {
ContextExpression expression = parseExpressionI32(context);
PROPAGATE_ERROR();
current = context.buildMinOrMaxI32(current, expression, op);
}
return current;
}
template <class Context>
ContextExpression WASMFunctionParser::parseExpressionF32(Context& context)
{
bool hasImmediate;
WASMOpExpressionF32 op;
WASMOpExpressionF32WithImmediate opWithImmediate;
uint8_t immediate;
READ_OP_EXPRESSION_F32_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, "Cannot read the float32 expression opcode.");
if (!hasImmediate) {
switch (op) {
case WASMOpExpressionF32::ConstantPoolIndex:
return parseConstantPoolIndexExpressionF32(context);
case WASMOpExpressionF32::Immediate:
return parseImmediateExpressionF32(context);
case WASMOpExpressionF32::GetLocal:
return parseGetLocalExpression(context, WASMType::F32);
case WASMOpExpressionF32::GetGlobal:
return parseGetGlobalExpression(context, WASMType::F32);
case WASMOpExpressionF32::SetLocal:
return parseSetLocal(context, WASMOpKind::Expression, WASMExpressionType::F32);
case WASMOpExpressionF32::SetGlobal:
return parseSetGlobal(context, WASMOpKind::Expression, WASMExpressionType::F32);
case WASMOpExpressionF32::Load:
return parseLoad(context, WASMExpressionType::F32, WASMMemoryType::F32, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionF32::LoadWithOffset:
return parseLoad(context, WASMExpressionType::F32, WASMMemoryType::F32, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionF32::Store:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::F32, WASMMemoryType::F32, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionF32::StoreWithOffset:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::F32, WASMMemoryType::F32, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionF32::CallInternal:
return parseCallInternal(context, WASMOpKind::Expression, WASMExpressionType::F32);
case WASMOpExpressionF32::CallIndirect:
return parseCallIndirect(context, WASMOpKind::Expression, WASMExpressionType::F32);
case WASMOpExpressionF32::Conditional:
return parseConditional(context, WASMExpressionType::F32);
case WASMOpExpressionF32::Comma:
return parseComma(context, WASMExpressionType::F32);
case WASMOpExpressionF32::FromS32:
return parseConvertType(context, WASMExpressionType::I32, WASMExpressionType::F32, WASMTypeConversion::ConvertSigned);
case WASMOpExpressionF32::FromU32:
return parseConvertType(context, WASMExpressionType::I32, WASMExpressionType::F32, WASMTypeConversion::ConvertUnsigned);
case WASMOpExpressionF32::FromF64:
return parseConvertType(context, WASMExpressionType::F64, WASMExpressionType::F32, WASMTypeConversion::Demote);
case WASMOpExpressionF32::Negate:
case WASMOpExpressionF32::Abs:
case WASMOpExpressionF32::Ceil:
case WASMOpExpressionF32::Floor:
case WASMOpExpressionF32::Sqrt:
return parseUnaryExpressionF32(context, op);
case WASMOpExpressionF32::Add:
case WASMOpExpressionF32::Sub:
case WASMOpExpressionF32::Mul:
case WASMOpExpressionF32::Div:
return parseBinaryExpressionF32(context, op);
default:
ASSERT_NOT_REACHED();
}
} else {
switch (opWithImmediate) {
case WASMOpExpressionF32WithImmediate::ConstantPoolIndex:
return parseConstantPoolIndexExpressionF32(context, immediate);
case WASMOpExpressionF32WithImmediate::GetLocal:
return parseGetLocalExpression(context, WASMType::F32, immediate);
default:
ASSERT_NOT_REACHED();
}
}
return 0;
}
template <class Context>
ContextExpression WASMFunctionParser::parseConstantPoolIndexExpressionF32(Context& context, uint32_t constantIndex)
{
FAIL_IF_FALSE(constantIndex < m_module->f32Constants().size(), "The constant pool index is incorrect.");
return context.buildImmediateF32(m_module->f32Constants()[constantIndex]);
}
template <class Context>
ContextExpression WASMFunctionParser::parseConstantPoolIndexExpressionF32(Context& context)
{
uint32_t constantIndex;
READ_COMPACT_UINT32_OR_FAIL(constantIndex, "Cannot read the constant pool index.");
return parseConstantPoolIndexExpressionF32(context, constantIndex);
}
template <class Context>
ContextExpression WASMFunctionParser::parseImmediateExpressionF32(Context& context)
{
float immediate;
READ_FLOAT_OR_FAIL(immediate, "Cannot read the immediate.");
return context.buildImmediateF32(immediate);
}
template <class Context>
ContextExpression WASMFunctionParser::parseUnaryExpressionF32(Context& context, WASMOpExpressionF32 op)
{
ContextExpression expression = parseExpressionF32(context);
PROPAGATE_ERROR();
return context.buildUnaryF32(expression, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseBinaryExpressionF32(Context& context, WASMOpExpressionF32 op)
{
ContextExpression left = parseExpressionF32(context);
PROPAGATE_ERROR();
ContextExpression right = parseExpressionF32(context);
PROPAGATE_ERROR();
return context.buildBinaryF32(left, right, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseExpressionF64(Context& context)
{
bool hasImmediate;
WASMOpExpressionF64 op;
WASMOpExpressionF64WithImmediate opWithImmediate;
uint8_t immediate;
READ_OP_EXPRESSION_F64_OR_FAIL(hasImmediate, op, opWithImmediate, immediate, "Cannot read the float64 expression opcode.");
if (!hasImmediate) {
switch (op) {
case WASMOpExpressionF64::ConstantPoolIndex:
return parseConstantPoolIndexExpressionF64(context);
case WASMOpExpressionF64::Immediate:
return parseImmediateExpressionF64(context);
case WASMOpExpressionF64::GetLocal:
return parseGetLocalExpression(context, WASMType::F64);
case WASMOpExpressionF64::GetGlobal:
return parseGetGlobalExpression(context, WASMType::F64);
case WASMOpExpressionF64::SetLocal:
return parseSetLocal(context, WASMOpKind::Expression, WASMExpressionType::F64);
case WASMOpExpressionF64::SetGlobal:
return parseSetGlobal(context, WASMOpKind::Expression, WASMExpressionType::F64);
case WASMOpExpressionF64::Load:
return parseLoad(context, WASMExpressionType::F64, WASMMemoryType::F64, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionF64::LoadWithOffset:
return parseLoad(context, WASMExpressionType::F64, WASMMemoryType::F64, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionF64::Store:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::F64, WASMMemoryType::F64, MemoryAccessOffsetMode::NoOffset);
case WASMOpExpressionF64::StoreWithOffset:
return parseStore(context, WASMOpKind::Expression, WASMExpressionType::F64, WASMMemoryType::F64, MemoryAccessOffsetMode::WithOffset);
case WASMOpExpressionF64::CallInternal:
return parseCallInternal(context, WASMOpKind::Expression, WASMExpressionType::F64);
case WASMOpExpressionF64::CallImport:
return parseCallImport(context, WASMOpKind::Expression, WASMExpressionType::F64);
case WASMOpExpressionF64::CallIndirect:
return parseCallIndirect(context, WASMOpKind::Expression, WASMExpressionType::F64);
case WASMOpExpressionF64::Conditional:
return parseConditional(context, WASMExpressionType::F64);
case WASMOpExpressionF64::Comma:
return parseComma(context, WASMExpressionType::F64);
case WASMOpExpressionF64::FromS32:
return parseConvertType(context, WASMExpressionType::I32, WASMExpressionType::F64, WASMTypeConversion::ConvertSigned);
case WASMOpExpressionF64::FromU32:
return parseConvertType(context, WASMExpressionType::I32, WASMExpressionType::F64, WASMTypeConversion::ConvertUnsigned);
case WASMOpExpressionF64::FromF32:
return parseConvertType(context, WASMExpressionType::F32, WASMExpressionType::F64, WASMTypeConversion::Promote);
case WASMOpExpressionF64::Negate:
case WASMOpExpressionF64::Abs:
case WASMOpExpressionF64::Ceil:
case WASMOpExpressionF64::Floor:
case WASMOpExpressionF64::Sqrt:
case WASMOpExpressionF64::Cos:
case WASMOpExpressionF64::Sin:
case WASMOpExpressionF64::Tan:
case WASMOpExpressionF64::ACos:
case WASMOpExpressionF64::ASin:
case WASMOpExpressionF64::ATan:
case WASMOpExpressionF64::Exp:
case WASMOpExpressionF64::Ln:
return parseUnaryExpressionF64(context, op);
case WASMOpExpressionF64::Add:
case WASMOpExpressionF64::Sub:
case WASMOpExpressionF64::Mul:
case WASMOpExpressionF64::Div:
case WASMOpExpressionF64::Mod:
case WASMOpExpressionF64::ATan2:
case WASMOpExpressionF64::Pow:
return parseBinaryExpressionF64(context, op);
case WASMOpExpressionF64::Min:
case WASMOpExpressionF64::Max:
return parseMinOrMaxExpressionF64(context, op);
default:
ASSERT_NOT_REACHED();
}
} else {
switch (opWithImmediate) {
case WASMOpExpressionF64WithImmediate::ConstantPoolIndex:
return parseConstantPoolIndexExpressionF64(context, immediate);
case WASMOpExpressionF64WithImmediate::GetLocal:
return parseGetLocalExpression(context, WASMType::F64, immediate);
default:
ASSERT_NOT_REACHED();
}
}
return 0;
}
template <class Context>
ContextExpression WASMFunctionParser::parseConstantPoolIndexExpressionF64(Context& context, uint32_t constantIndex)
{
FAIL_IF_FALSE(constantIndex < m_module->f64Constants().size(), "The constant index is incorrect.");
return context.buildImmediateF64(m_module->f64Constants()[constantIndex]);
}
template <class Context>
ContextExpression WASMFunctionParser::parseConstantPoolIndexExpressionF64(Context& context)
{
uint32_t constantIndex;
READ_COMPACT_UINT32_OR_FAIL(constantIndex, "Cannot read the constant index.");
return parseConstantPoolIndexExpressionF64(context, constantIndex);
}
template <class Context>
ContextExpression WASMFunctionParser::parseImmediateExpressionF64(Context& context)
{
double immediate;
READ_DOUBLE_OR_FAIL(immediate, "Cannot read the immediate.");
return context.buildImmediateF64(immediate);
}
template <class Context>
ContextExpression WASMFunctionParser::parseUnaryExpressionF64(Context& context, WASMOpExpressionF64 op)
{
ContextExpression expression = parseExpressionF64(context);
PROPAGATE_ERROR();
return context.buildUnaryF64(expression, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseBinaryExpressionF64(Context& context, WASMOpExpressionF64 op)
{
ContextExpression left = parseExpressionF64(context);
PROPAGATE_ERROR();
ContextExpression right = parseExpressionF64(context);
PROPAGATE_ERROR();
return context.buildBinaryF64(left, right, op);
}
template <class Context>
ContextExpression WASMFunctionParser::parseMinOrMaxExpressionF64(Context& context, WASMOpExpressionF64 op)
{
uint32_t numberOfArguments;
READ_COMPACT_UINT32_OR_FAIL(numberOfArguments, "Cannot read the number of arguments to min/max.");
FAIL_IF_FALSE(numberOfArguments >= 2, "Min/max must be passed at least 2 arguments.");
ContextExpression current = parseExpressionF64(context);
PROPAGATE_ERROR();
for (uint32_t i = 1; i < numberOfArguments; ++i) {
ContextExpression expression = parseExpressionF64(context);
PROPAGATE_ERROR();
current = context.buildMinOrMaxF64(current, expression, op);
}
return current;
}
template <class Context>
ContextExpression WASMFunctionParser::parseExpressionVoid(Context& context)
{
WASMOpExpressionVoid op;
READ_OP_EXPRESSION_VOID_OR_FAIL(op, "Cannot read the void expression opcode.");
switch (op) {
case WASMOpExpressionVoid::CallInternal:
return parseCallInternal(context, WASMOpKind::Expression, WASMExpressionType::Void);
case WASMOpExpressionVoid::CallIndirect:
return parseCallIndirect(context, WASMOpKind::Expression, WASMExpressionType::Void);
case WASMOpExpressionVoid::CallImport:
return parseCallImport(context, WASMOpKind::Expression, WASMExpressionType::Void);
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
template <class Context>
ContextExpression WASMFunctionParser::parseGetLocalExpression(Context& context, WASMType type, uint32_t localIndex)
{
FAIL_IF_FALSE(localIndex < m_localTypes.size(), "The local index is incorrect.");
FAIL_IF_FALSE(m_localTypes[localIndex] == type, "Expected a local of type " + nameOfType(type) + '.');
return context.buildGetLocal(localIndex, type);
}
template <class Context>
ContextExpression WASMFunctionParser::parseGetLocalExpression(Context& context, WASMType type)
{
uint32_t localIndex;
READ_COMPACT_UINT32_OR_FAIL(localIndex, "Cannot read the local index.");
return parseGetLocalExpression(context, type, localIndex);
}
template <class Context>
ContextExpression WASMFunctionParser::parseGetGlobalExpression(Context& context, WASMType type)
{
uint32_t globalIndex;
READ_COMPACT_UINT32_OR_FAIL(globalIndex, "Cannot read the global index.");
FAIL_IF_FALSE(globalIndex < m_module->globalVariableTypes().size(), "The global index is incorrect.");
FAIL_IF_FALSE(m_module->globalVariableTypes()[globalIndex] == type, "Expected a global of type " + nameOfType(type) + '.');
return context.buildGetGlobal(globalIndex, type);
}
template <class Context>
ContextExpression WASMFunctionParser::parseSetLocal(Context& context, WASMOpKind opKind, WASMExpressionType expressionType, uint32_t localIndex)
{
FAIL_IF_FALSE(localIndex < m_localTypes.size(), "The local variable index is incorrect.");
WASMType type = m_localTypes[localIndex];
if (opKind == WASMOpKind::Expression)
FAIL_IF_FALSE(expressionType == WASMExpressionType(type), "The type doesn't match.");
ContextExpression expression = parseExpression(context, WASMExpressionType(type));
PROPAGATE_ERROR();
return context.buildSetLocal(opKind, localIndex, expression, type);
}
template <class Context>
ContextExpression WASMFunctionParser::parseSetLocal(Context& context, WASMOpKind opKind, WASMExpressionType expressionType)
{
uint32_t localIndex;
READ_COMPACT_UINT32_OR_FAIL(localIndex, "Cannot read the local index.");
return parseSetLocal(context, opKind, expressionType, localIndex);
}
template <class Context>
ContextExpression WASMFunctionParser::parseSetGlobal(Context& context, WASMOpKind opKind, WASMExpressionType expressionType, uint32_t globalIndex)
{
FAIL_IF_FALSE(globalIndex < m_module->globalVariableTypes().size(), "The global index is incorrect.");
WASMType type = m_module->globalVariableTypes()[globalIndex];
if (opKind == WASMOpKind::Expression)
FAIL_IF_FALSE(expressionType == WASMExpressionType(type), "The type doesn't match.");
ContextExpression expression = parseExpression(context, WASMExpressionType(type));
PROPAGATE_ERROR();
return context.buildSetGlobal(opKind, globalIndex, expression, type);
}
template <class Context>
ContextExpression WASMFunctionParser::parseSetGlobal(Context& context, WASMOpKind opKind, WASMExpressionType expressionType)
{
uint32_t globalIndex;
READ_COMPACT_UINT32_OR_FAIL(globalIndex, "Cannot read the global index.");
return parseSetGlobal(context, opKind, expressionType, globalIndex);
}
template <class Context>
ContextMemoryAddress WASMFunctionParser::parseMemoryAddress(Context& context, MemoryAccessOffsetMode offsetMode)
{
uint32_t offset = 0;
if (offsetMode == MemoryAccessOffsetMode::WithOffset)
READ_COMPACT_UINT32_OR_FAIL(offset, "Cannot read the address offset.");
ContextExpression index = parseExpressionI32(context);
PROPAGATE_ERROR();
return ContextMemoryAddress(index, offset);
}
template <class Context>
ContextExpression WASMFunctionParser::parseLoad(Context& context, WASMExpressionType expressionType, WASMMemoryType memoryType, MemoryAccessOffsetMode offsetMode, MemoryAccessConversion conversion)
{
FAIL_IF_FALSE(m_module->arrayBuffer(), "An ArrayBuffer is not provided.");
const ContextMemoryAddress& memoryAddress = parseMemoryAddress(context, offsetMode);
PROPAGATE_ERROR();
return context.buildLoad(memoryAddress, expressionType, memoryType, conversion);
}
template <class Context>
ContextExpression WASMFunctionParser::parseStore(Context& context, WASMOpKind opKind, WASMExpressionType expressionType, WASMMemoryType memoryType, MemoryAccessOffsetMode offsetMode)
{
FAIL_IF_FALSE(m_module->arrayBuffer(), "An ArrayBuffer is not provided.");
const ContextMemoryAddress& memoryAddress = parseMemoryAddress(context, offsetMode);
PROPAGATE_ERROR();
ContextExpression value = parseExpression(context, expressionType);
PROPAGATE_ERROR();
return context.buildStore(opKind, memoryAddress, expressionType, memoryType, value);
}
template <class Context>
ContextExpressionList WASMFunctionParser::parseCallArguments(Context& context, const Vector<WASMType>& arguments)
{
ContextExpressionList argumentList;
for (size_t i = 0; i < arguments.size(); ++i) {
ContextExpression expression = parseExpression(context, WASMExpressionType(arguments[i]));
PROPAGATE_ERROR();
context.appendExpressionList(argumentList, expression);
}
return argumentList;
}
template <class Context>
ContextExpression WASMFunctionParser::parseCallInternal(Context& context, WASMOpKind opKind, WASMExpressionType returnType)
{
uint32_t functionIndex;
READ_COMPACT_UINT32_OR_FAIL(functionIndex, "Cannot read the function index.");
FAIL_IF_FALSE(functionIndex < m_module->functionDeclarations().size(), "The function index is incorrect.");
const WASMSignature& signature = m_module->signatures()[m_module->functionDeclarations()[functionIndex].signatureIndex];
if (opKind == WASMOpKind::Expression)
FAIL_IF_FALSE(signature.returnType == returnType, "Wrong return type.");
ContextExpressionList argumentList = parseCallArguments(context, signature.arguments);
PROPAGATE_ERROR();
return context.buildCallInternal(functionIndex, argumentList, signature, returnType);
}
template <class Context>
ContextExpression WASMFunctionParser::parseCallIndirect(Context& context, WASMOpKind opKind, WASMExpressionType returnType)
{
uint32_t functionPointerTableIndex;
READ_COMPACT_UINT32_OR_FAIL(functionPointerTableIndex, "Cannot read the function pointer table index.");
FAIL_IF_FALSE(functionPointerTableIndex < m_module->functionPointerTables().size(), "The function pointer table index is incorrect.");
const WASMFunctionPointerTable& functionPointerTable = m_module->functionPointerTables()[functionPointerTableIndex];
const WASMSignature& signature = m_module->signatures()[functionPointerTable.signatureIndex];
if (opKind == WASMOpKind::Expression)
FAIL_IF_FALSE(signature.returnType == returnType, "Wrong return type.");
ContextExpression index = parseExpressionI32(context);
PROPAGATE_ERROR();
ContextExpressionList argumentList = parseCallArguments(context, signature.arguments);
PROPAGATE_ERROR();
return context.buildCallIndirect(functionPointerTableIndex, index, argumentList, signature, returnType);
}
template <class Context>
ContextExpression WASMFunctionParser::parseCallImport(Context& context, WASMOpKind opKind, WASMExpressionType returnType)
{
uint32_t functionImportSignatureIndex;
READ_COMPACT_UINT32_OR_FAIL(functionImportSignatureIndex, "Cannot read the function import signature index.");
FAIL_IF_FALSE(functionImportSignatureIndex < m_module->functionImportSignatures().size(), "The function import signature index is incorrect.");
const WASMFunctionImportSignature& functionImportSignature = m_module->functionImportSignatures()[functionImportSignatureIndex];
const WASMSignature& signature = m_module->signatures()[functionImportSignature.signatureIndex];
if (opKind == WASMOpKind::Expression)
FAIL_IF_FALSE(signature.returnType == returnType, "Wrong return type.");
ContextExpressionList argumentList = parseCallArguments(context, signature.arguments);
PROPAGATE_ERROR();
return context.buildCallImport(functionImportSignature.functionImportIndex, argumentList, signature, returnType);
}
template <class Context>
ContextExpression WASMFunctionParser::parseConditional(Context& context, WASMExpressionType expressionType)
{
ContextJumpTarget elseTarget;
ContextJumpTarget end;
ContextExpression condition = parseExpressionI32(context);
PROPAGATE_ERROR();
context.jumpToTargetIf(Context::JumpCondition::Zero, condition, elseTarget);
parseExpression(context, expressionType);
PROPAGATE_ERROR();
context.jumpToTarget(end);
context.linkTarget(elseTarget);
// We use discard() here to decrement the stack top in the baseline JIT.
context.discard(UNUSED);
parseExpression(context, expressionType);
PROPAGATE_ERROR();
context.linkTarget(end);
return UNUSED;
}
template <class Context>
ContextExpression WASMFunctionParser::parseComma(Context& context, WASMExpressionType expressionType)
{
WASMExpressionType leftExpressionType;
READ_EXPRESSION_TYPE_OR_FAIL(leftExpressionType, "Cannot read the expression type.");
ContextExpression leftExpression = parseExpression(context, leftExpressionType);
PROPAGATE_ERROR();
if (leftExpressionType != WASMExpressionType::Void)
context.discard(leftExpression);
return parseExpression(context, expressionType);
}
template <class Context>
ContextExpression WASMFunctionParser::parseConvertType(Context& context, WASMExpressionType fromType, WASMExpressionType toType, WASMTypeConversion conversion)
{
ContextExpression expression = parseExpression(context, fromType);
PROPAGATE_ERROR();
return context.buildConvertType(expression, fromType, toType, conversion);
}
} // namespace JSC
#endif // ENABLE(WEBASSEMBLY)
| {
"pile_set_name": "Github"
} |
#Generated by Git-Commit-Id-Plugin
#Sun Jul 27 06:59:55 PDT 2014
git.commit.id.abbrev=a3a5fc7
[email protected]
git.commit.message.full=Move CF domain\n
git.commit.id=a3a5fc7a61f614c4e5e3c2aaee83ab209409c5b9
git.commit.message.short=Move CF domain
git.commit.user.name=Dave Syer
git.build.user.name=Dave Syer
git.commit.id.describe=a3a5fc7
[email protected]
git.branch=master
git.commit.time=2014-07-24T11\:17\:55-0700
git.build.time=2014-07-27T06\:59\:55-0700
[email protected]\:spring-platform-samples/eureka.git
| {
"pile_set_name": "Github"
} |
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.test.internal.util;
/**
* @author Emmanuel Bernard
*/
public class PositiveConstraintValidator extends BoundariesConstraintValidator<Positive> {
@Override
public void initialize(Positive constraintAnnotation) {
super.initialize( 0, Integer.MAX_VALUE );
}
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "test/pagespeed/system/tcp_server_thread_for_testing.h"
#include <sys/socket.h>
#include <cstdlib>
#include "apr_network_io.h"
#include "base/logging.h"
#include "pagespeed/kernel/base/abstract_mutex.h"
#include "pagespeed/system/apr_thread_compatible_pool.h"
#include "test/pagespeed/kernel/base/gtest.h"
namespace net_instaweb {
TcpServerThreadForTesting::TcpServerThreadForTesting(
apr_port_t listen_port, StringPiece name, ThreadSystem* thread_system)
: Thread(thread_system, name, ThreadSystem::kJoinable),
mutex_(thread_system->NewMutex()),
ready_notify_(mutex_->NewCondvar()),
pool_(AprCreateThreadCompatiblePool(nullptr)),
requested_listen_port_(listen_port),
actual_listening_port_(0),
listen_sock_(nullptr),
terminating_(false),
is_shut_down_(false) {}
void TcpServerThreadForTesting::ShutDown() {
// We want to ensure that the thread is terminated and it has accepted exactly
// one connection. Consider several scenarios:
// 1. Thread was not started before destructor is called. Then the Join()
// below will fail as expected.
// 2. Thread was started and our mutex-guarded block happened after creation
// of listen_sock_. Then we will shut down the socket so accept() in the
// thread will fail and the thread will close the socket and terminate.
// 3. Thread was started and our mutex-guarded block happened before creation
// of listen_sock_. It's extremely unlikely race as it requires the
// destructor to be called right after Start(). If it ever happens, CHECK()
// in the thread will fail.
{
ScopedMutex lock(mutex_.get());
terminating_ = true;
if (listen_sock_) {
apr_socket_shutdown(listen_sock_, APR_SHUTDOWN_READWRITE);
}
}
this->Join();
if (pool_ != nullptr) {
apr_pool_destroy(pool_);
pool_ = nullptr;
}
is_shut_down_ = true;
}
TcpServerThreadForTesting::~TcpServerThreadForTesting() {
CHECK(is_shut_down_)
<< "TcpServerThreadForTesting::ShutDown() was not called";
}
// static
void TcpServerThreadForTesting::PickListenPortOnce(
apr_port_t* static_port_number) {
// A listen_port of 0 means the system will pick for us.
*static_port_number = 0;
// Looks like creating a socket and looking at its port is the easiest way
// to find an available port.
apr_pool_t* pool = AprCreateThreadCompatiblePool(nullptr);
apr_socket_t* sock;
CreateAndBindSocket(pool, &sock, static_port_number);
apr_socket_close(sock);
apr_pool_destroy(pool);
CHECK_NE(*static_port_number, 0);
}
void TcpServerThreadForTesting::Run() {
// We do not want to hold mutex during accept(), hence the local copy.
apr_socket_t* local_listen_sock;
{
ScopedMutex lock(mutex_.get());
CHECK(!terminating_);
local_listen_sock = listen_sock_ = CreateAndBindSocket();
}
apr_socket_t* accepted_socket;
apr_status_t status =
apr_socket_accept(&accepted_socket, local_listen_sock, pool_);
EXPECT_EQ(APR_SUCCESS, status)
<< "TcpServerThreadForTesting: "
"apr_socket_accept failed (did not receive a connection?)";
if (status == APR_SUCCESS) {
HandleClientConnection(accepted_socket);
}
{
ScopedMutex lock(mutex_.get());
apr_socket_close(listen_sock_);
listen_sock_ = nullptr;
}
}
apr_port_t TcpServerThreadForTesting::GetListeningPort() {
ScopedMutex lock(mutex_.get());
while (actual_listening_port_ == 0) {
ready_notify_->Wait();
}
return actual_listening_port_;
}
/* static */ void TcpServerThreadForTesting::CreateAndBindSocket(
apr_pool_t* pool, apr_socket_t** socket, apr_port_t* port) {
// Create TCP socket with SO_REUSEADDR.
apr_status_t status =
apr_socket_create(socket, APR_INET, SOCK_STREAM, APR_PROTO_TCP, pool);
CHECK_EQ(status, APR_SUCCESS) << "CreateAndBindSocket apr_socket_create";
status = apr_socket_opt_set(*socket, APR_SO_REUSEADDR, 1);
CHECK_EQ(status, APR_SUCCESS) << "CreateAndBindSocket apr_socket_opt_set";
// port may be zero, in which case apr_socket_bind will pick a port for us.
apr_sockaddr_t* sa;
status = apr_sockaddr_info_get(&sa, "127.0.0.1", APR_INET, *port,
0 /* flags */, pool);
CHECK_EQ(status, APR_SUCCESS) << "CreateAndBindSocket apr_sockaddr_info_get";
// bind and listen.
status = apr_socket_bind(*socket, sa);
CHECK_EQ(status, APR_SUCCESS) << "CreateAndBindSocket apr_socket_bind";
status = apr_socket_listen(*socket, 1 /* backlog */);
CHECK_EQ(status, APR_SUCCESS) << "CreateAndBindSocket apr_socket_listen";
// Now the socket is bound and listening, find the local port we're actually
// using. If requested_listen_port_ is non-zero, they really should match.
apr_sockaddr_t* bound_sa;
status = apr_socket_addr_get(&bound_sa, APR_LOCAL, *socket);
CHECK_EQ(status, APR_SUCCESS) << "CreateAndBindSocket apr_socket_addr_get";
if (*port != 0) {
// If a specific port was requested, it should be used.
CHECK_EQ(*port, bound_sa->port);
}
*port = bound_sa->port;
}
apr_socket_t* TcpServerThreadForTesting::CreateAndBindSocket() {
apr_socket_t* sock;
apr_port_t port = requested_listen_port_;
CreateAndBindSocket(pool_, &sock, &port);
actual_listening_port_ = port;
ready_notify_->Broadcast();
return sock;
}
} // namespace net_instaweb
| {
"pile_set_name": "Github"
} |
package csharp
import (
"github.com/prasmussen/glot-code-runner/cmd"
"github.com/prasmussen/glot-code-runner/util"
"path/filepath"
)
func Run(files []string, stdin string) (string, string, error) {
workDir := filepath.Dir(files[0])
binName := "a.exe"
sourceFiles := util.FilterByExtension(files, "cs")
args := append([]string{"mcs", "-out:" + binName}, sourceFiles...)
stdout, stderr, err := cmd.Run(workDir, args...)
if err != nil {
return stdout, stderr, err
}
binPath := filepath.Join(workDir, binName)
return cmd.RunStdin(workDir, stdin, "mono", binPath)
}
| {
"pile_set_name": "Github"
} |
// +build seccomp
package seccomp // import "github.com/docker/docker/profiles/seccomp"
import (
"github.com/opencontainers/runtime-spec/specs-go"
"golang.org/x/sys/unix"
)
func arches() []Architecture {
return []Architecture{
{
Arch: specs.ArchX86_64,
SubArches: []specs.Arch{specs.ArchX86, specs.ArchX32},
},
{
Arch: specs.ArchAARCH64,
SubArches: []specs.Arch{specs.ArchARM},
},
{
Arch: specs.ArchMIPS64,
SubArches: []specs.Arch{specs.ArchMIPS, specs.ArchMIPS64N32},
},
{
Arch: specs.ArchMIPS64N32,
SubArches: []specs.Arch{specs.ArchMIPS, specs.ArchMIPS64},
},
{
Arch: specs.ArchMIPSEL64,
SubArches: []specs.Arch{specs.ArchMIPSEL, specs.ArchMIPSEL64N32},
},
{
Arch: specs.ArchMIPSEL64N32,
SubArches: []specs.Arch{specs.ArchMIPSEL, specs.ArchMIPSEL64},
},
{
Arch: specs.ArchS390X,
SubArches: []specs.Arch{specs.ArchS390},
},
}
}
// DefaultProfile defines the allowed syscalls for the default seccomp profile.
func DefaultProfile() *Seccomp {
syscalls := []*Syscall{
{
Names: []string{
"accept",
"accept4",
"access",
"adjtimex",
"alarm",
"bind",
"brk",
"capget",
"capset",
"chdir",
"chmod",
"chown",
"chown32",
"clock_adjtime",
"clock_adjtime64",
"clock_getres",
"clock_getres_time64",
"clock_gettime",
"clock_gettime64",
"clock_nanosleep",
"clock_nanosleep_time64",
"close",
"connect",
"copy_file_range",
"creat",
"dup",
"dup2",
"dup3",
"epoll_create",
"epoll_create1",
"epoll_ctl",
"epoll_ctl_old",
"epoll_pwait",
"epoll_wait",
"epoll_wait_old",
"eventfd",
"eventfd2",
"execve",
"execveat",
"exit",
"exit_group",
"faccessat",
"faccessat2",
"fadvise64",
"fadvise64_64",
"fallocate",
"fanotify_mark",
"fchdir",
"fchmod",
"fchmodat",
"fchown",
"fchown32",
"fchownat",
"fcntl",
"fcntl64",
"fdatasync",
"fgetxattr",
"flistxattr",
"flock",
"fork",
"fremovexattr",
"fsetxattr",
"fstat",
"fstat64",
"fstatat64",
"fstatfs",
"fstatfs64",
"fsync",
"ftruncate",
"ftruncate64",
"futex",
"futex_time64",
"futimesat",
"getcpu",
"getcwd",
"getdents",
"getdents64",
"getegid",
"getegid32",
"geteuid",
"geteuid32",
"getgid",
"getgid32",
"getgroups",
"getgroups32",
"getitimer",
"getpeername",
"getpgid",
"getpgrp",
"getpid",
"getppid",
"getpriority",
"getrandom",
"getresgid",
"getresgid32",
"getresuid",
"getresuid32",
"getrlimit",
"get_robust_list",
"getrusage",
"getsid",
"getsockname",
"getsockopt",
"get_thread_area",
"gettid",
"gettimeofday",
"getuid",
"getuid32",
"getxattr",
"inotify_add_watch",
"inotify_init",
"inotify_init1",
"inotify_rm_watch",
"io_cancel",
"ioctl",
"io_destroy",
"io_getevents",
"io_pgetevents",
"io_pgetevents_time64",
"ioprio_get",
"ioprio_set",
"io_setup",
"io_submit",
"io_uring_enter",
"io_uring_register",
"io_uring_setup",
"ipc",
"kill",
"lchown",
"lchown32",
"lgetxattr",
"link",
"linkat",
"listen",
"listxattr",
"llistxattr",
"_llseek",
"lremovexattr",
"lseek",
"lsetxattr",
"lstat",
"lstat64",
"madvise",
"membarrier",
"memfd_create",
"mincore",
"mkdir",
"mkdirat",
"mknod",
"mknodat",
"mlock",
"mlock2",
"mlockall",
"mmap",
"mmap2",
"mprotect",
"mq_getsetattr",
"mq_notify",
"mq_open",
"mq_timedreceive",
"mq_timedreceive_time64",
"mq_timedsend",
"mq_timedsend_time64",
"mq_unlink",
"mremap",
"msgctl",
"msgget",
"msgrcv",
"msgsnd",
"msync",
"munlock",
"munlockall",
"munmap",
"nanosleep",
"newfstatat",
"_newselect",
"open",
"openat",
"openat2",
"pause",
"pipe",
"pipe2",
"poll",
"ppoll",
"ppoll_time64",
"prctl",
"pread64",
"preadv",
"preadv2",
"prlimit64",
"pselect6",
"pselect6_time64",
"pwrite64",
"pwritev",
"pwritev2",
"read",
"readahead",
"readlink",
"readlinkat",
"readv",
"recv",
"recvfrom",
"recvmmsg",
"recvmmsg_time64",
"recvmsg",
"remap_file_pages",
"removexattr",
"rename",
"renameat",
"renameat2",
"restart_syscall",
"rmdir",
"rseq",
"rt_sigaction",
"rt_sigpending",
"rt_sigprocmask",
"rt_sigqueueinfo",
"rt_sigreturn",
"rt_sigsuspend",
"rt_sigtimedwait",
"rt_sigtimedwait_time64",
"rt_tgsigqueueinfo",
"sched_getaffinity",
"sched_getattr",
"sched_getparam",
"sched_get_priority_max",
"sched_get_priority_min",
"sched_getscheduler",
"sched_rr_get_interval",
"sched_rr_get_interval_time64",
"sched_setaffinity",
"sched_setattr",
"sched_setparam",
"sched_setscheduler",
"sched_yield",
"seccomp",
"select",
"semctl",
"semget",
"semop",
"semtimedop",
"semtimedop_time64",
"send",
"sendfile",
"sendfile64",
"sendmmsg",
"sendmsg",
"sendto",
"setfsgid",
"setfsgid32",
"setfsuid",
"setfsuid32",
"setgid",
"setgid32",
"setgroups",
"setgroups32",
"setitimer",
"setpgid",
"setpriority",
"setregid",
"setregid32",
"setresgid",
"setresgid32",
"setresuid",
"setresuid32",
"setreuid",
"setreuid32",
"setrlimit",
"set_robust_list",
"setsid",
"setsockopt",
"set_thread_area",
"set_tid_address",
"setuid",
"setuid32",
"setxattr",
"shmat",
"shmctl",
"shmdt",
"shmget",
"shutdown",
"sigaltstack",
"signalfd",
"signalfd4",
"sigprocmask",
"sigreturn",
"socket",
"socketcall",
"socketpair",
"splice",
"stat",
"stat64",
"statfs",
"statfs64",
"statx",
"symlink",
"symlinkat",
"sync",
"sync_file_range",
"syncfs",
"sysinfo",
"tee",
"tgkill",
"time",
"timer_create",
"timer_delete",
"timer_getoverrun",
"timer_gettime",
"timer_gettime64",
"timer_settime",
"timer_settime64",
"timerfd_create",
"timerfd_gettime",
"timerfd_gettime64",
"timerfd_settime",
"timerfd_settime64",
"times",
"tkill",
"truncate",
"truncate64",
"ugetrlimit",
"umask",
"uname",
"unlink",
"unlinkat",
"utime",
"utimensat",
"utimensat_time64",
"utimes",
"vfork",
"vmsplice",
"wait4",
"waitid",
"waitpid",
"write",
"writev",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
},
{
Names: []string{"ptrace"},
Action: specs.ActAllow,
Includes: Filter{
MinKernel: "4.8",
},
},
{
Names: []string{"personality"},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{
{
Index: 0,
Value: 0x0,
Op: specs.OpEqualTo,
},
},
},
{
Names: []string{"personality"},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{
{
Index: 0,
Value: 0x0008,
Op: specs.OpEqualTo,
},
},
},
{
Names: []string{"personality"},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{
{
Index: 0,
Value: 0x20000,
Op: specs.OpEqualTo,
},
},
},
{
Names: []string{"personality"},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{
{
Index: 0,
Value: 0x20008,
Op: specs.OpEqualTo,
},
},
},
{
Names: []string{"personality"},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{
{
Index: 0,
Value: 0xffffffff,
Op: specs.OpEqualTo,
},
},
},
{
Names: []string{
"sync_file_range2",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Arches: []string{"ppc64le"},
},
},
{
Names: []string{
"arm_fadvise64_64",
"arm_sync_file_range",
"sync_file_range2",
"breakpoint",
"cacheflush",
"set_tls",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Arches: []string{"arm", "arm64"},
},
},
{
Names: []string{
"arch_prctl",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Arches: []string{"amd64", "x32"},
},
},
{
Names: []string{
"modify_ldt",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Arches: []string{"amd64", "x32", "x86"},
},
},
{
Names: []string{
"s390_pci_mmio_read",
"s390_pci_mmio_write",
"s390_runtime_instr",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Arches: []string{"s390", "s390x"},
},
},
{
Names: []string{
"open_by_handle_at",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_DAC_READ_SEARCH"},
},
},
{
Names: []string{
"bpf",
"clone",
"fanotify_init",
"lookup_dcookie",
"mount",
"name_to_handle_at",
"perf_event_open",
"quotactl",
"setdomainname",
"sethostname",
"setns",
"syslog",
"umount",
"umount2",
"unshare",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_ADMIN"},
},
},
{
Names: []string{
"clone",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{
{
Index: 0,
Value: unix.CLONE_NEWNS | unix.CLONE_NEWUTS | unix.CLONE_NEWIPC | unix.CLONE_NEWUSER | unix.CLONE_NEWPID | unix.CLONE_NEWNET | unix.CLONE_NEWCGROUP,
ValueTwo: 0,
Op: specs.OpMaskedEqual,
},
},
Excludes: Filter{
Caps: []string{"CAP_SYS_ADMIN"},
Arches: []string{"s390", "s390x"},
},
},
{
Names: []string{
"clone",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{
{
Index: 1,
Value: unix.CLONE_NEWNS | unix.CLONE_NEWUTS | unix.CLONE_NEWIPC | unix.CLONE_NEWUSER | unix.CLONE_NEWPID | unix.CLONE_NEWNET | unix.CLONE_NEWCGROUP,
ValueTwo: 0,
Op: specs.OpMaskedEqual,
},
},
Comment: "s390 parameter ordering for clone is different",
Includes: Filter{
Arches: []string{"s390", "s390x"},
},
Excludes: Filter{
Caps: []string{"CAP_SYS_ADMIN"},
},
},
{
Names: []string{
"reboot",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_BOOT"},
},
},
{
Names: []string{
"chroot",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_CHROOT"},
},
},
{
Names: []string{
"delete_module",
"init_module",
"finit_module",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_MODULE"},
},
},
{
Names: []string{
"acct",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_PACCT"},
},
},
{
Names: []string{
"kcmp",
"process_vm_readv",
"process_vm_writev",
"ptrace",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_PTRACE"},
},
},
{
Names: []string{
"iopl",
"ioperm",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_RAWIO"},
},
},
{
Names: []string{
"settimeofday",
"stime",
"clock_settime",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_TIME"},
},
},
{
Names: []string{
"vhangup",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_TTY_CONFIG"},
},
},
{
Names: []string{
"get_mempolicy",
"mbind",
"set_mempolicy",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYS_NICE"},
},
},
{
Names: []string{
"syslog",
},
Action: specs.ActAllow,
Args: []*specs.LinuxSeccompArg{},
Includes: Filter{
Caps: []string{"CAP_SYSLOG"},
},
},
}
return &Seccomp{
DefaultAction: specs.ActErrno,
ArchMap: arches(),
Syscalls: syscalls,
}
}
| {
"pile_set_name": "Github"
} |
from typing import Any, List, Optional, Sequence, Tuple, Type
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.backends.ddl_references import Statement
from django.db.models.base import Model
from django.db.models.query_utils import Q
class Index:
model: Type[Model]
suffix: str = ...
max_name_length: int = ...
fields: Sequence[str] = ...
fields_orders: Sequence[Tuple[str, str]] = ...
name: str = ...
db_tablespace: Optional[str] = ...
opclasses: Sequence[str] = ...
condition: Optional[Q] = ...
def __init__(
self,
*,
fields: Sequence[str] = ...,
name: Optional[str] = ...,
db_tablespace: Optional[str] = ...,
opclasses: Sequence[str] = ...,
condition: Optional[Q] = ...
) -> None: ...
def check_name(self) -> List[str]: ...
def create_sql(
self, model: Type[Model], schema_editor: BaseDatabaseSchemaEditor, using: str = ...
) -> Statement: ...
def remove_sql(self, model: Type[Model], schema_editor: BaseDatabaseSchemaEditor) -> str: ...
def deconstruct(self) -> Any: ...
def clone(self) -> Index: ...
def set_name_with_model(self, model: Type[Model]) -> None: ...
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2015 PLUMgrid, http://plumgrid.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <linux/bpf.h>
#include "libbpf.h"
#include "bpf_load.h"
struct pair {
long long val;
__u64 ip;
};
static __u64 time_get_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000000000ull + ts.tv_nsec;
}
static void print_old_objects(int fd)
{
long long val = time_get_ns();
__u64 key, next_key;
struct pair v;
key = write(1, "\e[1;1H\e[2J", 12); /* clear screen */
key = -1;
while (bpf_get_next_key(map_fd[0], &key, &next_key) == 0) {
bpf_lookup_elem(map_fd[0], &next_key, &v);
key = next_key;
if (val - v.val < 1000000000ll)
/* object was allocated more then 1 sec ago */
continue;
printf("obj 0x%llx is %2lldsec old was allocated at ip %llx\n",
next_key, (val - v.val) / 1000000000ll, v.ip);
}
}
int main(int ac, char **argv)
{
char filename[256];
int i;
snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
if (load_bpf_file(filename)) {
printf("%s", bpf_log_buf);
return 1;
}
for (i = 0; ; i++) {
print_old_objects(map_fd[1]);
sleep(1);
}
return 0;
}
| {
"pile_set_name": "Github"
} |
{
"name": "xml2js",
"description": "Simple XML to JavaScript object converter.",
"keywords": [
"xml",
"json"
],
"homepage": "https://github.com/Leonidas-from-XIV/node-xml2js",
"version": "0.4.4",
"author": {
"name": "Marek Kubica",
"email": "[email protected]",
"url": "http://xivilization.net"
},
"contributors": [
{
"name": "maqr",
"email": "[email protected]",
"url": "https://github.com/maqr"
},
{
"name": "Ben Weaver",
"url": "http://benweaver.com/"
},
{
"name": "Jae Kwon",
"url": "https://github.com/jaekwon"
},
{
"name": "Jim Robert"
},
{
"name": "Ștefan Rusu",
"url": "http://www.saltwaterc.eu/"
},
{
"name": "Carter Cole",
"email": "[email protected]",
"url": "http://cartercole.com/"
},
{
"name": "Kurt Raschke",
"email": "[email protected]",
"url": "http://www.kurtraschke.com/"
},
{
"name": "Contra",
"email": "[email protected]",
"url": "https://github.com/Contra"
},
{
"name": "Marcelo Diniz",
"email": "[email protected]",
"url": "https://github.com/mdiniz"
},
{
"name": "Michael Hart",
"url": "https://github.com/mhart"
},
{
"name": "Zachary Scott",
"email": "[email protected]",
"url": "http://zacharyscott.net/"
},
{
"name": "Raoul Millais",
"url": "https://github.com/raoulmillais"
},
{
"name": "Salsita Software",
"url": "http://www.salsitasoft.com/"
},
{
"name": "Mike Schilling",
"email": "[email protected]",
"url": "http://www.emotive.com/"
},
{
"name": "Jackson Tian",
"email": "[email protected]",
"url": "http://weibo.com/shyvo"
},
{
"name": "Mikhail Zyatin",
"email": "[email protected]",
"url": "https://github.com/Sitin"
},
{
"name": "Chris Tavares",
"email": "[email protected]",
"url": "https://github.com/christav"
},
{
"name": "Frank Xu",
"email": "[email protected]",
"url": "http://f2e.us/"
},
{
"name": "Guido D'Albore",
"email": "[email protected]",
"url": "http://www.bitstorm.it/"
},
{
"name": "Jack Senechal",
"url": "http://jacksenechal.com/"
},
{
"name": "Matthias Hölzl",
"email": "[email protected]",
"url": "https://github.com/hoelzl"
},
{
"name": "Camille Reynders",
"email": "[email protected]",
"url": "http://www.creynders.be/"
},
{
"name": "Taylor Gautier",
"url": "https://github.com/tsgautier"
},
{
"name": "Todd Bryan",
"url": "https://github.com/toddrbryan"
},
{
"name": "Leore Avidar",
"email": "[email protected]",
"url": "http://leoreavidar.com/"
},
{
"name": "Dave Aitken",
"email": "[email protected]",
"url": "http://www.actionshrimp.com/"
}
],
"main": "./lib/xml2js",
"directories": {
"lib": "./lib"
},
"scripts": {
"test": "zap"
},
"repository": {
"type": "git",
"url": "https://github.com/Leonidas-from-XIV/node-xml2js.git"
},
"dependencies": {
"sax": "0.6.x",
"xmlbuilder": ">=1.0.0"
},
"devDependencies": {
"coffee-script": ">=1.7.1",
"zap": ">=0.2.6",
"docco": ">=0.6.2",
"diff": ">=1.0.8"
},
"licenses": [
{
"type": "MIT",
"url": "https://raw.github.com/Leonidas-from-XIV/node-xml2js/master/LICENSE"
}
],
"readme": "node-xml2js\n===========\n\nEver had the urge to parse XML? And wanted to access the data in some sane,\neasy way? Don't want to compile a C parser, for whatever reason? Then xml2js is\nwhat you're looking for!\n\nDescription\n===========\n\nSimple XML to JavaScript object converter. It supports bi-directional conversion.\nUses [sax-js](https://github.com/isaacs/sax-js/) and\n[xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js/).\n\nNote: If you're looking for a full DOM parser, you probably want\n[JSDom](https://github.com/tmpvar/jsdom).\n\nInstallation\n============\n\nSimplest way to install `xml2js` is to use [npm](http://npmjs.org), just `npm\ninstall xml2js` which will download xml2js and all dependencies.\n\nUsage\n=====\n\nNo extensive tutorials required because you are a smart developer! The task of\nparsing XML should be an easy one, so let's make it so! Here's some examples.\n\nShoot-and-forget usage\n----------------------\n\nYou want to parse XML as simple and easy as possible? It's dangerous to go\nalone, take this:\n\n```javascript\nvar parseString = require('xml2js').parseString;\nvar xml = \"<root>Hello xml2js!</root>\"\nparseString(xml, function (err, result) {\n console.dir(result);\n});\n```\n\nCan't get easier than this, right? This works starting with `xml2js` 0.2.3.\nWith CoffeeScript it looks like this:\n\n```coffeescript\n{parseString} = require 'xml2js'\nxml = \"<root>Hello xml2js!</root>\"\nparseString xml, (err, result) ->\n console.dir result\n```\n\nIf you need some special options, fear not, `xml2js` supports a number of\noptions (see below), you can specify these as second argument:\n\n```javascript\nparseString(xml, {trim: true}, function (err, result) {\n});\n```\n\nSimple as pie usage\n-------------------\n\nThat's right, if you have been using xml-simple or a home-grown\nwrapper, this was added in 0.1.11 just for you:\n\n```javascript\nvar fs = require('fs'),\n xml2js = require('xml2js');\n\nvar parser = new xml2js.Parser();\nfs.readFile(__dirname + '/foo.xml', function(err, data) {\n parser.parseString(data, function (err, result) {\n console.dir(result);\n console.log('Done');\n });\n});\n```\n\nLook ma, no event listeners!\n\nYou can also use `xml2js` from\n[CoffeeScript](http://jashkenas.github.com/coffee-script/), further reducing\nthe clutter:\n\n```coffeescript\nfs = require 'fs',\nxml2js = require 'xml2js'\n\nparser = new xml2js.Parser()\nfs.readFile __dirname + '/foo.xml', (err, data) ->\n parser.parseString data, (err, result) ->\n console.dir result\n console.log 'Done.'\n```\n\nBut what happens if you forget the `new` keyword to create a new `Parser`? In\nthe middle of a nightly coding session, it might get lost, after all. Worry\nnot, we got you covered! Starting with 0.2.8 you can also leave it out, in\nwhich case `xml2js` will helpfully add it for you, no bad surprises and\ninexplicable bugs!\n\n\"Traditional\" usage\n-------------------\n\nAlternatively you can still use the traditional `addListener` variant that was\nsupported since forever:\n\n```javascript\nvar fs = require('fs'),\n xml2js = require('xml2js');\n\nvar parser = new xml2js.Parser();\nparser.addListener('end', function(result) {\n console.dir(result);\n console.log('Done.');\n});\nfs.readFile(__dirname + '/foo.xml', function(err, data) {\n parser.parseString(data);\n});\n```\n\nIf you want to parse multiple files, you have multiple possibilites:\n\n * You can create one `xml2js.Parser` per file. That's the recommended one\n and is promised to always *just work*.\n * You can call `reset()` on your parser object.\n * You can hope everything goes well anyway. This behaviour is not\n guaranteed work always, if ever. Use option #1 if possible. Thanks!\n\nSo you wanna some JSON?\n-----------------------\n\nJust wrap the `result` object in a call to `JSON.stringify` like this\n`JSON.stringify(result)`. You get a string containing the JSON representation\nof the parsed object that you can feed to JSON-hungry consumers.\n\nDisplaying results\n------------------\n\nYou might wonder why, using `console.dir` or `console.log` the output at some\nlevel is only `[Object]`. Don't worry, this is not because xml2js got lazy.\nThat's because Node uses `util.inspect` to convert the object into strings and\nthat function stops after `depth=2` which is a bit low for most XML.\n\nTo display the whole deal, you can use `console.log(util.inspect(result, false,\nnull))`, which displays the whole result.\n\nSo much for that, but what if you use\n[eyes](https://github.com/cloudhead/eyes.js) for nice colored output and it\ntruncates the output with `…`? Don't fear, there's also a solution for that,\nyou just need to increase the `maxLength` limit by creating a custom inspector\n`var inspect = require('eyes').inspector({maxLength: false})` and then you can\neasily `inspect(result)`.\n\nXML builder usage\n-----------------\n\nSince 0.4.0, objects can be also be used to build XML:\n\n```javascript\nvar fs = require('fs'),\n xml2js = require('xml2js');\n\nvar obj = {name: \"Super\", Surname: \"Man\", age: 23};\n\nvar builder = new xml2js.Builder();\nvar xml = builder.buildObject(obj);\n```\n\nAt the moment, a one to one bi-directional conversion is guaranteed only for\ndefault configuration, except for `attrkey`, `charkey` and `explicitArray` options\nyou can redefine to your taste. Writing CDATA is not currently supported.\n\nProcessing attribute and tag names\n----------------------------------\n\nSince 0.4.1 you can optionally provide the parser with attribute and tag name processors:\n\n```javascript\n\nfunction nameToUpperCase(name){\n return name.toUpperCase();\n}\n\n//transform all attribute and tag names to uppercase\nparseString(xml, {tagNameProcessors: [nameToUpperCase], attrNameProcessors: [nameToUpperCase]}, function (err, result) {\n});\n```\n\nThe `tagNameProcessors` and `attrNameProcessors` options both accept an `Array` of functions with the following signature:\n```javascript\nfunction (name){\n //do something with `name`\n return name\n}\n```\n\nSome processors are provided out-of-the-box and can be found in `lib/processors.js`:\n\n- `normalize`: transforms the name to lowercase.\n(Automatically used when `options.normalize` is set to `true`)\n\n- `firstCharLowerCase`: transforms the first character to lower case.\nE.g. 'MyTagName' becomes 'myTagName'\n\n- `stripPrefix`: strips the xml namespace prefix. E.g `<foo:Bar/>` will become 'Bar'.\n(N.B.: the `xmlns` prefix is NOT stripped.)\n\nOptions\n=======\n\nApart from the default settings, there are a number of options that can be\nspecified for the parser. Options are specified by ``new Parser({optionName:\nvalue})``. Possible options are:\n\n * `attrkey` (default: `$`): Prefix that is used to access the attributes.\n Version 0.1 default was `@`.\n * `charkey` (default: `_`): Prefix that is used to access the character\n content. Version 0.1 default was `#`.\n * `explicitCharkey` (default: `false`)\n * `trim` (default: `false`): Trim the whitespace at the beginning and end of\n text nodes.\n * `normalizeTags` (default: `false`): Normalize all tag names to lowercase.\n * `normalize` (default: `false`): Trim whitespaces inside text nodes.\n * `explicitRoot` (default: `true`): Set this if you want to get the root\n node in the resulting object.\n * `emptyTag` (default: `undefined`): what will the value of empty nodes be.\n Default is `{}`.\n * `explicitArray` (default: `true`): Always put child nodes in an array if\n true; otherwise an array is created only if there is more than one.\n * `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create\n text nodes.\n * `mergeAttrs` (default: `false`): Merge attributes and child elements as\n properties of the parent, instead of keying attributes off a child\n attribute object. This option is ignored if `ignoreAttrs` is `false`.\n * `validator` (default `null`): You can specify a callable that validates\n the resulting structure somehow, however you want. See unit tests\n for an example.\n * `xmlns` (default `false`): Give each element a field usually called '$ns'\n (the first character is the same as attrkey) that contains its local name\n and namespace URI.\n * `explicitChildren` (default `false`): Put child elements to separate\n property. Doesn't work with `mergeAttrs = true`. If element has no children\n then \"children\" won't be created. Added in 0.2.5.\n * `childkey` (default `$$`): Prefix that is used to access child elements if\n `explicitChildren` is set to `true`. Added in 0.2.5.\n * `charsAsChildren` (default `false`): Determines whether chars should be\n considered children if `explicitChildren` is on. Added in 0.2.5.\n * `async` (default `false`): Should the callbacks be async? This *might* be\n an incompatible change if your code depends on sync execution of callbacks.\n xml2js 0.3 might change this default, so the recommendation is to not\n depend on sync execution anyway. Added in 0.2.6.\n * `strict` (default `true`): Set sax-js to strict or non-strict parsing mode.\n Defaults to `true` which is *highly* recommended, since parsing HTML which\n is not well-formed XML might yield just about anything. Added in 0.2.7.\n * `attrNameProcessors` (default: `null`): Allows the addition of attribute name processing functions.\n Accepts an `Array` of functions with following signature:\n ```javascript\n function (name){\n //do something with `name`\n return name\n }\n ```\n Added in 0.4.1\n * `tagNameProcessors` (default: `null`):Allows the addition of tag name processing functions.\n Accepts an `Array` of functions with following signature:\n ```javascript\n function (name){\n //do something with `name`\n return name\n }\n ```\n Added in 0.4.1\n\nOptions for the `Builder` class\n-------------------------------\n\n * `rootName` (default `root`): root element name to be used in case\n `explicitRoot` is `false` or to override the root element name.\n * `renderOpts` (default `{ 'pretty': true, 'indent': ' ', 'newline': '\\n' }`):\n Rendering options for xmlbuilder-js.\n * pretty: prettify generated XML\n * indent: whitespace for indentation (only when pretty)\n * newline: newline char (only when pretty)\n * `xmldec` (default `{ 'version': '1.0', 'encoding': 'UTF-8', 'standalone': true }`:\n XML declaration attributes.\n * `xmldec.version` A version number string, e.g. 1.0\n * `xmldec.encoding` Encoding declaration, e.g. UTF-8\n * `xmldec.standalone` standalone document declaration: true or false\n * `doctype` (default `null`): optional DTD. Eg. `{'ext': 'hello.dtd'}`\n * `headless` (default: `false`): omit the XML header. Added in 0.4.3.\n\n`renderOpts`, `xmldec`,`doctype` and `headless` pass through to\n[xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js).\n\nUpdating to new version\n=======================\n\nVersion 0.2 changed the default parsing settings, but version 0.1.14 introduced\nthe default settings for version 0.2, so these settings can be tried before the\nmigration.\n\n```javascript\nvar xml2js = require('xml2js');\nvar parser = new xml2js.Parser(xml2js.defaults[\"0.2\"]);\n```\n\nTo get the 0.1 defaults in version 0.2 you can just use\n`xml2js.defaults[\"0.1\"]` in the same place. This provides you with enough time\nto migrate to the saner way of parsing in xml2js 0.2. We try to make the\nmigration as simple and gentle as possible, but some breakage cannot be\navoided.\n\nSo, what exactly did change and why? In 0.2 we changed some defaults to parse\nthe XML in a more universal and sane way. So we disabled `normalize` and `trim`\nso xml2js does not cut out any text content. You can reenable this at will of\ncourse. A more important change is that we return the root tag in the resulting\nJavaScript structure via the `explicitRoot` setting, so you need to access the\nfirst element. This is useful for anybody who wants to know what the root node\nis and preserves more information. The last major change was to enable\n`explicitArray`, so everytime it is possible that one might embed more than one\nsub-tag into a tag, xml2js >= 0.2 returns an array even if the array just\nincludes one element. This is useful when dealing with APIs that return\nvariable amounts of subtags.\n\nRunning tests, development\n==========================\n\n[](https://travis-ci.org/Leonidas-from-XIV/node-xml2js)\n[](https://david-dm.org/Leonidas-from-XIV/node-xml2js)\n\nThe development requirements are handled by npm, you just need to install them.\nWe also have a number of unit tests, they can be run using `npm test` directly\nfrom the project root. This runs zap to discover all the tests and execute\nthem.\n\nIf you like to contribute, keep in mind that xml2js is written in CoffeeScript,\nso don't develop on the JavaScript files that are checked into the repository\nfor convenience reasons. Also, please write some unit test to check your\nbehaviour and if it is some user-facing thing, add some documentation to this\nREADME, so people will know it exists. Thanks in advance!\n",
"readmeFilename": "README.md",
"bugs": {
"url": "https://github.com/Leonidas-from-XIV/node-xml2js/issues"
},
"_id": "[email protected]",
"_shasum": "3111010003008ae19240eba17497b57c729c555d",
"_from": "xml2js@^0.4.3",
"_resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.4.tgz"
}
| {
"pile_set_name": "Github"
} |
// @flow
/* eslint-disable react/jsx-sort-props */
import * as React from 'react';
import * as vars from '../styles/variables';
import AccessibleSVG from '../icons/accessible-svg';
import type { Icon } from '../icons/flowTypes';
/**
* This is an auto-generated component and should not be edited
* manually in contributor pull requests.
*
* If you have problems with this component:
* - https://github.com/box/box-ui-elements/issues/new?template=Bug_report.md
*
* If there are missing features in this component:
* - https://github.com/box/box-ui-elements/issues/new?template=Feature_request.md
*/
const UserOrbit56 = (props: Icon) => (
<AccessibleSVG width={56} height={56} viewBox="0 0 56 56" {...props}>
<g fill="none" fillRule="evenodd">
<circle cx={16} cy={48} r={4} fill={vars.bdlBoxBlue10} />
<circle cx={18} cy={10} r={6} fill={vars.bdlBoxBlue10} />
<path
fill={vars.bdlBoxBlue}
fillRule="nonzero"
d="M33.676 4.253c2.645.675 4.72 2.63 6.138 5.451 6.966 1.52 12.252 5.432 13.761 11.009 1.148 4.242-.084 8.732-3.056 12.735a5 5 0 11-7.389 6.717c-2.585 1.65-5.547 3.038-8.791 4.053-4.158 5.638-9.363 8.717-14.015 7.53-3.163-.809-5.513-3.446-6.895-7.208-5.583-1.865-9.702-5.438-11.004-10.253-.86-3.177-.385-6.492 1.156-9.638a5 5 0 016.353-7.698c2.703-2.2 5.996-4.088 9.718-5.48l.336-.124c4.101-5.36 9.157-8.251 13.688-7.094zm-.939 40.43l-.082.022c-6.457 1.713-12.791 1.669-18.01.208 1.295 3.1 3.32 5.239 5.938 5.908 3.905.997 8.38-1.465 12.154-6.138zm-8.875-32.455a37.348 37.348 0 00-4.304 1.423c-2.062 3.117-3.816 6.923-5.01 11.17-.518 1.84-.9 3.659-1.156 5.43A3.996 3.996 0 0116 34a4.003 4.003 0 01-2.918 3.852c.123 1.69.382 3.276.77 4.72 5.061 1.748 11.568 1.98 18.286.2a37.525 37.525 0 002.527-.765c1.965-3.05 3.637-6.735 4.787-10.827 1.1-3.911 1.592-7.726 1.545-11.18a3 3 0 01-.686-5.92 19.86 19.86 0 00-.71-2.376c-4.612-1.046-10.101-.97-15.739.524zm-5.906 2.11l-.271.126c-2.4 1.125-4.552 2.469-6.4 3.959A5 5 0 015.291 25.7c-1.268 2.678-1.646 5.45-.937 8.066 1.008 3.72 4.08 6.629 8.361 8.379a26.922 26.922 0 01-.625-4.146L12 38c-2.21 0-4-1.79-4-4a3.999 3.999 0 014.417-3.979 43.47 43.47 0 011.166-5.447c1.07-3.802 2.581-7.273 4.373-10.236zm22.802-2.342l.004.01c.214.642.4 1.313.56 2.012a3 3 0 01.672 5.813c.058 3.181-.332 6.647-1.21 10.204l-.148.583-.22.808c-1.044 3.715-2.511 7.113-4.249 10.03a33.8 33.8 0 006.03-3.064 5 5 0 016.651-6.039c2.673-3.561 3.781-7.491 2.798-11.12-1.197-4.417-5.304-7.69-10.888-9.237zM49.9 34.245l-.185.224c-1.555 1.864-3.493 3.604-5.745 5.141a3.999 3.999 0 105.93-5.365zM47 33a3.999 3.999 0 00-3.92 4.8c2.01-1.397 3.733-2.96 5.113-4.619A3.989 3.989 0 0047 33zm-35-1a2 2 0 100 4h.003c-.017-1.288.04-2.623.171-3.991A1.633 1.633 0 0012 32zm1.146.36l-.008.077A36.091 36.091 0 0013 35.732a1.999 1.999 0 00.146-3.372zm-2.639-13.284l-.213.185c-1.928 1.715-3.468 3.594-4.542 5.54a3.999 3.999 0 004.755-5.725zM7 17a3.999 3.999 0 00-2.93 6.722c1.216-2.165 2.937-4.233 5.07-6.1A3.956 3.956 0 007 17zm14.722-6.237a41.182 41.182 0 011.623-.468c5.343-1.418 10.601-1.632 15.214-.836-1.273-2.217-3.01-3.735-5.142-4.28-3.748-.956-8.02 1.273-11.695 5.584z"
/>
<path fill={vars.bdlBoxBlue10} fillRule="nonzero" d="M27.5 20a7.5 7.5 0 100 15 7.5 7.5 0 000-15z" />
<path
fill={vars.bdlBoxBlue}
fillRule="nonzero"
d="M27.5 18c5.247 0 9.5 4.253 9.5 9.5S32.747 37 27.5 37 18 32.747 18 27.5s4.253-9.5 9.5-9.5zm0 2a7.5 7.5 0 00-5.25 12.856 5.503 5.503 0 0110.5-.001A7.5 7.5 0 0027.5 20zm0 3a2.5 2.5 0 010 5 2.5 2.5 0 010-5z"
/>
<path
fill={vars.bdlBoxBlue10}
fillRule="nonzero"
d="M47 33c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"
/>
<path fill={vars.white} fillRule="nonzero" d="M7 17c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z" />
<path fill={vars.bdlBoxBlue10} fillRule="nonzero" d="M12 32a2 2 0 11.001 3.999A2 2 0 0112 32z" />
</g>
</AccessibleSVG>
);
export default UserOrbit56;
| {
"pile_set_name": "Github"
} |
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
| {
"pile_set_name": "Github"
} |
package com.rsen.db.converter;
import android.database.Cursor;
import com.rsen.db.sqlite.ColumnDbType;
/**
* Author: wyouflf
* Date: 13-11-4
* Time: 下午10:51
*/
public class StringColumnConverter implements ColumnConverter<String> {
@Override
public String getFieldValue(final Cursor cursor, int index) {
return cursor.isNull(index) ? null : cursor.getString(index);
}
@Override
public Object fieldValue2DbValue(String fieldValue) {
return fieldValue;
}
@Override
public ColumnDbType getColumnDbType() {
return ColumnDbType.TEXT;
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.