text stringlengths 2 1.04M | meta dict |
|---|---|
layout: archive
title: "Documentation and tutorials"
date: 2016-08-03
modified:
tags: []
image:
feature:
teaser:
---
- [all functions and workflows]({{ site.baseurl }}/documentation/all/)
- [all Arbor tutorials]({{ site.baseurl }}/tutorials/)
| {
"content_hash": "d28771d1c6322de7aaa1fa2513aa8060",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 70,
"avg_line_length": 20.666666666666668,
"alnum_prop": 0.6975806451612904,
"repo_name": "arborworkflows/arborworkflows.github.com",
"id": "2090858f1cef57891f61d710445df791fce57415",
"size": "252",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "documentation/index.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "119006"
},
{
"name": "HTML",
"bytes": "944396"
},
{
"name": "JavaScript",
"bytes": "16633"
},
{
"name": "R",
"bytes": "26"
},
{
"name": "Ruby",
"bytes": "2978"
},
{
"name": "Shell",
"bytes": "216"
}
],
"symlink_target": ""
} |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 28636 : 18636;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop Hexagon server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Hexagon server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "setmininput", &setmininput, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "getnormalizedtxid", &getnormalizedtxid, true, true, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: hexagon-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: hexagon-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: hexagon-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use hexagond";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=hexagonrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Hexagon Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
if (rpc_worker_group != NULL)
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DoS the user really
shouldn't have their RPC port exposed. */
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "sendrawtransaction" && n > 1) ConvertTo<bool>(params[1], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| {
"content_hash": "82945c4feef70fb3f608ac0680f2c8f5",
"timestamp": "",
"source": "github",
"line_count": 1308,
"max_line_length": 159,
"avg_line_length": 37.292813455657495,
"alnum_prop": 0.5768670944463806,
"repo_name": "DannyHex/Hexagon",
"id": "bef0dedfaee3f25183caae63f8e6be696d9fb999",
"size": "48779",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/bitcoinrpc.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "32394"
},
{
"name": "C++",
"bytes": "2605857"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50615"
},
{
"name": "Makefile",
"bytes": "13377"
},
{
"name": "NSIS",
"bytes": "5918"
},
{
"name": "Objective-C",
"bytes": "1052"
},
{
"name": "Objective-C++",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69716"
},
{
"name": "QMake",
"bytes": "14749"
},
{
"name": "Roff",
"bytes": "18289"
},
{
"name": "Shell",
"bytes": "16339"
}
],
"symlink_target": ""
} |
First off, thank you for considering contributing to HAL. It's people like you that make HAL such a great tool. HAL is an open source project and we love to receive contributions from our community — you! There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, submitting bug reports and feature requests or writing code which can be incorporated into HAL itself.
We expect all contributors and users to follow our [Code of Conduct](CODE_OF_CONDUCT.md) when communicating through project channels. These include, but are not limited to: chat, issues, code.
# One time setup
## Create a GitHub account
If you don't have one already, head to https://github.com/
## Git Flow
We use [Git Flow](https://github.com/nvie/gitflow) to manage branches. Although it's no requirement, it helps if you've read and understood the [basic ideas](https://nvie.com/posts/a-successful-git-branching-model/) behind Git Flow. The most important fact is that development happens in the `develop` branch and that the latest stable version is always available in branch `master`.
## Fork HAL
Fork https://github.com/hal/console into your GitHub account.
## Clone your newly forked repository onto your local machine
```bash
git clone git@github.com:[your username]/console.git
cd console
```
## Add a remote reference to upstream
This makes it easy to pull down changes in the project over time
```bash
git remote add upstream git://github.com/hal/console.git
```
# Development Process
This is the typical process you would follow to submit any changes to Elemento.
## Pulling updates from upstream
```bash
git pull --rebase upstream develop
```
> Note that --rebase will automatically move your local commits, if you have
> any, on top of the latest branch you pull from.
> If you don't have any commits it is safe to leave off, but for safety it
> doesn't hurt to use it each time just in case you have a commit you've
> forgotten about!
## Discuss your planned changes (if you want feedback)
* HAL Issue Tracker - https://issues.jboss.org/browse/HAL
* Gitter - https://gitter.im/hal/console
## Create a simple topic branch to isolate your work (recommended)
```bash
git checkout -b my_cool_feature
```
## Make the changes
Make whatever code changes, including new tests to verify your change, are necessary and ensure that the build and tests pass. Make sure your code changes apply to the checkstyle rules defined at [build/checkstyle.xml](build/checkstyle.xml):
```bash
mvn clean install
```
> If you're making non code changes, the above step is not required.
## Commit changes
Add whichever files were changed into 'staging' before performing a commit:
```bash
git commit
```
## Rebase changes against develop
Once all your commits for the issue have been made against your local topic branch, we need to rebase it against develop in upstream to ensure that your commits are added on top of the current state of develop. This will make it easier to incorporate your changes into the develop branch, especially if there has been any significant time passed since you rebased at the beginning.
```bash
git pull --rebase upstream develop
```
## Push to your repo
Now that you've sync'd your topic branch with upstream, it's time to push it to your GitHub repo.
```bash
git push origin my_cool_feature
```
## Getting your changes merged into upstream, a pull request
Now your updates are in your GitHub repo, you will need to notify the project that you have code/docs for inclusion.
* Send a pull request, by clicking the pull request link while in your repository fork
* After review a maintainer will merge your pull request, update/resolve associated issues, and reply when complete
* Lastly, switch back to develop from your topic branch and pull the updates
```bash
git checkout develop
git pull upstream develop
```
* You may also choose to update your origin on GitHub as well
```bash
git push origin
```
## Some tips
Here are some tips on increasing the chance that your pull request is accepted:
* Write a [good commit message](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
* Include tests that fail without your code, and pass with it
| {
"content_hash": "4f47d0e1b6d677c84da7e799082f00e2",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 409,
"avg_line_length": 35.69747899159664,
"alnum_prop": 0.7641242937853108,
"repo_name": "hpehl/hal.next",
"id": "2e69f3cca128de76123c6b4f75a389d75f3a849d",
"size": "4250",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "CONTRIBUTING.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "28923"
},
{
"name": "FreeMarker",
"bytes": "10423"
},
{
"name": "HTML",
"bytes": "113886"
},
{
"name": "Java",
"bytes": "1389150"
},
{
"name": "JavaScript",
"bytes": "4311"
},
{
"name": "Shell",
"bytes": "633"
}
],
"symlink_target": ""
} |
/**
* Policy Mappings
* (sails.config.policies)
*
* Policies are simple functions which run **before** your controllers.
* You can apply one or more policies to a given controller, or protect
* its actions individually.
*
* Any policy file (e.g. `api/policies/authenticated.js`) can be accessed
* below by its filename, minus the extension, (e.g. "authenticated")
*
* For more information on how policies work, see:
* http://sailsjs.org/#!/documentation/concepts/Policies
*
* For more information on configuring policies, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.policies.html
*/
module.exports.policies = {
/***************************************************************************
* *
* Default policy for all controllers and actions (`true` allows public *
* access) *
* *
***************************************************************************/
// '*': true,
/***************************************************************************
* *
* Here's an example of mapping some policies to run before a controller *
* and its actions *
* *
***************************************************************************/
UserController: {
// 'ngUpdatePassword': true,
// 'ngGetUser': true,
'*': 'isAuth'
},
// RoleController: {'*': 'isAuth'},
// RabbitController: {
// Apply the `false` policy as the default for all of RabbitController's actions
// (`false` prevents all access, which ensures that nothing bad happens to our rabbits)
// '*': false,
// For the action `nurture`, apply the 'isRabbitMother' policy
// (this overrides `false` above)
// nurture : 'isRabbitMother',
// Apply the `isNiceToAnimals` AND `hasRabbitFood` policies
// before letting any users feed our rabbits
// feed : ['isNiceToAnimals', 'hasRabbitFood']
// }
};
| {
"content_hash": "cfb25567aa27a73ed46dda44e0e767d8",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 89,
"avg_line_length": 40.26315789473684,
"alnum_prop": 0.4588235294117647,
"repo_name": "slims2016/slims-beta",
"id": "aff97f1fc952c6c93620394ae38b447ce3e0788d",
"size": "2295",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/policies.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11"
},
{
"name": "CSS",
"bytes": "3300"
},
{
"name": "HTML",
"bytes": "194091"
},
{
"name": "JavaScript",
"bytes": "448386"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e8810f99152c190619f973f1f800bd7e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "8e182702e34056804251dce6d87fd98e950cbda4",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Laurus/Laurus linguy/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Reflection;
using Nelibur.ObjectMapper.CodeGenerators.Emitters;
namespace Nelibur.ObjectMapper.Mappers.Caches
{
internal sealed class MapperCacheItem
{
public int Id { get; set; }
public Mapper Mapper { get; set; }
public IEmitterType EmitMapMethod(IEmitterType sourceMemeber, IEmitterType targetMember)
{
Type mapperType = typeof(Mapper);
MethodInfo mapMethod = mapperType.GetMethod(Mapper.MapMethodName, BindingFlags.Instance | BindingFlags.Public);
FieldInfo mappersField = mapperType.GetField(Mapper.MappersFieldName, BindingFlags.Instance | BindingFlags.NonPublic);
IEmitterType mappers = EmitField.Load(EmitThis.Load(mapperType), mappersField);
IEmitterType mapper = EmitArray.Load(mappers, Id);
IEmitterType result = EmitMethod.Call(mapMethod, mapper, sourceMemeber, targetMember);
return result;
}
}
}
| {
"content_hash": "8eef293eeb5b67a1ab6430c6a13bee2e",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 130,
"avg_line_length": 42.43478260869565,
"alnum_prop": 0.7038934426229508,
"repo_name": "iEmiya/TinyMapper",
"id": "c56e39ce4aaede93b85d0082cfc3c4aaad1d49f6",
"size": "978",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Source/TinyMapper/Mappers/Caches/MapperCacheItem.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "259"
},
{
"name": "C#",
"bytes": "175113"
},
{
"name": "CSS",
"bytes": "1147"
},
{
"name": "HTML",
"bytes": "16932"
},
{
"name": "JavaScript",
"bytes": "170"
},
{
"name": "PowerShell",
"bytes": "3140"
}
],
"symlink_target": ""
} |
require 'test/unit'
require 'yaml'
module Syck
class TestSet < Test::Unit::TestCase
def setup
@set = YAML::Set.new
@set['foo'] = 'bar'
@set['bar'] = 'baz'
end
def test_to_yaml
assert_match(/!set/, @set.to_yaml)
end
def test_roundtrip
assert_equal(@set, YAML.load(YAML.dump(@set)))
end
###
# FIXME: Syck should also support !!set as shorthand
def test_load_from_yaml
loaded = YAML.load(<<-eoyml)
--- !set
foo: bar
bar: baz
eoyml
assert_equal(@set, loaded)
end
end
end
| {
"content_hash": "3b348bf01b15d431b27aa27e62bc4c19",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 56,
"avg_line_length": 18.161290322580644,
"alnum_prop": 0.5754884547069272,
"repo_name": "richo/unrubby",
"id": "d58f92e53f49bc6b954810946144ff362d896860",
"size": "563",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "ruby/test/syck/test_set.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "35"
},
{
"name": "Assembly",
"bytes": "1267"
},
{
"name": "Awk",
"bytes": "753"
},
{
"name": "Batchfile",
"bytes": "17319"
},
{
"name": "C",
"bytes": "8800167"
},
{
"name": "C++",
"bytes": "1615"
},
{
"name": "CSS",
"bytes": "13693"
},
{
"name": "E",
"bytes": "17545"
},
{
"name": "Emacs Lisp",
"bytes": "96936"
},
{
"name": "Groff",
"bytes": "2661490"
},
{
"name": "HTML",
"bytes": "331467"
},
{
"name": "JavaScript",
"bytes": "5821"
},
{
"name": "Makefile",
"bytes": "94262"
},
{
"name": "Perl",
"bytes": "305"
},
{
"name": "Perl6",
"bytes": "626"
},
{
"name": "Prolog",
"bytes": "106"
},
{
"name": "Python",
"bytes": "871"
},
{
"name": "R",
"bytes": "23182"
},
{
"name": "Ragel in Ruby Host",
"bytes": "27704"
},
{
"name": "Ruby",
"bytes": "17309389"
},
{
"name": "Scheme",
"bytes": "672"
},
{
"name": "Scilab",
"bytes": "745"
},
{
"name": "Shell",
"bytes": "3909"
},
{
"name": "Tcl",
"bytes": "50595"
},
{
"name": "XSLT",
"bytes": "13913"
},
{
"name": "Yacc",
"bytes": "239246"
}
],
"symlink_target": ""
} |
package org.apache.commons.digester3.plugins;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.digester3.Digester;
/**
* Represents a Class that can be instantiated by a PluginCreateRule, plus info on how to load custom digester rules for
* mapping xml into that plugged-in class.
*
* @since 1.6
*/
public class Declaration
{
/** The class of the object to be instantiated. */
private Class<?> pluginClass;
/** The name of the class of the object to be instantiated. */
private final String pluginClassName;
/** See {@link #setId}. */
private String id;
/** See {@link #setProperties}. */
private final Properties properties = new Properties();
/** See {@link #init}. */
private boolean initialized = false;
/**
* Class which is responsible for dynamically loading this plugin's rules on demand.
*/
private RuleLoader ruleLoader = null;
// ---------------------- constructors ----------------------------------
/**
* Constructor.
*
* @param pluginClassName The name of the class of the object to be instantiated (will be load in the init method)
*/
public Declaration( final String pluginClassName )
{
// We can't load the pluginClass at this time, because we don't
// have a digester instance yet to load it through. So just
// save the name away, and we'll load the Class object in the
// init method.
this.pluginClassName = pluginClassName;
}
/**
* Constructor.
*
* @param pluginClass The class of the object to be instantiated (will be load in the init method)
*/
public Declaration( final Class<?> pluginClass )
{
this.pluginClass = pluginClass;
this.pluginClassName = pluginClass.getName();
}
/**
* Create an instance where a fully-initialized ruleLoader instance is provided by the caller instead of having the
* PluginManager "discover" an appropriate one.
*
* @param pluginClass The class of the object to be instantiated (will be load in the init method)
* @param ruleLoader Class which is responsible for dynamically loading this plugin's rules on demand
*/
public Declaration( final Class<?> pluginClass, final RuleLoader ruleLoader )
{
this.pluginClass = pluginClass;
this.pluginClassName = pluginClass.getName();
this.ruleLoader = ruleLoader;
}
// ---------------------- properties -----------------------------------
/**
* The id that the user associated with a particular plugin declaration in the input xml. This id is later used in
* the input xml to refer back to the original declaration.
* <p>
* For plugins declared "in-line", the id is null.
*
* @param id The id that the user associated with a particular plugin declaration in the input xml
*/
public void setId( final String id )
{
this.id = id;
}
/**
* Return the id associated with this declaration. For plugins declared "inline", null will be returned.
*
* @return The id value. May be null.
*/
public String getId()
{
return id;
}
/**
* Copy all (key,value) pairs in the param into the properties member of this object.
* <p>
* The declaration properties cannot be explicit member variables, because the set of useful properties a user can
* provide on a declaration depends on what RuleFinder classes are available - and extra RuleFinders can be added by
* the user. So here we keep a map of the settings, and let the RuleFinder objects look for whatever properties they
* consider significant.
* <p>
* The "id" and "class" properties are treated differently.
*
* @param p The properties have to be copied into the properties member of this object
*/
public void setProperties( final Properties p )
{
properties.putAll( p );
}
/**
* Return plugin class associated with this declaration.
*
* @return The pluginClass.
*/
public Class<?> getPluginClass()
{
return pluginClass;
}
// ---------------------- methods -----------------------------------
/**
* Must be called exactly once, and must be called before any call to the configure method.
*
* @param digester The Digester instance where plugin has to be plugged
* @param pm The plugin manager reference
* @throws PluginException if any error occurs while loading the rules
*/
public void init( final Digester digester, final PluginManager pm )
throws PluginException
{
final Log log = digester.getLogger();
final boolean debug = log.isDebugEnabled();
if ( debug )
{
log.debug( "init being called!" );
}
if ( initialized )
{
throw new PluginAssertionFailure( "Init called multiple times." );
}
if ( ( pluginClass == null ) && ( pluginClassName != null ) )
{
try
{
// load the plugin class object
pluginClass = digester.getClassLoader().loadClass( pluginClassName );
}
catch ( final ClassNotFoundException cnfe )
{
throw new PluginException( "Unable to load class " + pluginClassName, cnfe );
}
}
if ( ruleLoader == null )
{
// the caller didn't provide a ruleLoader to the constructor,
// so get the plugin manager to "discover" one.
log.debug( "Searching for ruleloader..." );
ruleLoader = pm.findLoader( digester, id, pluginClass, properties );
}
else
{
log.debug( "This declaration has an explicit ruleLoader." );
}
if ( debug )
{
if ( ruleLoader == null )
{
log.debug( "No ruleLoader found for plugin declaration" + " id [" + id + "]" + ", class ["
+ pluginClass.getClass().getName() + "]." );
}
else
{
log.debug( "RuleLoader of type [" + ruleLoader.getClass().getName()
+ "] associated with plugin declaration" + " id [" + id + "]" + ", class ["
+ pluginClass.getClass().getName() + "]." );
}
}
initialized = true;
}
/**
* Attempt to load custom rules for the target class at the specified pattern.
* <p>
* On return, any custom rules associated with the plugin class have been loaded into the Rules object currently
* associated with the specified digester object.
*
* @param digester The Digester instance where plugin has to be plugged
* @param pattern The pattern the custom rules have to be bound
* @throws PluginException if any error occurs
*/
public void configure( final Digester digester, final String pattern )
throws PluginException
{
final Log log = digester.getLogger();
final boolean debug = log.isDebugEnabled();
if ( debug )
{
log.debug( "configure being called!" );
}
if ( !initialized )
{
throw new PluginAssertionFailure( "Not initialized." );
}
if ( ruleLoader != null )
{
ruleLoader.addRules( digester, pattern );
}
}
}
| {
"content_hash": "49f60ab6027ef833fe5c104860361ea6",
"timestamp": "",
"source": "github",
"line_count": 230,
"max_line_length": 120,
"avg_line_length": 32.76521739130435,
"alnum_prop": 0.5908970276008493,
"repo_name": "apache/commons-digester",
"id": "46a495227ec2b43b8642ed771b0a65cd6fbadf94",
"size": "8343",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/apache/commons/digester3/plugins/Declaration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "4897"
},
{
"name": "Java",
"bytes": "1298541"
},
{
"name": "Shell",
"bytes": "157"
}
],
"symlink_target": ""
} |
package com.astrazeneca.seq2c.input;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class SampleStatisticsTest {
@DataProvider(name = "lines")
Object[][] lineData() {
return new Object[][] {
{"seq2c-test", "TPTE:11057796-11058160:BAGE", "chr21", 10906903, 10907042, 140, 0.0, 0.1},
{"seq2c-test", "chr21:19641434-19642441:PRSS7", "chr21", 19641434, 19642441, 1008, 0.2, 0.0},
{"seq2c-test", "chr21:43334707-43334830:C2CD2", "chr21", 43334707, 43334830, 124, 0.3, 1.2},
};
}
@Test(dataProvider = "lines")
public void factoryShouldCreateProperSampleStatistics(
String sample, String gene, String chr, int start, int end, int len, double norm3, double norm3s) {
String line = createLine(sample, gene, chr, start, end, len, norm3, norm3s);
StatisticsFactory factory = new StatisticsFactory();
SampleStatistics statistics = factory.createObjectFromLine(line);
assertEquals(statistics.getSample(), sample);
assertEquals(statistics.getGenes().size(), 1);
assertTrue(statistics.getGenes().containsKey(gene));
assertEquals(statistics.getGenes().get(gene).size(), 1);
final Sample smpl = statistics.getGenes().get(gene).get(0);
assertEquals(smpl.getSample(), sample);
assertEquals(smpl.getChr(), chr);
assertEquals(smpl.getGene(), gene);
assertEquals(smpl.getStart(), start);
assertEquals(smpl.getEnd(), end);
assertEquals(smpl.getLen(), len);
assertEquals(smpl.getNorm3(), norm3);
assertEquals(smpl.getNorm3s(), norm3s);
}
@Test
public void addNewStatisticsOnTheSameGeneTest() {
StatisticsFactory factory = new StatisticsFactory();
final String gene = "chr21:43640008-43640156:ABCG1";
SampleStatistics stat1 =
factory.createObjectFromLine(createLine(
"seq2c-test",
gene,
"chr21",
43640008,
43640156,
149,
0.00,
0.00));
SampleStatistics stat2 =
factory.createObjectFromLine(createLine(
"seq2c-test",
gene,
"chr21",
43645781,
43646024,
244,
0.00,
0.00));
stat1.addNextObject(stat2);
assertEquals(stat1.getGenes().size(), 1);
assertEquals(stat1.getGenes().get(gene).size(), 2);
}
@Test
public void addNewStatisticsOnDifferentGenesTest() {
StatisticsFactory factory = new StatisticsFactory();
final String gene1 = "chr21:43562206-43563105:UMODL1";
SampleStatistics stat1 =
factory.createObjectFromLine(createLine(
"seq2c-test",
gene1,
"chr21",
43640008,
43640156,
149,
0.00,
0.00));
final String gene2 = "chr21:43640008-43640156:ABCG1";
SampleStatistics stat2 =
factory.createObjectFromLine(createLine(
"seq2c-test",
gene2,
"chr21",
43645781,
43646024,
244,
0.00,
0.00));
stat1.addNextObject(stat2);
assertEquals(stat1.getGenes().size(), 2);
assertEquals(stat1.getGenes().get(gene1).size(), 1);
assertEquals(stat1.getGenes().get(gene2).size(), 1);
}
@Test
public void equalsShouldWorkOnlyWithSampleNames() {
StatisticsFactory factory = new StatisticsFactory();
final String sample1 = "seq2c-test";
SampleStatistics stat1 = factory.createObjectFromLine(createLine(
sample1,
"chr21:43562206-43563105:UMODL1","chr21",43640008,43640156,
149, 0.00, 0.00));
final String sample2 = "seq2c-test2";
SampleStatistics stat2 = factory.createObjectFromLine(createLine(
sample2,
"chr21:43640008-43640156:ABCG1","chr21",43645781, 43646024,
244, 0.00, 0.00));
assertTrue(stat1.equals(stat1));
assertTrue(stat2.equals(stat2));
assertFalse(stat2.equals(stat1));
assertFalse(stat1.equals(stat2));
}
private static String createLine(
String sample, String gene, String chr, int start, int end, int len, double norm3, double norm3s) {
return sample + '\t' + gene + '\t' + chr + '\t' + start + '\t' + end + '\t' + len + '\t' + norm3 + '\t' + norm3s;
}
} | {
"content_hash": "221c2f65151433747fbebae94f1aff62",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 121,
"avg_line_length": 37.10948905109489,
"alnum_prop": 0.5318646734854445,
"repo_name": "AstraZeneca-NGS/Seq2CJava",
"id": "552727408eaef14d674f720732b012ce07fe9d04",
"size": "5084",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/astrazeneca/seq2c/input/SampleStatisticsTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "185843"
}
],
"symlink_target": ""
} |
package javaobject;
import java.util.*;
import org.apache.geode.cache.CacheLoader;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.RegionEvent;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.Declarable;
import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
import org.apache.geode.LogWriter;
import org.apache.geode.cache.CacheWriterException;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.cache.partition.PartitionRegionHelper;
import org.apache.geode.internal.cache.PartitionedRegionHelper;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheException;
import org.apache.geode.internal.cache.EntryEventImpl;
import org.apache.geode.cache.*;
public class CacheLoaderForSingleHop implements Declarable, CacheLoader {
public CacheLoaderForSingleHop()
{
}
public void init(Properties props) {
}
public Boolean checkSingleHop(LoaderHelper helper) {
System.out.println("CPPTEST: java key: " + helper.getKey());
if (helper.getKey() instanceof Integer && ((Integer) helper.getKey()).intValue() < 1500) {
return null;
}
PartitionedRegion pr;
try {
pr = (PartitionedRegion) helper.getRegion();
} catch (Exception ex) {
//throw new CacheLoaderException("PartitionRegion Cast failed due to: "+ ex.getMessage());
return Boolean.FALSE;
}
Integer bucketId = new Integer(PartitionedRegionHelper.getHashKey(pr, helper.getKey()));
System.out.println("CPPTEST: found BucketId: " + bucketId);
List bucketListOnNode = pr.getLocalBucketsListTestOnly();
System.out.println("CPPTEST: bucketListOnNode size is: " + bucketListOnNode.size());
if (!bucketListOnNode.contains(bucketId)) {
System.out.println("CPPTEST: Wrong BucketId from list");
//throw new CacheLoaderException("Calculated bucketId " + bucketId +
//" does not match java partitionedRegion BucketId" );
return Boolean.FALSE;
}
if (PartitionRegionHelper.getPrimaryMemberForKey(pr, helper.getKey()) == null) {
System.out.println("CPPTEST: Wrong BucketId from member");
//throw new CacheLoaderException("Calculated bucketId " + bucketId +
//" does not match java partitionedRegion BucketId" );
return Boolean.FALSE;
}
System.out.println("CPPTEST: cache loader OK BucketId");
return Boolean.TRUE;
}
public Object load(LoaderHelper helper)
{
System.out.println("CPPTEST: Inside load of loader");
try {
return checkSingleHop(helper);
}
catch (Exception ex) {
return Boolean.FALSE;
}
}
public void close()
{
}
}
| {
"content_hash": "c2d59ac93f1db9baf6945cfb28430a29",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 95,
"avg_line_length": 31.068181818181817,
"alnum_prop": 0.7114118507681053,
"repo_name": "mhansonp/geode-native",
"id": "b44d3bf9fbfc46352c5eaacce8848b6859834267",
"size": "3536",
"binary": false,
"copies": "5",
"ref": "refs/heads/develop",
"path": "tests/javaobject/CacheLoaderForSingleHop.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1899"
},
{
"name": "C#",
"bytes": "3515617"
},
{
"name": "C++",
"bytes": "10771399"
},
{
"name": "CMake",
"bytes": "107196"
},
{
"name": "GAP",
"bytes": "73860"
},
{
"name": "Java",
"bytes": "408387"
},
{
"name": "Perl",
"bytes": "2704"
},
{
"name": "PowerShell",
"bytes": "20450"
},
{
"name": "Shell",
"bytes": "35505"
}
],
"symlink_target": ""
} |
package com.niomongo.processing;
import com.niomongo.RequestProcessor;
/**
* Created with IntelliJ IDEA.
* User: Yevgen Bushuyev
* Date: 18.02.15.
*/
public interface Condition {
boolean check(RequestProcessor requestProcessor);
}
| {
"content_hash": "3937e12a68a609de03862d844c214c83",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 51,
"avg_line_length": 19.916666666666668,
"alnum_prop": 0.7531380753138075,
"repo_name": "bushuyev/niomongo",
"id": "2b17674ffc657bec071b01a247f3ab405cd2053f",
"size": "239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/niomongo/processing/Condition.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "347552"
}
],
"symlink_target": ""
} |
<?php
namespace Ens\JobeetBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery as ProxyQueryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
class JobAdminController extends Controller
{
public function batchActionExtend(ProxyQueryInterface $selectedModelQuery)
{
if ($this->admin->isGranted('EDIT') === false || $this->admin->isGranted('DELETE') === false)
{
throw new AccessDeniedException();
}
$request = $this->get('request');
$modelManager = $this->admin->getModelManager();
$selectedModels = $selectedModelQuery->execute();
try {
foreach ($selectedModels as $selectedModel) {
$selectedModel->extend();
$modelManager->update($selectedModel);
}
} catch (\Exception $e) {
$this->get('session')->setFlash('sonata_flash_error', $e->getMessage());
return new RedirectResponse($this->admin->generateUrl('list',$this->admin->getFilterParameters()));
}
$this->get('session')->setFlash('sonata_flash_success', sprintf('The selected jobs validity has been extended until %s.', date('m/d/Y', time() + 86400 * 30)));
return new RedirectResponse($this->admin->generateUrl('list',$this->admin->getFilterParameters()));
}
public function batchActionDeleteNeverActivatedIsRelevant()
{
return true;
}
public function batchActionDeleteNeverActivated()
{
if ($this->admin->isGranted('EDIT') === false || $this->admin->isGranted('DELETE') === false) {
throw new AccessDeniedException();
}
$em = $this->getDoctrine()->getEntityManager();
$nb = $em->getRepository('EnsJobeetBundle:Job')->cleanup(60);
if ($nb) {
$this->get('session')->setFlash('sonata_flash_success', sprintf('%d never activated jobs have been deleted successfully.', $nb));
} else {
$this->get('session')->setFlash('sonata_flash_info', 'No job to delete.');
}
return new RedirectResponse($this->admin->generateUrl('list',$this->admin->getFilterParameters()));
}
}
?>
| {
"content_hash": "2af96e5f223f8ff2712ea51b92a2495f",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 168,
"avg_line_length": 35.06349206349206,
"alnum_prop": 0.6441828881846989,
"repo_name": "kjanczyk/praktyka",
"id": "4a33d763e1a5d625efea7519ddb10117f21ee1f1",
"size": "2209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Ens/JobeetBundle/Controller/JobAdminController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "146663"
},
{
"name": "PHP",
"bytes": "89461"
}
],
"symlink_target": ""
} |
import rgplot
| {
"content_hash": "0b5fe660760c0be6929838f2fd9ddbe6",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 13,
"avg_line_length": 14,
"alnum_prop": 0.8571428571428571,
"repo_name": "vjuranek/rg-offline-plotting",
"id": "a08f452881e2e561a36ca7367631555bf4f12b85",
"size": "14",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/python/test/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "12211"
},
{
"name": "R",
"bytes": "191"
}
],
"symlink_target": ""
} |
package org.eclipse.bpel.ui.details.providers;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.eclipse.bpel.ui.util.XSDUtils;
import org.eclipse.wst.wsdl.Definition;
import org.eclipse.wst.wsdl.Types;
import org.eclipse.xsd.XSDComplexTypeDefinition;
import org.eclipse.xsd.XSDNamedComponent;
import org.eclipse.xsd.XSDSchema;
import org.eclipse.xsd.XSDSimpleTypeDefinition;
import org.eclipse.xsd.XSDTypeDefinition;
import org.eclipse.xsd.util.XSDConstants;
/**
* Content provider for XSDComplexType. It also handles built-in types.
*
* Expects an XSDSchema as input.
*/
public class XSDTypeOrElementContentProvider extends AbstractContentProvider {
final protected static List xsdPrimitiveTypes = XSDUtils.getAdvancedPrimitives();
final protected static HashSet xsdPrimitiveTypesNames = new HashSet(xsdPrimitiveTypes.size() + 1);
final public static int INCLUDE_SIMPLE_TYPES = 0x1;
final public static int INCLUDE_COMPLEX_TYPES = 0x2;
final public static int INCLUDE_TYPES = INCLUDE_SIMPLE_TYPES | INCLUDE_COMPLEX_TYPES;
final public static int INCLUDE_ELEMENT_DECLARATIONS = 0x4;
final public static int INCLUDE_PRIMITIVES = 0x8;
// https://issues.jboss.org/browse/JBIDE-8045
// fix typo
final public static int INCLUDE_ALL = 0xff;
static {
Iterator i = xsdPrimitiveTypes.iterator();
while (i.hasNext()) {
XSDNamedComponent component = (XSDNamedComponent) i.next();
xsdPrimitiveTypesNames.add( component.getName() );
}
}
private int fFilter = INCLUDE_ALL;
public void setFilter ( int filter ) {
fFilter = filter;
}
public int getFilter () {
return fFilter;
}
/**
* Append the schemas that are present in the object passed to the list
* indicated. This can deal with WSDL definitions, XSDSchema, and a List or Array
* of objects that any of those.
*
* @param input an object that has or is schema definitions.
* @param list the list where the schemas are put.
*/
public void collectElements ( Object input, List list) {
if (input == null) {
return ;
}
if (input instanceof Definition) {
Types types = ((Definition)input).getETypes();
if (types == null) {
return;
}
collectElements( types.getSchemas(), list);
return;
}
if (input instanceof XSDSchema) {
XSDSchema schema = (XSDSchema)input;
addSchemaElements(list, schema);
return;
}
collectComplex(input, list);
}
protected void addSchemaElements(List list, XSDSchema schema) {
boolean builtInTypesSchema = XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001.equals(schema.getTargetNamespace());
if (builtInTypesSchema && (fFilter & INCLUDE_PRIMITIVES) > 0 ) {
list.addAll ( XSDUtils.getAdvancedPrimitives () );
return ;
}
if ((fFilter & INCLUDE_ELEMENT_DECLARATIONS) > 0) {
list.addAll ( schema.getElementDeclarations() );
}
if ( (fFilter & INCLUDE_TYPES) == 0) {
return ;
}
List types = schema.getTypeDefinitions();
Iterator i = types.iterator();
boolean bAdd = false;
while (i.hasNext()) {
XSDTypeDefinition defn = (XSDTypeDefinition) i.next();
bAdd = ( ((fFilter & INCLUDE_COMPLEX_TYPES) > 0) && (defn instanceof XSDComplexTypeDefinition) ||
((fFilter & INCLUDE_SIMPLE_TYPES) > 0) && (defn instanceof XSDSimpleTypeDefinition) ) ;
if (bAdd) {
list.add(defn);
}
}
}
/**
* Helper method for identifying if a given type is a built-in type.
*/
public static boolean isBuiltInType(XSDTypeDefinition target) {
XSDSchema schema = (XSDSchema) target.eContainer();
if (!XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001.equals(schema.getTargetNamespace())) {
return false;
}
return xsdPrimitiveTypesNames.contains(target.getName());
}
}
| {
"content_hash": "cf0acf29467f728635823d8da3450676",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 107,
"avg_line_length": 26.09655172413793,
"alnum_prop": 0.7069238900634249,
"repo_name": "asankas/developer-studio",
"id": "14ced1ab149da33de3da555d7efbfbc1cfbf355a",
"size": "4318",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "bps/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/details/providers/XSDTypeOrElementContentProvider.java",
"mode": "33261",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.fontys.epic.core.impl;
import java.util.HashMap;
import java.util.logging.Logger;
import nl.fontys.epic.core.GameObject;
import nl.fontys.epic.core.Inventory;
import nl.fontys.epic.core.Room;
import nl.fontys.epic.core.RoomException;
import nl.fontys.epic.util.InventoryAdapter;
import nl.fontys.epic.util.MatrixList;
import nl.fontys.epic.util.Position;
/**
*
* @author Jan Kerkenhoff <jan.kerkenhoff@gmail.com>
*/
public class SimpleRoom extends SimpleIDProvider implements Room {
private final String name, welcomeMessage;
private int width = 3;
private int height= 3;
private final MatrixList<GameObject> objects;
private final MatrixList<InventoryAdapter> items;
public SimpleRoom(String name, String welcomeMessage, int width, int height, String ID) {
this(name,welcomeMessage,ID);
this.width = width;
this.height = height;
}
public SimpleRoom(String name, String welcomeMessage, String ID) {
super(ID);
this.name = name;
this.welcomeMessage = welcomeMessage;
this.objects = new MatrixList<>();
this.items = new MatrixList<>();
}
@Override
public GameObject getObject(int x, int y) {
if (hasObject(x,y)) {
return objects.get(x, y);
}
return null;
}
@Override
public boolean hasObject(int x, int y) {
return objects.contains(x, x);
}
@Override
public Inventory getItems(int x, int y) {
if(items.contains(x, y)){
return items.get(x, y);
}
return null;
}
@Override
public String getName() {
return this.name;
}
@Override
public void moveObject(GameObject object, int x, int y) throws RoomException {
if(x>this.width || y>this.height){
throw new RoomException("Index out of Bounds");
}
if(object.getRoom() != this){
throw new RoomException("Object not in this room");
}
objects.remove(object);
object.setPosition(x, y);
objects.add(object);
}
@Override
public void addObject(GameObject object) {
objects.add(object);
}
@Override
public void removeObject(int x, int y) {
objects.remove(x, y);
}
@Override
public int getWidth() {
return this.width;
}
@Override
public int getHeight() {
return this.height;
}
@Override
public String getWelcomeMessage() {
return this.welcomeMessage;
}
}
| {
"content_hash": "9853e10b3367b1eb982f4f330b7cec46",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 93,
"avg_line_length": 23.836206896551722,
"alnum_prop": 0.6242314647377939,
"repo_name": "kerko/epic",
"id": "4e2798e86968c7c392fc18b22796fb872e6ff3f8",
"size": "2765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "project/src/nl/fontys/epic/core/impl/SimpleRoom.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "161589"
},
{
"name": "TeX",
"bytes": "52821"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com" rel="preconnect" crossorigin="">
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono:400,500,700&display=fallback">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.ar_model.AutoRegResults.bic — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.ar_model.AutoRegResults.bse" href="statsmodels.tsa.ar_model.AutoRegResults.bse.html" />
<link rel="prev" title="statsmodels.tsa.ar_model.AutoRegResults.arfreq" href="statsmodels.tsa.ar_model.AutoRegResults.arfreq.html" />
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.ar_model.AutoRegResults.bic" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels 0.11.0</span>
<span class="md-header-nav__topic"> statsmodels.tsa.ar_model.AutoRegResults.bic </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../tsa.html" class="md-tabs__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.ar_model.AutoRegResults.html" class="md-tabs__link">statsmodels.tsa.ar_model.AutoRegResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels 0.11.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.ar_model.AutoRegResults.bic.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-ar-model-autoregresults-bic--page-root">statsmodels.tsa.ar_model.AutoRegResults.bic<a class="headerlink" href="#generated-statsmodels-tsa-ar-model-autoregresults-bic--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="attribute">
<dt id="statsmodels.tsa.ar_model.AutoRegResults.bic">
<code class="sig-prename descclassname">AutoRegResults.</code><code class="sig-name descname">bic</code><a class="headerlink" href="#statsmodels.tsa.ar_model.AutoRegResults.bic" title="Permalink to this definition">¶</a></dt>
<dd><p>Bayes Information Criterion</p>
<p><span class="math notranslate nohighlight">\(\ln(\sigma) + df_{model} \ln(nobs)/nobs\)</span></p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.ar_model.AutoRegResults.arfreq.html" title="Material"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.ar_model.AutoRegResults.arfreq </span>
</div>
</a>
<a href="statsmodels.tsa.ar_model.AutoRegResults.bse.html" title="Admonition"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.ar_model.AutoRegResults.bse </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Jan 22, 2020.
<br/>
Created using
<a href="http://sphinx-doc.org/">Sphinx</a> 2.3.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "58433d808d824bd337081d3b9a4b8090",
"timestamp": "",
"source": "github",
"line_count": 412,
"max_line_length": 999,
"avg_line_length": 42.29368932038835,
"alnum_prop": 0.6039024390243902,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "8e87c6a4bf0231a7993631ede27c5d126ab5af63",
"size": "17429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.11.0/generated/statsmodels.tsa.ar_model.AutoRegResults.bic.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
from __future__ import unicode_literals, print_function
import frappe
import hashlib
from frappe.model.db_schema import DbManager
from frappe.installer import get_root_connection
from frappe.database import Database
import os
from markdown2 import markdown
from bs4 import BeautifulSoup
import jinja2.exceptions
from six import text_type
def sync():
# make table
print('Syncing help database...')
help_db = HelpDatabase()
help_db.make_database()
help_db.connect()
help_db.make_table()
help_db.sync_pages()
help_db.build_index()
@frappe.whitelist()
def get_help(text):
return HelpDatabase().search(text)
@frappe.whitelist()
def get_help_content(path):
return HelpDatabase().get_content(path)
def get_improve_page_html(app_name, target):
docs_config = frappe.get_module(app_name + ".config.docs")
source_link = docs_config.source_link
branch = getattr(docs_config, "branch", "develop")
html = '''<div class="page-container">
<div class="page-content">
<div class="edit-container text-center">
<i class="fa fa-smile text-muted"></i>
<a class="edit text-muted" href="{source_link}/blob/{branch}/{target}">
Improve this page
</a>
</div>
</div>
</div>'''.format(source_link=source_link, app_name=app_name, target=target, branch=branch)
return html
class HelpDatabase(object):
def __init__(self):
self.global_help_setup = frappe.conf.get('global_help_setup')
if self.global_help_setup:
bench_name = os.path.basename(os.path.abspath(frappe.get_app_path('frappe')).split('/apps/')[0])
self.help_db_name = hashlib.sha224(bench_name).hexdigest()[:15]
def make_database(self):
'''make database for global help setup'''
if not self.global_help_setup:
return
dbman = DbManager(get_root_connection())
dbman.drop_database(self.help_db_name)
# make database
if not self.help_db_name in dbman.get_database_list():
try:
dbman.create_user(self.help_db_name, self.help_db_name)
except Exception as e:
# user already exists
if e.args[0] != 1396: raise
dbman.create_database(self.help_db_name)
dbman.grant_all_privileges(self.help_db_name, self.help_db_name)
dbman.flush_privileges()
def connect(self):
if self.global_help_setup:
self.db = Database(user=self.help_db_name, password=self.help_db_name)
else:
self.db = frappe.db
def make_table(self):
if not 'help' in self.db.get_tables():
self.db.sql('''create table help(
path varchar(255),
content text,
title text,
intro text,
full_path text,
fulltext(title),
fulltext(content),
index (path))
COLLATE=utf8mb4_unicode_ci
ENGINE=MyISAM
CHARACTER SET=utf8mb4''')
def search(self, words):
self.connect()
return self.db.sql('''
select title, intro, path from help where title like %s union
select title, intro, path from help where match(content) against (%s) limit 10''', ('%'+words+'%', words))
def get_content(self, path):
self.connect()
query = '''select title, content from help
where path like "{path}%" order by path desc limit 1'''
result = None
if not path.endswith('index'):
result = self.db.sql(query.format(path=os.path.join(path, 'index')))
if not result:
result = self.db.sql(query.format(path=path))
return {'title':result[0][0], 'content':result[0][1]} if result else {}
def sync_pages(self):
self.db.sql('truncate help')
doc_contents = '<ol>'
apps = os.listdir('../apps') if self.global_help_setup else frappe.get_installed_apps()
for app in apps:
docs_folder = '../apps/{app}/{app}/docs/user'.format(app=app)
self.out_base_path = '../apps/{app}/{app}/docs'.format(app=app)
if os.path.exists(docs_folder):
app_name = getattr(frappe.get_module(app), '__title__', None) or app.title()
doc_contents += '<li><a data-path="/{app}/index">{app_name}</a></li>'.format(
app=app, app_name=app_name)
for basepath, folders, files in os.walk(docs_folder):
files = self.reorder_files(files)
for fname in files:
if fname.rsplit('.', 1)[-1] in ('md', 'html'):
fpath = os.path.join(basepath, fname)
with open(fpath, 'r') as f:
try:
content = frappe.render_template(text_type(f.read(), 'utf-8'),
{'docs_base_url': '/assets/{app}_docs'.format(app=app)})
relpath = self.get_out_path(fpath)
relpath = relpath.replace("user", app)
content = markdown(content)
title = self.make_title(basepath, fname, content)
intro = self.make_intro(content)
content = self.make_content(content, fpath, relpath)
self.db.sql('''insert into help(path, content, title, intro, full_path)
values (%s, %s, %s, %s, %s)''', (relpath, content, title, intro, fpath))
except jinja2.exceptions.TemplateSyntaxError:
print("Invalid Jinja Template for {0}. Skipping".format(fpath))
doc_contents += "</ol>"
self.db.sql('''insert into help(path, content, title, intro, full_path) values (%s, %s, %s, %s, %s)''',
('/documentation/index', doc_contents, 'Documentation', '', ''))
def make_title(self, basepath, filename, html):
if '<h1>' in html:
title = html.split("<h1>", 1)[1].split("</h1>", 1)[0]
elif 'index' in filename:
title = basepath.rsplit('/', 1)[-1].title().replace("-", " ")
else:
title = filename.rsplit('.', 1)[0].title().replace("-", " ")
return title
def make_intro(self, html):
intro = ""
if '<p>' in html:
intro = html.split('<p>', 1)[1].split('</p>', 1)[0]
if 'Duration' in html:
intro = "Help Video: " + intro
return intro
def make_content(self, html, path, relpath):
if '<h1>' in html:
html = html.split('</h1>', 1)[1]
if '{next}' in html:
html = html.replace('{next}', '')
target = path.split('/', 3)[-1]
app_name = path.split('/', 3)[2]
html += get_improve_page_html(app_name, target)
soup = BeautifulSoup(html, 'html.parser')
self.fix_links(soup, app_name)
self.fix_images(soup, app_name)
parent = self.get_parent(relpath)
if parent:
parent_tag = soup.new_tag('a')
parent_tag.string = parent['title']
parent_tag['class'] = 'parent-link'
parent_tag['data-path'] = parent['path']
soup.find().insert_before(parent_tag)
return soup.prettify()
def fix_links(self, soup, app_name):
for link in soup.find_all('a'):
if link.has_attr('href'):
url = link['href']
if '/user' in url:
data_path = url[url.index('/user'):]
if '.' in data_path:
data_path = data_path[: data_path.rindex('.')]
if data_path:
link['data-path'] = data_path.replace("user", app_name)
def fix_images(self, soup, app_name):
for img in soup.find_all('img'):
if img.has_attr('src'):
url = img['src']
if '/docs/' in url:
img['src'] = url.replace('/docs/', '/assets/{0}_docs/'.format(app_name))
def build_index(self):
for data in self.db.sql('select path, full_path, content from help'):
self.make_index(data[0], data[1], data[2])
def make_index(self, original_path, full_path, content):
'''Make index from index.txt'''
if '{index}' in content:
path = os.path.dirname(full_path)
files = []
# get files from index.txt
index_path = os.path.join(path, "index.txt")
if os.path.exists(index_path):
with open(index_path, 'r') as f:
files = f.read().splitlines()
# files not in index.txt
for f in os.listdir(path):
if not os.path.isdir(os.path.join(path, f)):
name, extn = f.rsplit('.', 1)
if name not in files \
and name != 'index' and extn in ('md', 'html'):
files.append(name)
links_html = "<ol class='index-links'>"
for line in files:
fpath = os.path.join(os.path.dirname(original_path), line)
title = self.db.sql('select title from help where path like %s',
os.path.join(fpath, 'index') + '%')
if not title:
title = self.db.sql('select title from help where path like %s',
fpath + '%')
if title:
title = title[0][0]
links_html += "<li><a data-path='{fpath}'> {title} </a></li>".format(
fpath=fpath, title=title)
# else:
# bad entries in .txt files
# print fpath
links_html += "</ol>"
html = content.replace('{index}', links_html)
self.db.sql('update help set content=%s where path=%s', (html, original_path))
def get_out_path(self, path):
return '/' + os.path.relpath(path, self.out_base_path)
def get_parent(self, child_path):
if 'index' in child_path:
child_path = child_path[: child_path.rindex('index')]
if child_path[-1] == '/':
child_path = child_path[:-1]
child_path = child_path[: child_path.rindex('/')]
out = None
if child_path:
parent_path = child_path + "/index"
out = self.get_content(parent_path)
#if parent is documentation root
else:
parent_path = "/documentation/index"
out = {}
out['title'] = "Documentation"
if not out:
return None
out['path'] = parent_path
return out
def reorder_files(self, files):
pos = 0
if 'index.md' in files:
pos = files.index('index.md')
elif 'index.html' in files:
pos = files.index('index.html')
if pos:
files[0], files[pos] = files[pos], files[0]
return files
| {
"content_hash": "edfba66c884b1979b824a893476d1fa0",
"timestamp": "",
"source": "github",
"line_count": 298,
"max_line_length": 109,
"avg_line_length": 30.738255033557046,
"alnum_prop": 0.6354803493449782,
"repo_name": "tmimori/frappe",
"id": "45971820c0c91f8d35cdaba0834fc93548b9c0a2",
"size": "9288",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "frappe/utils/help.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "237768"
},
{
"name": "HTML",
"bytes": "133546"
},
{
"name": "JavaScript",
"bytes": "1331599"
},
{
"name": "Python",
"bytes": "1091219"
},
{
"name": "Shell",
"bytes": "517"
}
],
"symlink_target": ""
} |
require('./base');
describe('Table tests', function() {
describe('Constructor values', function() {
it('Test various values', function(done) {
ObjectManager.get('com://home/menu.database.table.items')
.then(function(table) {
table.should.have.property('name', 'menu_items')
table.getIdentifier().toString().should.equal('com://home/menu.database.table.items');
table.getRow().should.be.an.instanceOf(Promise);
table.getRowset().should.be.an.instanceOf(Promise);
done();
});
});
});
describe('#getRow()', function() {
it('Should return a Row object', function(done) {
ObjectManager.get('com://home/menu.database.table.items')
.then(function(table) {
return table.getRow();
})
.then(function(row) {
row.should.be.an.instanceOf(Raddish.Row);
done();
});
});
});
describe('#getRowset()', function() {
it('Should return a Rowset object', function(done) {
ObjectManager.get('com://home/menu.database.table.items')
.then(function(table) {
return table.getRowset();
})
.then(function(rowset) {
rowset.should.be.an.instanceOf(Raddish.Rowset);
done();
});
});
});
}); | {
"content_hash": "ace520096c13a1bdc13e8ee7b3651625",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 106,
"avg_line_length": 33.73913043478261,
"alnum_prop": 0.4793814432989691,
"repo_name": "polidog/raddish",
"id": "44856c9263babd2173f56d75f4eb2cb499e86be3",
"size": "1552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/table.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Tchaik is an open source music organisation and streaming system. The backend is written in [Go](http://golang.org), the frontend is built using [React](https://facebook.github.io/react/), [Flux](https://facebook.github.io/flux/) and [PostCSS](https://github.com/postcss/postcss).

")
# Features
* Automatic prefix grouping and enumeration detection (ideal for classical music: properly groups big works together).
* Multiplatform web-based UI and REST-like API for controlling player.
* Multiple storage and caching options: Amazon S3, Google Cloud Storage, local and remote file stores.
* Import music library from iTunes or build from directory-tree of audio tracks.
# Requirements
* [Go 1.4+](http://golang.org/dl/) (recent changes have only been tested on 1.4.2).
* [NodeJS](https://nodejs.org/), [NPM](https://www.npmjs.com/) and [Gulp](http://gulpjs.com/) installed globally (for building the UI).
* Recent version of Chrome (Firefox may also work, though hasn't been fully tested).
# Building
If you haven't setup Go before, you need to first set a `GOPATH` (see [https://golang.org/doc/code.html#GOPATH](https://golang.org/doc/code.html#GOPATH)).
To fetch and build the code for Tchaik:
$ go get tchaik.com/cmd/...
This will fetch the code and build the command line tools into `$GOPATH/bin` (assumed to be in your `PATH` already).
Building the UI:
$ cd $GOPATH/src/tchaik.com/cmd/tchaik/ui
$ npm install
$ gulp
Alternatively, if you want the JS and CSS to be recompiled and have the browser refreshed as you change the source files:
$ WS_URL="ws://localhost:8080/socket" gulp serve
Then browse to `http://localhost:3000/` to use tchaik.
# Starting the UI
To start Tchaik you first need to move into the `cmd/tchaik` directory:
$ cd $GOPATH/src/tchaik.com/cmd/tchaik
## Importing an iTunes Library
The easiest way to begin is to build a Tchaik library on-the-fly and start the UI in one command:
$ tchaik -itlXML ~/path/to/iTunesLibrary.xml
You can also convert the iTunes Library into a Tchaik library using the `tchimport` tool:
$ tchimport -itlXML ~/path/to/iTunesLibrary.xml -out lib.tch
$ tchaik -lib lib.tch
NB: A Tchaik library will generally be smaller than its corresponding iTunes Library. Tchaik libraries are stored as gzipped-JSON (rather than Apple plist) and contain a subset of the metadata used by iTunes.
## Importing Audio Files
Alternatively you can build a Tchaik library on-the-fly from a directory-tree of audio files. Only files with supported metadata (see [github.com/dhowden/tag](https://github.com/dhowden/tag)) will be included in the index:
$ tchaik -path /all/my/music
To avoid rescanning your entire collection every time you restart, you can build a Tchaik library using the `tchimport` tool:
$ tchimport -path /all/my/music -out lib.tch
$ tchaik -lib lib.tch
# More Advanced Options
A full list of command line options is available from the `--help` flag:
$ tchaik --help
Usage of ./tchaik:
-add-path-prefix="": add prefix to every path
-artwork-cache="": path to local artwork cache (content addressable)
-auth-password="": password to use for HTTP authentication
-auth-user="": username to use for HTTP authentication (set to enable)
-debug=false: print debugging information
-itlXML="": path to iTunes Library XML file
-lib="": path to Tchaik library file
-listen="localhost:8080": bind address to http listen
-local-store="/": local media store, full local path /path/to/root
-media-cache="": path to local media cache
-path="": path to directory containing music files (to build index from)
-play-history="history.json": path to play history file
-remote-store="": remote media store, tchstore server address <hostname>:<port>, s3://<bucket>/path/to/root for S3, or gs://<project-id>:<bucket>/path/to/root for Google Cloud Storage
-static-dir="ui/static": Path to the static asset directory
-tls-cert="": path to a certificate file, must also specify -tls-key
-tls-key="": path to a certificate key file, must also specify -tls-cert
-trace-listen="": bind address for trace HTTP server
-trim-path-prefix="": remove prefix from every path
### -local-store
Set `-local-store` to the local path that contains your media files. You can use `trim-path-prefix` and `add-path-prefix` to rewrite paths used in the Tchaik library so that file locations can still be correctly resolved.
### -remote-store
Set `-remote-store` to the URI of a running [tchstore](http://godoc.org/tchaik.com/cmd/tchstore) server (`hostname:port`). Instead, S3 paths can be used: `s3://<bucket>/path/to/root` (set the environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` to pass credentials to the S3 client), or Google Cloud Storage paths: `gs://<project-id>:<bucket>/path/to/root` (set the GOOGLE_APPLICATION_CREDENTIALS to point at your JSON credentials file).
### -media-cache
Set `-media-cache` to cache all files loaded from `-remote-store` (or `-local-store` if set).
### -artwork-cache
Set `-artwork-cache` to create/use a content addressable filesystem for track artwork. An index file will be created in the path on first use. The folder should initially be empty to ensure that no other files interfere with the system.
### -trace-listen
Set `-trace-listen` to a suitable bind address (i.e. `localhost:4040`) to start an HTTP server which defines the `/debug/requests` endpoint used to inspect server requests. Currently we only support tracing for media (track/artwork/icon) requests. See [https://godoc.org/golang.org/x/net/trace](https://godoc.org/golang.org/x/net/trace) for more details.
# Get Involved!
Development is on-going and the codebase is changing very quickly. If you're interested in contributing then it's safest to jump into our gitter room and chat to people before getting started!
[](https://gitter.im/tchaik/tchaik?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
| {
"content_hash": "f506047db195f648d1f0be79eec379eb",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 456,
"avg_line_length": 53.325,
"alnum_prop": 0.7323019221753398,
"repo_name": "GrahamGoudeau21/tchaik",
"id": "6e3c0aafa2ca10c0d25aecde2e3ef669d437f594",
"size": "6442",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "31463"
},
{
"name": "Go",
"bytes": "206405"
},
{
"name": "HTML",
"bytes": "488"
},
{
"name": "JavaScript",
"bytes": "129156"
},
{
"name": "Makefile",
"bytes": "563"
},
{
"name": "Shell",
"bytes": "162"
}
],
"symlink_target": ""
} |
package org.apache.flink.runtime.io.network.netty;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.runtime.util.FatalExitExceptionHandler;
import org.apache.flink.shaded.guava18.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap;
import org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture;
import org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer;
import org.apache.flink.shaded.netty4.io.netty.channel.ChannelOption;
import org.apache.flink.shaded.netty4.io.netty.channel.epoll.Epoll;
import org.apache.flink.shaded.netty4.io.netty.channel.epoll.EpollEventLoopGroup;
import org.apache.flink.shaded.netty4.io.netty.channel.epoll.EpollServerSocketChannel;
import org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup;
import org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel;
import org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ThreadFactory;
import java.util.function.Function;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
class NettyServer {
private static final ThreadFactoryBuilder THREAD_FACTORY_BUILDER =
new ThreadFactoryBuilder()
.setDaemon(true)
.setUncaughtExceptionHandler(FatalExitExceptionHandler.INSTANCE);
private static final Logger LOG = LoggerFactory.getLogger(NettyServer.class);
private final NettyConfig config;
private ServerBootstrap bootstrap;
private ChannelFuture bindFuture;
private InetSocketAddress localAddress;
NettyServer(NettyConfig config) {
this.config = checkNotNull(config);
localAddress = null;
}
int init(final NettyProtocol protocol, NettyBufferPool nettyBufferPool) throws IOException {
return init(
nettyBufferPool,
sslHandlerFactory -> new ServerChannelInitializer(protocol, sslHandlerFactory));
}
int init(
NettyBufferPool nettyBufferPool,
Function<SSLHandlerFactory, ServerChannelInitializer> channelInitializer) throws IOException {
checkState(bootstrap == null, "Netty server has already been initialized.");
final long start = System.nanoTime();
bootstrap = new ServerBootstrap();
// --------------------------------------------------------------------
// Transport-specific configuration
// --------------------------------------------------------------------
switch (config.getTransportType()) {
case NIO:
initNioBootstrap();
break;
case EPOLL:
initEpollBootstrap();
break;
case AUTO:
if (Epoll.isAvailable()) {
initEpollBootstrap();
LOG.info("Transport type 'auto': using EPOLL.");
}
else {
initNioBootstrap();
LOG.info("Transport type 'auto': using NIO.");
}
}
// --------------------------------------------------------------------
// Configuration
// --------------------------------------------------------------------
// Server bind address
bootstrap.localAddress(config.getServerAddress(), config.getServerPort());
// Pooled allocators for Netty's ByteBuf instances
bootstrap.option(ChannelOption.ALLOCATOR, nettyBufferPool);
bootstrap.childOption(ChannelOption.ALLOCATOR, nettyBufferPool);
if (config.getServerConnectBacklog() > 0) {
bootstrap.option(ChannelOption.SO_BACKLOG, config.getServerConnectBacklog());
}
// Receive and send buffer size
int receiveAndSendBufferSize = config.getSendAndReceiveBufferSize();
if (receiveAndSendBufferSize > 0) {
bootstrap.childOption(ChannelOption.SO_SNDBUF, receiveAndSendBufferSize);
bootstrap.childOption(ChannelOption.SO_RCVBUF, receiveAndSendBufferSize);
}
// SSL related configuration
final SSLHandlerFactory sslHandlerFactory;
try {
sslHandlerFactory = config.createServerSSLEngineFactory();
} catch (Exception e) {
throw new IOException("Failed to initialize SSL Context for the Netty Server", e);
}
// --------------------------------------------------------------------
// Child channel pipeline for accepted connections
// --------------------------------------------------------------------
bootstrap.childHandler(channelInitializer.apply(sslHandlerFactory));
// --------------------------------------------------------------------
// Start Server
// --------------------------------------------------------------------
bindFuture = bootstrap.bind().syncUninterruptibly();
localAddress = (InetSocketAddress) bindFuture.channel().localAddress();
final long duration = (System.nanoTime() - start) / 1_000_000;
LOG.info("Successful initialization (took {} ms). Listening on SocketAddress {}.", duration, localAddress);
return localAddress.getPort();
}
NettyConfig getConfig() {
return config;
}
ServerBootstrap getBootstrap() {
return bootstrap;
}
void shutdown() {
final long start = System.nanoTime();
if (bindFuture != null) {
bindFuture.channel().close().awaitUninterruptibly();
bindFuture = null;
}
if (bootstrap != null) {
if (bootstrap.group() != null) {
bootstrap.group().shutdownGracefully();
}
bootstrap = null;
}
final long duration = (System.nanoTime() - start) / 1_000_000;
LOG.info("Successful shutdown (took {} ms).", duration);
}
private void initNioBootstrap() {
// Add the server port number to the name in order to distinguish
// multiple servers running on the same host.
String name = NettyConfig.SERVER_THREAD_GROUP_NAME + " (" + config.getServerPort() + ")";
NioEventLoopGroup nioGroup = new NioEventLoopGroup(config.getServerNumThreads(), getNamedThreadFactory(name));
bootstrap.group(nioGroup).channel(NioServerSocketChannel.class);
}
private void initEpollBootstrap() {
// Add the server port number to the name in order to distinguish
// multiple servers running on the same host.
String name = NettyConfig.SERVER_THREAD_GROUP_NAME + " (" + config.getServerPort() + ")";
EpollEventLoopGroup epollGroup = new EpollEventLoopGroup(config.getServerNumThreads(), getNamedThreadFactory(name));
bootstrap.group(epollGroup).channel(EpollServerSocketChannel.class);
}
public static ThreadFactory getNamedThreadFactory(String name) {
return THREAD_FACTORY_BUILDER.setNameFormat(name + " Thread %d").build();
}
@VisibleForTesting
static class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
private final NettyProtocol protocol;
private final SSLHandlerFactory sslHandlerFactory;
public ServerChannelInitializer(
NettyProtocol protocol, SSLHandlerFactory sslHandlerFactory) {
this.protocol = protocol;
this.sslHandlerFactory = sslHandlerFactory;
}
@Override
public void initChannel(SocketChannel channel) throws Exception {
if (sslHandlerFactory != null) {
channel.pipeline().addLast("ssl",
sslHandlerFactory.createNettySSLHandler(channel.alloc()));
}
channel.pipeline().addLast(protocol.getServerChannelHandlers());
}
}
}
| {
"content_hash": "309f5813258b634e59664c84ece124c8",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 118,
"avg_line_length": 34.08571428571429,
"alnum_prop": 0.7034087734003912,
"repo_name": "kaibozhou/flink",
"id": "fb71446b95d846db614474cbcea08948dccb86a3",
"size": "7963",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/NettyServer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4722"
},
{
"name": "CSS",
"bytes": "58149"
},
{
"name": "Clojure",
"bytes": "93247"
},
{
"name": "Dockerfile",
"bytes": "12142"
},
{
"name": "FreeMarker",
"bytes": "28662"
},
{
"name": "HTML",
"bytes": "108850"
},
{
"name": "Java",
"bytes": "53661126"
},
{
"name": "JavaScript",
"bytes": "1829"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "1129763"
},
{
"name": "Scala",
"bytes": "13885013"
},
{
"name": "Shell",
"bytes": "533455"
},
{
"name": "TSQL",
"bytes": "123113"
},
{
"name": "TypeScript",
"bytes": "249103"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>paramcoq: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.2 / paramcoq - 1.1.1+coq8.7</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
paramcoq
<small>
1.1.1+coq8.7
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-14 02:44:10 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-14 02:44:10 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.04.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.04.2 Official 4.04.2 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
synopsis: "Paramcoq"
name: "coq-paramcoq"
version: "1.1.1+coq8.7"
maintainer: "Pierre Roux <pierre.roux@onera.fr>"
homepage: "https://github.com/coq-community/paramcoq"
dev-repo: "git+https://github.com/coq-community/paramcoq.git"
bug-reports: "https://github.com/coq-community/paramcoq/issues"
license: "MIT"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Param"]
depends: [
"ocaml"
"coq" {>= "8.7.2" & < "8.8~"}
]
tags: [
"keyword:paramcoq"
"keyword:parametricity"
"keyword:OCaml modules"
"category:Miscellaneous/Coq Extensions"
"logpath:Param"
]
authors: [
"Chantal Keller (Inria, École polytechnique)"
"Marc Lasson (ÉNS de Lyon)"
"Abhishek Anand"
"Pierre Roux"
"Emilio Jesús Gallego Arias"
"Cyril Cohen"
"Matthieu Sozeau"
]
flags: light-uninstall
url {
src:
"https://github.com/coq-community/paramcoq/releases/download/v1.1.1+coq8.7/coq-paramcoq.1.1.1+coq8.7.tgz"
checksum: "md5=3eb94ccdb53e6dfc7f0d74b3cd1a5db5"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-paramcoq.1.1.1+coq8.7 coq.8.8.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.2).
The following dependencies couldn't be met:
- coq-paramcoq -> coq < 8.8~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-paramcoq.1.1.1+coq8.7</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "a7e3fcb3ced8b8be89276dc43a3011e7",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 39.87845303867403,
"alnum_prop": 0.5454419506788584,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "bb8ad2a5c692ff37407aaf322ce7927bb15f10d6",
"size": "7246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.8.2/paramcoq/1.1.1+coq8.7.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
xcnote () {
echo >&2 "${BASH_SOURCE[1]}:${BASH_LINENO[0]}: note: $*"
}
# Output a clickable message prefixed with a warning symbol (U+26A0)
# and highlighted yellow. This will increase the overall warning
# count. A non-zero value for the variable ERRORS_ONLY will force
# warnings to be treated as errors.
if ((ERRORS_ONLY)); then
xcwarning () {
echo >&2 "${BASH_SOURCE[1]}:${BASH_LINENO[0]}: error: $*"
}
else
xcwarning () {
echo >&2 "${BASH_SOURCE[1]}:${BASH_LINENO[0]}: warning: $*"
}
fi
# Output a clickable message prefixed with a halt symbol (U+1F6D1) and
# highlighted red. This will increase the overall error count. Xcode
# will flag the build as failed if the error count is non-zero at the
# end of the build, even if this script returns a successful exit
# code. Set WARNINGS_ONLY to non-zero to prevent this.
if ((WARNINGS_ONLY)); then
xcerror () {
echo >&2 "${BASH_SOURCE[1]}:${BASH_LINENO[0]}: warning: $*"
}
else
xcerror () {
echo >&2 "${BASH_SOURCE[1]}:${BASH_LINENO[0]}: error: $*"
}
fi
xcdebug () {
if ((VERBOSE)); then xcnote "$*"; fi
}
# Locate the script directory.
script_dir () {
local SCRIPT
if [[ "$0" == */* ]]; then SCRIPT="$0"; else SCRIPT="./$0"; fi
while [[ -L "$SCRIPT" ]]; do
local LINK="$(readlink "$SCRIPT")"
if [[ "$LINK" == /* ]]; then
SCRIPT="$LINK"
else
SCRIPT="${SCRIPT%/*}/$LINK"
fi
done
( cd "${SCRIPT%/*}"; pwd -P )
}
# All files created by fcr_mktemp will be listed in FCR_TEMPORARY_FILES.
# Delete these when the enclosing script exits.
typeset -a FCR_TEMPORARY_FILES
trap 'STATUS=$?; rm -rf "${FCR_TEMPORARY_FILES[@]}"; exit $STATUS' 0 1 2 15
# Create a temporary file and add it to the list of files to delete when the
# script finishes.
#
# Arguments: Variable names in which to store the generated file names.
fcr_mktemp () {
for VAR; do
eval "$VAR=\$(mktemp -t com.google.FirebaseCrashReporter) || return 1"
FCR_TEMPORARY_FILES+=("${!VAR}")
done
}
# Create a temporary directory and add it to the list of files to
# delete when the script finishes.
#
# Arguments: Variable names in which to store the generated file names.
fcr_mktempdir () {
for VAR; do
eval "$VAR=\$(mktemp -d -t com.google.FirebaseCrashReporter) || return 1"
FCR_TEMPORARY_FILES+=("${!VAR}")
done
}
# BASE64URL uses a sligtly different character set than BASE64, and uses no
# padding characters.
function base64url () {
/usr/bin/base64 | sed -e 's/=//g; s/+/-/g; s/\//_/g'
}
FCR_SVC_KEYS=(auth_provider_x509_cert_url auth_uri client_email client_id client_x509_cert_url private_key private_key_id project_id token_uri type)
FCR_TOK_KEYS=(access_token expires_at token_type)
# Retrieve the property from the service account property list using
# the application ID. Assumes the APP_KEY variable has been
# initialized, which contains the application key translated to a
# property name. To examine the top level of the property list,
# temporarily set APP_KEY to the empty string.
svc_property () {
/usr/libexec/PlistBuddy "${SVC_PLIST}" \
-c "Print ${APP_KEY:+:${APP_KEY}}${1:+:$1}" 2>/dev/null
}
# Does the same as svc_property above but for the token cache
# property list.
tok_property () {
/usr/libexec/PlistBuddy "${TOK_PLIST}" \
-c "Print ${APP_KEY:+:${APP_KEY}}${1:+:$1}" 2>/dev/null
}
# Verify that the service account property list has values for the
# required keys. Does not check the values themselves.
fcr_verify_svc_plist () {
for key in "${FCR_SVC_KEYS[@]}"; do
if ! svc_property "$key" >/dev/null; then
xcdebug "$key not found in $SVC_PLIST. Service account invalid."
return 1
fi
done
}
# Verify that the token cache property list has values for the
# required keys. If the token_type is incorrect or the expiration
# date has been passed, return failure.
fcr_verify_tok_plist () {
for key in "${FCR_TOK_KEYS[@]}"; do
if ! tok_property "$key" >/dev/null; then
xcdebug "$key not found in $TOK_PLIST. Token invalid."
return 1
fi
done
if [[ "$(tok_property token_type)" != "Bearer" ]]; then
xcwarning "Invalid token type '$(tok_property token_type)'."
return 1
fi
if (($(tok_property expires_at) <= NOW)); then
xcdebug "Token well-formed but expired."
return 1
fi
}
#
# If the user has an existing version 0 property list, try to convert
# it to the new format, assuming that the current app ID is the
# correct one.
#
fcr_legacy_format_conversion_0 () {
VERSION="$(APP_KEY='' svc_property version)"
# Handle situation where VERSION is absent or malformed.
[[ "${VERSION}" =~ ^[[:digit:]]+$ ]] || VERSION=0
((VERSION < 1)) || return
for key in "${FCR_SVC_KEYS[@]}"; do
if ! (APP_KEY='' svc_property "$key" >/dev/null 2>&1); then
/usr/libexec/PlistBuddy "$SVC_PLIST" -c 'Clear dict' >/dev/null 2>&1
/usr/libexec/PlistBuddy "$TOK_PLIST" -c 'Clear dict' >/dev/null 2>&1
return
fi
done
xcnote "Converting certificate information to version 1."
/usr/libexec/PlistBuddy "$SVC_PLIST" \
-c "Copy : :$APP_KEY" \
-c "Add :version integer 1" >/dev/null 2>&1
for key in "${FCR_SVC_KEYS[@]}"; do
/usr/libexec/PlistBuddy "$SVC_PLIST" -c "Delete :$key" >/dev/null 2>&1
done
/usr/libexec/PlistBuddy "$TOK_PLIST" -c 'Clear dict' >/dev/null 2>&1
}
# Set the BEARER_TOKEN variable for authentication.
#
# Requires interaction if the file has not been installed correctly.
#
# No arguments.
fcr_authenticate () {
: "${FIREBASE_APP_ID:?FIREBASE_APP_ID is required to select authentication credentials}"
local SVC_PLIST="$HOME/Library/Preferences/com.google.SymbolUpload.plist"
local TOK_PLIST="$HOME/Library/Preferences/com.google.SymbolUploadToken.plist"
# Translate FIREBASE_APP_ID to a property list key. This involves
# prefixing it with an alphabetic character and replacing all
# colons with underscores. Technically, property lists can use
# any legal string as a key, but some of the utilities are more
# finicky than others.
local APP_KEY="app_${FIREBASE_APP_ID//:/_}"
# Convert service account plist version 0 to version 1 if needed.
fcr_legacy_format_conversion_0
if ((VERBOSE > 2)); then
CURLOPT='--trace-ascii /dev/fd/2'
elif ((VERBOSE > 1)); then
CURLOPT='--verbose'
else
CURLOPT=''
fi
local NOW="$(/bin/date +%s)"
# If the certificate property list does not contain the required
# keys, delete it and the token property list.
if ! fcr_verify_svc_plist; then
xcdebug "Invalid certificate information for $FIREBASE_APP_ID."
/usr/libexec/PlistBuddy "$SVC_PLIST" -c "Delete $APP_KEY" >/dev/null 2>&1
/usr/libexec/PlistBuddy "$TOK_PLIST" -c "Delete $APP_KEY" >/dev/null 2>&1
else
xcdebug "Certificate information valid."
fi
# If the token will expire in the next sixty seconds (or already
# has), reload it.
if ! fcr_verify_tok_plist; then
xcdebug "Token is invalid. Refreshing..."
if ! fcr_verify_svc_plist; then
xcdebug "Service account information is invalid. Requesting reload..."
if [[ "$SERVICE_ACCOUNT_FILE" && -f "$SERVICE_ACCOUNT_FILE" ]]; then
xcdebug "Using $SERVICE_ACCOUNT_FILE for credentials."
else
SERVICE_ACCOUNT_FILE="$(/usr/bin/osascript -e 'the POSIX path of (choose file with prompt "Where is the service account file?" of type "public.json")' 2>/dev/null)"
fi
/usr/libexec/PlistBuddy "$SVC_PLIST" \
-c "Add :version integer 1"
if [[ "$SERVICE_ACCOUNT_FILE" && -f "$SERVICE_ACCOUNT_FILE" ]]; then
/usr/bin/plutil -replace "$APP_KEY" -json "$(/bin/cat "$SERVICE_ACCOUNT_FILE")" "$SVC_PLIST" || return 2
if fcr_verify_svc_plist; then
xcdebug "Installed service account file into $SVC_PLIST."
else
/usr/libexec/PlistBuddy "$SVC_PLIST" -c "Delete $APP_KEY" >/dev/null 2>&1
xcerror "Unable to parse service account file."
return 2
fi
else
xcerror "User cancelled symbol uploading."
return 1
fi
fi
xcdebug "Requesting OAuth2 token using installed credentials."
TOKEN_URI="$(svc_property token_uri)"
CLIENT_EMAIL="$(svc_property client_email)"
# Assemble the JSON Web Token (RFC 1795)
local JWT_HEADER='{"alg":"RS256","typ":"JWT"}'
JWT_HEADER="$(echo -n "$JWT_HEADER" | base64url)"
local JWT_CLAIM='{"iss":"'"$CLIENT_EMAIL"'","scope":"https://www.googleapis.com/auth/mobilecrashreporting","aud":"'"$TOKEN_URI"'","exp":'"$((NOW + 3600))"',"iat":'"$NOW"'}'
JWT_CLAIM="$(echo -n "$JWT_CLAIM" | base64url)"
local JWT_SIG="$(echo -n "$JWT_HEADER.$JWT_CLAIM" | openssl dgst -sha256 -sign <(svc_property private_key) -binary | base64url)"
local JWT="$JWT_HEADER.$JWT_CLAIM.$JWT_SIG"
if [[ "$(tok_property version)" != 1 ]]; then
/usr/libexec/PlistBuddy "$TOK_PLIST" \
-c "Clear dict" \
-c "Add :version integer 1" >/dev/null 2>&1
fi
fcr_mktemp TOKEN_JSON
HTTP_STATUS="$(curl $CURLOPT -o "$TOKEN_JSON" -s -d grant_type='urn:ietf:params:oauth:grant-type:jwt-bearer' -d assertion="$JWT" -w '%{http_code}' "$TOKEN_URI")"
if [[ "$HTTP_STATUS" == 403 ]]; then
xcerror "Invalid certificate. Unable to retrieve OAuth2 token."
/usr/libexec/PlistBuddy "$SVC_PLIST" -c "Delete $APP_KEY" >/dev/null 2>&1
return 2
fi
/usr/bin/plutil -replace "$APP_KEY" -json "$(cat "$TOKEN_JSON")" \
"$TOK_PLIST" || return 1
EXPIRES_AT="$(($(tok_property expires_in) + NOW))"
/usr/libexec/PlistBuddy "$TOK_PLIST" \
-c "Add :$APP_KEY:expires_at integer $EXPIRES_AT" \
-c "Add :$APP_KEY:expiration_date date $(date -jf %s "$EXPIRES_AT")" >/dev/null 2>&1
if ! fcr_verify_tok_plist; then
xcwarning "Token returned is not valid. If this error persists, remove the certificate."
xcnote "To remove the certificate, execute the following command: defaults delete com.google.SymbolUpload $APP_KEY"
xcnote "You will need to reinstall the JSON credential file."
fi
else
xcdebug "Token still valid."
EXPIRES_AT="$(tok_property expires_at)"
fi
xcdebug "Token will expire at $(date -jf %s +'%r %Z' "$EXPIRES_AT")."
xcdebug "Using service account with key $(svc_property private_key_id)"
BEARER_TOKEN="$(tok_property access_token)"
if [[ ! "$BEARER_TOKEN" ]]; then
# Calling tok_property without an argument dumps the entire
# token cache to the console.
tok_property
xcerror "Unable to retrieve authentication token from server."
/usr/libexec/PlistBuddy "$TOK_PLIST" -c "Delete $APP_KEY"
return 2
fi
return 0
}
# Upload the files to the server.
#
# Arguments: Names of files to upload.
fcr_upload_files() {
fcr_authenticate || return $?
: "${FCR_PROD_VERS:?}"
: "${FCR_BUNDLE_ID:?}"
: "${FIREBASE_APP_ID:?}"
: "${FIREBASE_API_KEY:?}"
: "${FCR_BASE_URL:=https://mobilecrashreporting.googleapis.com}"
fcr_mktemp FILE_UPLOAD_LOCATION_PLIST META_UPLOAD_RESULT_PLIST
if ((VERBOSE > 2)); then
CURLOPT='--trace-ascii /dev/fd/2'
elif ((VERBOSE > 1)); then
CURLOPT='--verbose'
else
CURLOPT=''
fi
for FILE; do
xcdebug "Get signed URL for uploading."
URL="$FCR_BASE_URL/v1/apps/$FIREBASE_APP_ID"
HTTP_STATUS="$(curl $CURLOPT -o "$FILE_UPLOAD_LOCATION_PLIST" -sL -H "X-Ios-Bundle-Identifier: $FCR_BUNDLE_ID" -H "Authorization: Bearer $BEARER_TOKEN" -X POST -d '' -w '%{http_code}' "$URL/symbolFileUploadLocation?key=$FIREBASE_API_KEY")"
STATUS=$?
if [[ "$STATUS" == 22 && "$HTTP_STATUS" == 403 ]]; then
xcerror "Unable to access resource. Token invalid."
xcnote "You will have to reinstall the service account file."
/usr/libexec/PlistBuddy -c "delete :$APP_KEY" "$SVC_PLIST"
return 2
elif [[ "$STATUS" != 0 ]]; then
xcerror "curl exited with non-zero status $STATUS."
((STATUS == 22)) && xcerror "HTTP response code is $HTTP_STATUS."
return 2
fi
plutil -convert binary1 "$FILE_UPLOAD_LOCATION_PLIST" || return 1
UPLOAD_KEY="$(/usr/libexec/PlistBuddy -c 'print uploadKey' "$FILE_UPLOAD_LOCATION_PLIST" 2>/dev/null)"
UPLOAD_URL="$(/usr/libexec/PlistBuddy -c 'print uploadUrl' "$FILE_UPLOAD_LOCATION_PLIST" 2>/dev/null)"
ERRMSG="$(/usr/libexec/PlistBuddy -c 'print error:message' "$FILE_UPLOAD_LOCATION_PLIST" 2>/dev/null)"
if [[ "$ERRMSG" ]]; then
if ((VERBOSE)); then
xcnote "Server response:"
plutil -p "$FILE_UPLOAD_LOCATION_PLIST" >&2
fi
xcerror "symbolFileUploadLocation: $ERRMSG"
xcnote "symbolFileUploadLocation: Failed to get upload location."
return 1
fi
xcdebug "Upload symbol file."
HTTP_STATUS=$(curl $CURLOPT -sfL -H 'Content-Type: text/plain' -H "Authorization: Bearer $BEARER_TOKEN" -w '%{http_code}' -T "$FILE" "$UPLOAD_URL")
STATUS=$?
if ((STATUS == 22)); then # exit code 22 is a non-successful HTTP response
xcerror "upload: Unable to upload symbol file (HTTP Status $HTTP_STATUS)."
return 1
elif ((STATUS != 0)); then
xcerror "upload: Unable to upload symbol file (reason unknown)."
return 1
fi
xcdebug "Upload metadata information."
curl $CURLOPT -sL -H 'Content-Type: application/json' -H "X-Ios-Bundle-Identifier: $FCR_BUNDLE_ID" -H "Authorization: Bearer $BEARER_TOKEN" -X POST -d '{"upload_key":"'"$UPLOAD_KEY"'","symbol_file_mapping":{"symbol_type":2,"app_version":"'"$FCR_PROD_VERS"'"}}' "$URL/symbolFileMappings:upsert?key=$FIREBASE_API_KEY" >|"$META_UPLOAD_RESULT_PLIST" || return 1
plutil -convert binary1 "$META_UPLOAD_RESULT_PLIST" || return 1
ERRMSG="$(/usr/libexec/PlistBuddy -c 'print error:message' "$META_UPLOAD_RESULT_PLIST" 2>/dev/null)"
if [[ "$ERRMSG" ]]; then
xcerror "symbolFileMappings:upsert: $ERRMSG"
xcnote "symbolFileMappings:upsert: The metadata for the symbol file failed to update."
return 1
fi
done
}
| {
"content_hash": "e2cb22db572a74b34e7db509c7f905f3",
"timestamp": "",
"source": "github",
"line_count": 411,
"max_line_length": 365,
"avg_line_length": 36.39659367396594,
"alnum_prop": 0.6085299819506651,
"repo_name": "ethanneff/organize",
"id": "200c823fb4c3557b50f17b845355c26dc088481b",
"size": "15036",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Pods/FirebaseCrash/upload-sym-util.bash",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Swift",
"bytes": "178744"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.camel</groupId>
<artifactId>components</artifactId>
<version>3.9.0-SNAPSHOT</version>
</parent>
<artifactId>camel-univocity-parsers</artifactId>
<packaging>jar</packaging>
<name>Camel :: UniVocity Parsers</name>
<description>Camel UniVocity parsers data format support</description>
<properties>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-support</artifactId>
</dependency>
<dependency>
<groupId>com.univocity</groupId>
<artifactId>univocity-parsers</artifactId>
<version>${univocity-parsers-version}</version>
<type>jar</type>
</dependency>
<!-- testing -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core-xml</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-xml</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-spring-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "dbb3d1f87ae91c87c715e6074be0b695",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 201,
"avg_line_length": 37.54929577464789,
"alnum_prop": 0.6436609152288072,
"repo_name": "pmoerenhout/camel",
"id": "71b6dc2a18e13a4c2923cadff74650de8dc979b9",
"size": "2666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/camel-univocity-parsers/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1518"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "47394"
},
{
"name": "HTML",
"bytes": "903016"
},
{
"name": "Java",
"bytes": "74647280"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323982"
},
{
"name": "Shell",
"bytes": "17120"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "288715"
}
],
"symlink_target": ""
} |
layout: press
title: "Syrian Activist Bassel Khartabil Reportedly Killed by Assad Regime"
source: "Al Bawaba"
link: https://www.albawaba.com/news/syrian-activist-bassel-khartabil-reportedly-killed-assad-regime-1004722
categories: [ press ]
tags: [ ]
---
| {
"content_hash": "7a033fed6a27c2a431ba4a9f911eb613",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 107,
"avg_line_length": 36.285714285714285,
"alnum_prop": 0.7755905511811023,
"repo_name": "Fabricatorz/freebassel.org",
"id": "027ba582ad9718c59c72101517d13ccf680b4a6d",
"size": "258",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "_posts/2017-08-02-albawaba.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12312"
},
{
"name": "HTML",
"bytes": "1241445"
},
{
"name": "JavaScript",
"bytes": "2432"
},
{
"name": "Ruby",
"bytes": "3568"
}
],
"symlink_target": ""
} |
#include <ModuleAnalyzerNodes.h>
#include <algorithm>
using namespace swift;
using namespace ide;
using namespace api;
namespace fs = llvm::sys::fs;
namespace path = llvm::sys::path;
namespace {
static StringRef getAttrName(DeclAttrKind Kind) {
switch (Kind) {
#define DECL_ATTR(NAME, CLASS, ...) \
case DAK_##CLASS: \
return DeclAttribute::isDeclModifier(DAK_##CLASS) ? #NAME : "@"#NAME;
#include "swift/AST/Attr.def"
case DAK_Count:
llvm_unreachable("unrecognized attribute kind.");
}
}
} // End of anonymous namespace.
struct swift::ide::api::SDKNodeInitInfo {
SDKContext &Ctx;
DeclKind DKind;
#define KEY_STRING(X, Y) StringRef X;
#include "swift/IDE/DigesterEnums.def"
#define KEY_BOOL(X, Y) bool X = false;
#include "swift/IDE/DigesterEnums.def"
#define KEY_UINT(X, Y) Optional<uint8_t> X;
#include "swift/IDE/DigesterEnums.def"
#define KEY_STRING_ARR(X, Y) std::vector<StringRef> X;
#include "swift/IDE/DigesterEnums.def"
ReferenceOwnership ReferenceOwnership = ReferenceOwnership::Strong;
std::vector<DeclAttrKind> DeclAttrs;
std::vector<TypeAttrKind> TypeAttrs;
SDKNodeInitInfo(SDKContext &Ctx) : Ctx(Ctx) {}
SDKNodeInitInfo(SDKContext &Ctx, Decl *D);
SDKNodeInitInfo(SDKContext &Ctx, ValueDecl *VD);
SDKNodeInitInfo(SDKContext &Ctx, OperatorDecl *D);
SDKNodeInitInfo(SDKContext &Ctx, ProtocolConformance *Conform);
SDKNodeInitInfo(SDKContext &Ctx, Type Ty, TypeInitInfo Info = TypeInitInfo());
SDKNode* createSDKNode(SDKNodeKind Kind);
};
SDKContext::SDKContext(CheckerOptions Opts): Diags(SourceMgr), Opts(Opts) {
#define ADD(NAME) BreakingAttrs.push_back({DeclAttrKind::DAK_##NAME, \
getAttrName(DeclAttrKind::DAK_##NAME)});
// Add attributes that both break ABI and API.
ADD(Final)
if (checkingABI()) {
// Add ABI-breaking-specific attributes.
ADD(ObjC)
ADD(FixedLayout)
ADD(Frozen)
ADD(Dynamic)
}
#undef ADD
}
void SDKNodeRoot::registerDescendant(SDKNode *D) {
// Operator doesn't have usr
if (isa<SDKNodeDeclOperator>(D))
return;
if (auto DD = dyn_cast<SDKNodeDecl>(D)) {
assert(!DD->getUsr().empty());
DescendantDeclTable[DD->getUsr()].insert(DD);
}
}
SDKNode::SDKNode(SDKNodeInitInfo Info, SDKNodeKind Kind): Ctx(Info.Ctx),
Name(Info.Name), PrintedName(Info.PrintedName), TheKind(unsigned(Kind)) {}
SDKNodeRoot::SDKNodeRoot(SDKNodeInitInfo Info): SDKNode(Info, SDKNodeKind::Root) {}
SDKNodeDecl::SDKNodeDecl(SDKNodeInitInfo Info, SDKNodeKind Kind)
: SDKNode(Info, Kind), DKind(Info.DKind), Usr(Info.Usr),
Location(Info.Location), ModuleName(Info.ModuleName),
DeclAttributes(Info.DeclAttrs), IsImplicit(Info.IsImplicit),
IsStatic(Info.IsStatic), IsDeprecated(Info.IsDeprecated),
IsProtocolReq(Info.IsProtocolReq),
IsOverriding(Info.IsOverriding),
IsOpen(Info.IsOpen),
IsInternal(Info.IsInternal),
ReferenceOwnership(uint8_t(Info.ReferenceOwnership)),
GenericSig(Info.GenericSig), FixedBinaryOrder(Info.FixedBinaryOrder) {}
SDKNodeType::SDKNodeType(SDKNodeInitInfo Info, SDKNodeKind Kind):
SDKNode(Info, Kind), TypeAttributes(Info.TypeAttrs),
HasDefaultArg(Info.HasDefaultArg),
ParamValueOwnership(Info.ParamValueOwnership) {}
SDKNodeTypeNominal::SDKNodeTypeNominal(SDKNodeInitInfo Info):
SDKNodeType(Info, SDKNodeKind::TypeNominal), USR(Info.Usr) {}
SDKNodeTypeFunc::SDKNodeTypeFunc(SDKNodeInitInfo Info):
SDKNodeType(Info, SDKNodeKind::TypeFunc) {}
SDKNodeTypeAlias::SDKNodeTypeAlias(SDKNodeInitInfo Info):
SDKNodeType(Info, SDKNodeKind::TypeAlias) {}
SDKNodeDeclType::SDKNodeDeclType(SDKNodeInitInfo Info):
SDKNodeDecl(Info, SDKNodeKind::DeclType), SuperclassUsr(Info.SuperclassUsr),
SuperclassNames(Info.SuperclassNames),
EnumRawTypeName(Info.EnumRawTypeName) {}
SDKNodeConformance::SDKNodeConformance(SDKNodeInitInfo Info):
SDKNode(Info, SDKNodeKind::Conformance) {}
SDKNodeTypeWitness::SDKNodeTypeWitness(SDKNodeInitInfo Info):
SDKNode(Info, SDKNodeKind::TypeWitness) {}
SDKNodeDeclOperator::SDKNodeDeclOperator(SDKNodeInitInfo Info):
SDKNodeDecl(Info, SDKNodeKind::DeclOperator) {}
SDKNodeDeclTypeAlias::SDKNodeDeclTypeAlias(SDKNodeInitInfo Info):
SDKNodeDecl(Info, SDKNodeKind::DeclTypeAlias) {}
SDKNodeDeclVar::SDKNodeDeclVar(SDKNodeInitInfo Info):
SDKNodeDecl(Info, SDKNodeKind::DeclVar), IsLet(Info.IsLet),
HasStorage(Info.HasStorage), HasDidSet(Info.HasDidset),
HasWillSet(Info.HasWillset) {}
SDKNodeDeclAbstractFunc::SDKNodeDeclAbstractFunc(SDKNodeInitInfo Info,
SDKNodeKind Kind): SDKNodeDecl(Info, Kind), IsThrowing(Info.IsThrowing),
SelfIndex(Info.SelfIndex) {}
SDKNodeDeclFunction::SDKNodeDeclFunction(SDKNodeInitInfo Info):
SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclFunction),
FuncSelfKind(Info.FuncSelfKind) {}
SDKNodeDeclConstructor::SDKNodeDeclConstructor(SDKNodeInitInfo Info):
SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclConstructor) {}
SDKNodeDeclGetter::SDKNodeDeclGetter(SDKNodeInitInfo Info):
SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclGetter) {}
SDKNodeDeclSetter::SDKNodeDeclSetter(SDKNodeInitInfo Info):
SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclSetter) {}
SDKNodeDeclAssociatedType::SDKNodeDeclAssociatedType(SDKNodeInitInfo Info):
SDKNodeDecl(Info, SDKNodeKind::DeclAssociatedType) {};
SDKNodeDeclSubscript::SDKNodeDeclSubscript(SDKNodeInitInfo Info):
SDKNodeDeclAbstractFunc(Info, SDKNodeKind::DeclSubscript),
HasSetter(Info.HasSetter), HasStorage(Info.HasStorage),
HasDidSet(Info.HasDidset), HasWillSet(Info.HasWillset) {}
StringRef SDKNodeDecl::getHeaderName() const {
if (Location.empty())
return StringRef();
return llvm::sys::path::filename(Location.split(":").first);
}
SDKNodeDeclGetter *SDKNodeDeclVar::getGetter() const {
if (getChildrenCount() > 1)
return cast<SDKNodeDeclGetter>(childAt(1));
return nullptr;
}
SDKNodeDeclSetter *SDKNodeDeclVar::getSetter() const {
if (getChildrenCount() > 2)
return cast<SDKNodeDeclSetter>(childAt(2));
return nullptr;
}
SDKNodeType *SDKNodeDeclVar::getType() const {
return cast<SDKNodeType>(childAt(0));
}
NodePtr UpdatedNodesMap::findUpdateCounterpart(const SDKNode *Node) const {
assert(Node->isAnnotatedAs(NodeAnnotation::Updated) && "Not update operation.");
auto FoundPair = std::find_if(MapImpl.begin(), MapImpl.end(),
[&](std::pair<NodePtr, NodePtr> Pair) {
return Pair.second == Node || Pair.first == Node;
});
assert(FoundPair != MapImpl.end() && "Cannot find update counterpart.");
return Node == FoundPair->first ? FoundPair->second : FoundPair->first;
}
#define NODE_KIND_RANGE(ID, FIRST, LAST) \
bool SDKNode##ID::classof(const SDKNode *N) { \
return N->getKind() >= SDKNodeKind::FIRST && \
N->getKind() <= SDKNodeKind::LAST; \
}
#include "swift/IDE/DigesterEnums.def"
unsigned SDKNode::getChildIndex(const SDKNode* Child) const {
auto It = std::find(Children.begin(), Children.end(), Child);
assert(It != Children.end() && "cannot find the child");
return It - Children.begin();
}
SDKNode* SDKNode::getOnlyChild() const {
assert(Children.size() == 1 && "more that one child.");
return *Children.begin();
}
SDKNodeRoot *SDKNode::getRootNode() const {
for (auto *Root = const_cast<SDKNode*>(this); ; Root = Root->getParent()) {
if (auto Result = dyn_cast<SDKNodeRoot>(Root))
return Result;
}
llvm_unreachable("Unhandled SDKNodeKind in switch.");
}
void SDKNode::addChild(SDKNode *Child) {
Child->Parent = this;
Children.push_back(Child);
if (auto *Root = dyn_cast<SDKNodeRoot>(this)) {
struct DeclCollector: public SDKNodeVisitor {
SDKNodeRoot &Root;
DeclCollector(SDKNodeRoot &Root): Root(Root) {}
void visit(NodePtr Node) override {
Root.registerDescendant(Node);
}
} Collector(*Root);
SDKNode::preorderVisit(Child, Collector);
}
}
NodePtr SDKNode::childAt(unsigned I) const {
assert(I < getChildrenCount());
return getChildren()[I];
}
void SDKNode::removeChild(NodePtr C) {
Children.erase(std::find(Children.begin(), Children.end(), C));
}
void SDKNode::annotate(NodeAnnotation Anno, StringRef Comment) {
assert(!Comment.empty());
if(isAnnotatedAs(Anno))
return;
annotate(Anno);
AnnotateComments[Anno] = Comment;
}
void SDKNode::removeAnnotate(NodeAnnotation Anno) {
assert(isAnnotatedAs(Anno));
Annotations.erase(Anno);
AnnotateComments.erase(Anno);
assert(!isAnnotatedAs(Anno));
assert(AnnotateComments.count(Anno) == 0);
}
StringRef SDKNode::getAnnotateComment(NodeAnnotation Anno) const {
return AnnotateComments.find(Anno)->second;
}
ArrayRef<NodeAnnotation> SDKNode::
getAnnotations(std::vector<NodeAnnotation> &Scratch) const {
for (auto Ann : Annotations)
Scratch.push_back(Ann);
return llvm::makeArrayRef(Scratch);
}
bool SDKNode::isAnnotatedAs(NodeAnnotation Anno) const {
return Annotations.find(Anno) != Annotations.end();;
}
void SDKNode::preorderVisit(NodePtr Root, SDKNodeVisitor &Visitor) {
Visitor.visit(Root);
Visitor.Ancestors.push_back(Root);
for (auto Child : Root->Children)
preorderVisit(Child, Visitor);
Visitor.Ancestors.pop_back();
}
void SDKNode::postorderVisit(NodePtr Root, SDKNodeVisitor &Visitor) {
Visitor.Ancestors.push_back(Root);
for (auto Child : Root->Children)
postorderVisit(Child, Visitor);
Visitor.Ancestors.pop_back();
Visitor.visit(Root);
}
SDKNodeVectorViewer::VectorIt
SDKNodeVectorViewer::getNext(VectorIt Start) {
for (auto It = Start; It != Collection.end(); ++ It)
if (Selector(*It))
return It;
return Collection.end();
}
SDKNodeVectorViewer::ViewerIterator&
SDKNodeVectorViewer::ViewerIterator::operator++() {
P = Viewer.getNext(P + 1);
return *this;
}
SDKNodeVectorViewer::ViewerIterator SDKNodeVectorViewer::begin() {
return ViewerIterator(*this, getNext(Collection.begin()));
}
SDKNodeVectorViewer::ViewerIterator SDKNodeVectorViewer::end() {
return ViewerIterator(*this, Collection.end());
}
KnownTypeKind SDKNodeType::getTypeKind() const {
#define KNOWN_TYPE(NAME) if (getName() == #NAME) return KnownTypeKind::NAME;
#include "swift/IDE/DigesterEnums.def"
return KnownTypeKind::Unknown;
}
ArrayRef<TypeAttrKind> SDKNodeType::getTypeAttributes() const {
return llvm::makeArrayRef(TypeAttributes.data(), TypeAttributes.size());
}
void SDKNodeType::addTypeAttribute(TypeAttrKind AttrKind) {
TypeAttributes.push_back(AttrKind);
}
bool SDKNodeType::hasTypeAttribute(TypeAttrKind DAKind) const {
return std::find(TypeAttributes.begin(), TypeAttributes.end(), DAKind) !=
TypeAttributes.end();
}
StringRef SDKNodeType::getParamValueOwnership() const {
return ParamValueOwnership.empty() ? "Default" : ParamValueOwnership;
}
StringRef SDKNodeType::getTypeRoleDescription() const {
assert(isTopLevelType());
auto P = getParent();
switch(P->getKind()) {
case SDKNodeKind::Root:
case SDKNodeKind::TypeNominal:
case SDKNodeKind::TypeFunc:
case SDKNodeKind::TypeAlias:
case SDKNodeKind::DeclType:
case SDKNodeKind::DeclOperator:
case SDKNodeKind::Conformance:
llvm_unreachable("Type Parent is wrong");
case SDKNodeKind::DeclFunction:
case SDKNodeKind::DeclConstructor:
case SDKNodeKind::DeclGetter:
case SDKNodeKind::DeclSetter:
case SDKNodeKind::DeclSubscript:
return SDKNodeDeclAbstractFunc::getTypeRoleDescription(Ctx,
P->getChildIndex(this));
case SDKNodeKind::DeclVar:
return "declared";
case SDKNodeKind::DeclTypeAlias:
return "underlying";
case SDKNodeKind::DeclAssociatedType:
return "default";
case SDKNodeKind::TypeWitness:
return "type witness type";
}
}
SDKNode *SDKNodeRoot::getInstance(SDKContext &Ctx) {
SDKNodeInitInfo Info(Ctx);
Info.Name = Ctx.buffer("TopLevel");
Info.PrintedName = Ctx.buffer("TopLevel");
return Info.createSDKNode(SDKNodeKind::Root);
}
StringRef SDKNodeDecl::getScreenInfo() const {
auto ModuleName = getModuleName();
auto HeaderName = getHeaderName();
auto &Ctx = getSDKContext();
llvm::SmallString<64> SS;
llvm::raw_svector_ostream OS(SS);
if (Ctx.getOpts().PrintModule)
OS << ModuleName;
if (!HeaderName.empty())
OS << "(" << HeaderName << ")";
if (!OS.str().empty())
OS << ": ";
OS << getDeclKind() << " " << getFullyQualifiedName();
return Ctx.buffer(OS.str());
}
void SDKNodeDecl::printFullyQualifiedName(llvm::raw_ostream &OS) const {
std::vector<NodePtr> Parent;
for (auto *P = getParent(); isa<SDKNodeDecl>(P); P = P->getParent())
Parent.push_back(P);
for (auto It = Parent.rbegin(); It != Parent.rend(); ++ It)
OS << (*It)->getPrintedName() << ".";
OS << getPrintedName();
}
StringRef SDKNodeDecl::getFullyQualifiedName() const {
llvm::SmallString<32> Buffer;
llvm::raw_svector_ostream OS(Buffer);
printFullyQualifiedName(OS);
return getSDKContext().buffer(OS.str());
}
bool SDKNodeDecl::hasDeclAttribute(DeclAttrKind DAKind) const {
return std::find(DeclAttributes.begin(), DeclAttributes.end(), DAKind) !=
DeclAttributes.end();
}
ArrayRef<DeclAttrKind> SDKNodeDecl::getDeclAttributes() const {
return llvm::makeArrayRef(DeclAttributes.data(), DeclAttributes.size());
}
bool SDKNodeDecl::hasAttributeChange(const SDKNodeDecl &Another) const {
std::set<DeclAttrKind> Left(getDeclAttributes().begin(),
getDeclAttributes().end());
std::set<DeclAttrKind> Right(Another.getDeclAttributes().begin(),
Another.getDeclAttributes().end());
return Left != Right;
}
bool SDKNodeType::hasAttributeChange(const SDKNodeType &Another) const {
std::set<TypeAttrKind> Left(getTypeAttributes().begin(),
getTypeAttributes().end());
std::set<TypeAttrKind> Right(Another.getTypeAttributes().begin(),
Another.getTypeAttributes().end());
return Left != Right;
}
SDKNodeDecl *SDKNodeType::getClosestParentDecl() const {
auto *Result = getParent();
for (; !isa<SDKNodeDecl>(Result); Result = Result->getParent());
return Result->getAs<SDKNodeDecl>();
}
void SDKNodeDeclType::addConformance(SDKNode *Conf) {
cast<SDKNodeConformance>(Conf)->TypeDecl = this;
Conformances.push_back(Conf);
}
SDKNodeType *SDKNodeTypeWitness::getUnderlyingType() const {
return getOnlyChild()->getAs<SDKNodeType>();
}
StringRef SDKNodeTypeWitness::getWitnessedTypeName() const {
return Ctx.buffer((llvm::Twine(getParent()->getAs<SDKNodeConformance>()->
getName()) + "." + getName()).str());
}
Optional<SDKNodeDeclType*> SDKNodeDeclType::getSuperclass() const {
if (SuperclassUsr.empty())
return None;
auto Descendants = getRootNode()->getDescendantsByUsr(SuperclassUsr);
if (!Descendants.empty()) {
return Descendants.front()->getAs<SDKNodeDeclType>();
}
return None;
}
/// Finding the node through all children, including the inheritted ones,
/// whose printed name matches with the given name.
Optional<SDKNodeDecl*>
SDKNodeDeclType::lookupChildByPrintedName(StringRef Name) const {
for (auto C : getChildren()) {
if (C->getPrintedName() == Name)
return C->getAs<SDKNodeDecl>();
}
// Finding from the inheritance chain.
if (auto Super = getSuperclass()) {
return (*Super)->lookupChildByPrintedName(Name);
}
return None;
}
SDKNodeType *SDKNodeDeclType::getRawValueType() const {
if (isConformingTo(KnownProtocolKind::RawRepresentable)) {
if (auto RV = lookupChildByPrintedName("rawValue")) {
return (*(*RV)->getChildBegin())->getAs<SDKNodeType>();
}
}
return nullptr;
}
bool SDKNodeDeclType::isConformingTo(KnownProtocolKind Kind) const {
switch (Kind) {
#define KNOWN_PROTOCOL(NAME) \
case KnownProtocolKind::NAME: \
return std::find_if(Conformances.begin(), Conformances.end(), \
[](SDKNode *Conf) { return Conf->getName() == #NAME; }) != \
Conformances.end();
#include "swift/IDE/DigesterEnums.def"
}
}
StringRef SDKNodeDeclAbstractFunc::getTypeRoleDescription(SDKContext &Ctx,
unsigned Index) {
if (Index == 0) {
return Ctx.buffer("return");
} else {
llvm::SmallString<4> Buffer;
Buffer += "parameter ";
Buffer += std::to_string(Index - 1);
return Ctx.buffer(Buffer.str());
}
}
#define NODE_KIND(X, NAME) \
bool SDKNode##X::classof(const SDKNode *N) { \
return N->getKind() == SDKNodeKind::X; \
}
#include "swift/IDE/DigesterEnums.def"
static Optional<KeyKind> parseKeyKind(StringRef Content) {
return llvm::StringSwitch<Optional<KeyKind>>(Content)
#define KEY(NAME) .Case(#NAME, KeyKind::KK_##NAME)
#include "swift/IDE/DigesterEnums.def"
.Default(None)
;
}
static StringRef getKeyContent(SDKContext &Ctx, KeyKind Kind) {
switch (Kind) {
#define KEY(NAME) case KeyKind::KK_##NAME: return Ctx.buffer(#NAME);
#include "swift/IDE/DigesterEnums.def"
}
llvm_unreachable("Unhandled KeyKind in switch.");
}
SDKNode* SDKNode::constructSDKNode(SDKContext &Ctx,
llvm::yaml::MappingNode *Node) {
static auto GetScalarString = [&](llvm::yaml::Node *N) -> StringRef {
auto WithQuote = cast<llvm::yaml::ScalarNode>(N)->getRawValue();
return WithQuote.substr(1, WithQuote.size() - 2);
};
static auto getAsInt = [&](llvm::yaml::Node *N) -> int {
return std::stoi(cast<llvm::yaml::ScalarNode>(N)->getRawValue());
};
static auto getAsBool = [&](llvm::yaml::Node *N) -> bool {
auto txt = cast<llvm::yaml::ScalarNode>(N)->getRawValue();
assert(txt.startswith("false") || txt.startswith("true"));
return txt.startswith("true");
};
SDKNodeKind Kind;
SDKNodeInitInfo Info(Ctx);
NodeVector Children;
NodeVector Conformances;
for (auto &Pair : *Node) {
auto keyString = GetScalarString(Pair.getKey());
if (auto keyKind = parseKeyKind(keyString)) {
switch(*keyKind) {
case KeyKind::KK_kind:
if (auto parsedKind = parseSDKNodeKind(GetScalarString(Pair.getValue()))) {
Kind = *parsedKind;
} else {
Ctx.diagnose(Pair.getValue(), diag::sdk_node_unrecognized_node_kind,
GetScalarString(Pair.getValue()));
}
break;
#define KEY_UINT(X, Y) \
case KeyKind::KK_##Y: Info.X = getAsInt(Pair.getValue()); break;
#include "swift/IDE/DigesterEnums.def"
#define KEY_STRING(X, Y) \
case KeyKind::KK_##Y: Info.X = GetScalarString(Pair.getValue()); break;
#include "swift/IDE/DigesterEnums.def"
#define KEY_BOOL(X, Y) case KeyKind::KK_##Y: Info.X = getAsBool(Pair.getValue()); break;
#include "swift/IDE/DigesterEnums.def"
case KeyKind::KK_children:
for (auto &Mapping : *cast<llvm::yaml::SequenceNode>(Pair.getValue())) {
Children.push_back(constructSDKNode(Ctx,
cast<llvm::yaml::MappingNode>(&Mapping)));
}
break;
case KeyKind::KK_conformances:
for (auto &Mapping : *cast<llvm::yaml::SequenceNode>(Pair.getValue())) {
Conformances.push_back(constructSDKNode(Ctx,
cast<llvm::yaml::MappingNode>(&Mapping)));
}
break;
#define KEY_STRING_ARR(X, Y) \
case KeyKind::KK_##Y: \
assert(Info.X.empty()); \
for (auto &Name : *cast<llvm::yaml::SequenceNode>(Pair.getValue())) { \
Info.X.push_back(GetScalarString(&Name)); \
} \
break;
#include "swift/IDE/DigesterEnums.def"
case KeyKind::KK_ownership:
Info.ReferenceOwnership =
swift::ReferenceOwnership(getAsInt(Pair.getValue()));
assert(Info.ReferenceOwnership != swift::ReferenceOwnership::Strong &&
"Strong is implied.");
break;
case KeyKind::KK_typeAttributes: {
auto *Seq = cast<llvm::yaml::SequenceNode>(Pair.getValue());
std::transform(Seq->begin(), Seq->end(),
std::back_inserter(Info.TypeAttrs),
[&](llvm::yaml::Node &N) {
auto Result = llvm::StringSwitch<TypeAttrKind>(GetScalarString(&N))
#define TYPE_ATTR(X) .Case(#X, TypeAttrKind::TAK_##X)
#include "swift/AST/Attr.def"
.Default(TypeAttrKind::TAK_Count);
if (Result == TAK_Count)
Ctx.diagnose(&N, diag::sdk_node_unrecognized_type_attr_kind,
GetScalarString(&N));
return Result;
});
break;
}
case KeyKind::KK_declAttributes: {
auto *Seq = cast<llvm::yaml::SequenceNode>(Pair.getValue());
std::transform(Seq->begin(), Seq->end(), std::back_inserter(Info.DeclAttrs),
[&](llvm::yaml::Node &N) {
auto Result = llvm::StringSwitch<DeclAttrKind>(GetScalarString(&N))
#define DECL_ATTR(_, NAME, ...) .Case(#NAME, DeclAttrKind::DAK_##NAME)
#include "swift/AST/Attr.def"
.Default(DeclAttrKind::DAK_Count);
if (Result == DAK_Count)
Ctx.diagnose(&N, diag::sdk_node_unrecognized_decl_attr_kind,
GetScalarString(&N));
return Result;
});
break;
}
case KeyKind::KK_declKind: {
auto dKind = llvm::StringSwitch<Optional<DeclKind>>(
GetScalarString(Pair.getValue()))
#define DECL(X, PARENT) .Case(#X, DeclKind::X)
#include "swift/AST/DeclNodes.def"
.Default(None);
if (dKind)
Info.DKind = *dKind;
else
Ctx.diagnose(Pair.getValue(), diag::sdk_node_unrecognized_decl_kind,
GetScalarString(Pair.getValue()));
break;
}
}
}
else {
Ctx.diagnose(Pair.getKey(), diag::sdk_node_unrecognized_key,
keyString);
Pair.skip();
}
};
SDKNode *Result = Info.createSDKNode(Kind);
for (auto C : Children) {
Result->addChild(C);
}
for (auto *Conf: Conformances) {
cast<SDKNodeDeclType>(Result)->addConformance(Conf);
}
return Result;
}
bool SDKNode::hasSameChildren(const SDKNode &Other) const {
if (Children.size() != Other.Children.size())
return false;
for (unsigned I = 0; I < Children.size(); ++ I) {
if (*Children[I] != *Other.Children[I])
return false;
}
return true;
}
void swift::ide::api::nodeSetDifference(ArrayRef<SDKNode*> Left,
ArrayRef<SDKNode*> Right,
NodeVector &LeftMinusRight,
NodeVector &RightMinusLeft) {
llvm::SmallPtrSet<NodePtr, 16> LeftToRemove;
llvm::SmallPtrSet<NodePtr, 16> RightToRemove;
for (auto LC: Left) {
for (auto RC: Right) {
if (!RightToRemove.count(RC) && *LC == *RC) {
LeftToRemove.insert(LC);
RightToRemove.insert(RC);
break;
}
}
}
std::for_each(Left.begin(), Left.end(), [&] (SDKNode *N) {
if (!LeftToRemove.count(N))
LeftMinusRight.push_back(N);
});
std::for_each(Right.begin(), Right.end(), [&] (SDKNode *N) {
if (!RightToRemove.count(N))
RightMinusLeft.push_back(N);
});
}
static bool hasSameContents(ArrayRef<SDKNode*> Left,
ArrayRef<SDKNode*> Right) {
NodeVector LeftMinusRight, RightMinusLeft;
nodeSetDifference(Left, Right, LeftMinusRight, RightMinusLeft);
return LeftMinusRight.empty() && RightMinusLeft.empty();
}
static bool hasSameParameterFlags(const SDKNodeType *Left, const SDKNodeType *Right) {
if (Left->hasDefaultArgument() != Right->hasDefaultArgument())
return false;
if (Left->getParamValueOwnership() != Right->getParamValueOwnership())
return false;
return true;
}
static bool isSDKNodeEqual(SDKContext &Ctx, const SDKNode &L, const SDKNode &R) {
auto *LeftAlias = dyn_cast<SDKNodeTypeAlias>(&L);
auto *RightAlias = dyn_cast<SDKNodeTypeAlias>(&R);
if (LeftAlias || RightAlias) {
auto Left = L.getAs<SDKNodeType>();
auto Right = R.getAs<SDKNodeType>();
// First compare the parameter attributes.
if (!hasSameParameterFlags(Left, Right))
return false;
// Comparing the underlying types if any of the inputs are alias.
Left = LeftAlias ? LeftAlias->getUnderlyingType() : Left;
Right = RightAlias ? RightAlias->getUnderlyingType() : Right;
return *Left == *Right;
}
if (L.getKind() != R.getKind())
return false;
switch(L.getKind()) {
case SDKNodeKind::TypeAlias:
llvm_unreachable("Should be handled above.");
case SDKNodeKind::TypeNominal:
case SDKNodeKind::TypeFunc: {
auto Left = L.getAs<SDKNodeType>();
auto Right = R.getAs<SDKNodeType>();
if (Left->hasAttributeChange(*Right))
return false;
if (!hasSameParameterFlags(Left, Right))
return false;
if (Left->getPrintedName() == Right->getPrintedName())
return true;
return Left->getName() == Right->getName() &&
Left->hasSameChildren(*Right);
}
case SDKNodeKind::DeclFunction: {
auto Left = L.getAs<SDKNodeDeclFunction>();
auto Right = R.getAs<SDKNodeDeclFunction>();
if (Left->getSelfAccessKind() != Right->getSelfAccessKind())
return false;
LLVM_FALLTHROUGH;
}
case SDKNodeKind::DeclConstructor:
case SDKNodeKind::DeclGetter:
case SDKNodeKind::DeclSetter: {
auto Left = L.getAs<SDKNodeDeclAbstractFunc>();
auto Right = R.getAs<SDKNodeDeclAbstractFunc>();
if (Left->isThrowing() ^ Right->isThrowing())
return false;
LLVM_FALLTHROUGH;
}
case SDKNodeKind::DeclVar: {
if (Ctx.checkingABI()) {
// If we're checking ABI, the definition order matters.
// If they're both members for fixed layout types, we never consider
// them equal because we need to check definition orders.
if (auto *LV = dyn_cast<SDKNodeDeclVar>(&L)) {
if (auto *RV = dyn_cast<SDKNodeDeclVar>(&R)) {
if (LV->isLet() != RV->isLet())
return false;
if (LV->hasStorage() != RV->hasStorage())
return false;
}
}
}
LLVM_FALLTHROUGH;
}
case SDKNodeKind::DeclType: {
auto *Left = dyn_cast<SDKNodeDeclType>(&L);
auto *Right = dyn_cast<SDKNodeDeclType>(&R);
if (Left && Right) {
if (!hasSameContents(Left->getConformances(), Right->getConformances())) {
return false;
}
if (Left->getSuperClassName() != Right->getSuperClassName()) {
return false;
}
if (Left->getDeclKind() != Right->getDeclKind()) {
return false;
}
}
LLVM_FALLTHROUGH;
}
case SDKNodeKind::DeclAssociatedType:
case SDKNodeKind::DeclSubscript: {
if (auto *Left = dyn_cast<SDKNodeDeclSubscript>(&L)) {
if (auto *Right = dyn_cast<SDKNodeDeclSubscript>(&R)) {
if (Left->hasSetter() != Right->hasSetter())
return false;
}
}
LLVM_FALLTHROUGH;
}
case SDKNodeKind::DeclOperator:
case SDKNodeKind::DeclTypeAlias: {
auto Left = L.getAs<SDKNodeDecl>();
auto Right = R.getAs<SDKNodeDecl>();
if (Left->isStatic() ^ Right->isStatic())
return false;
if (Left->getReferenceOwnership() != Right->getReferenceOwnership())
return false;
if (Left->hasAttributeChange(*Right))
return false;
if (Left->getGenericSignature() != Right->getGenericSignature())
return false;
if (Left->isOpen() != Right->isOpen())
return false;
if (Left->isInternal() != Right->isInternal())
return false;
if (Left->hasFixedBinaryOrder() != Right->hasFixedBinaryOrder())
return false;
if (Left->hasFixedBinaryOrder()) {
if (Left->getFixedBinaryOrder() != Right->getFixedBinaryOrder())
return false;
}
LLVM_FALLTHROUGH;
}
case SDKNodeKind::Conformance:
case SDKNodeKind::TypeWitness:
case SDKNodeKind::Root: {
return L.getPrintedName() == R.getPrintedName() &&
L.hasSameChildren(R);
}
}
llvm_unreachable("Unhandled SDKNodeKind in switch.");
}
bool SDKContext::isEqual(const SDKNode &Left, const SDKNode &Right) {
if (!EqualCache[&Left].count(&Right)) {
EqualCache[&Left][&Right] = isSDKNodeEqual(*this, Left, Right);
}
return EqualCache[&Left][&Right];
}
AccessLevel SDKContext::getAccessLevel(const ValueDecl *VD) const {
return checkingABI() ? VD->getEffectiveAccess() : VD->getFormalAccess();
}
bool SDKNode::operator==(const SDKNode &Other) const {
return Ctx.isEqual(*this, Other);
}
// The pretty printer of a tree of SDKNode
class SDKNodeDumpVisitor : public SDKNodeVisitor {
void dumpSpace(int Num) {
while (Num != 0) {
llvm::outs() << "\t";
Num --;
}
}
void visit(NodePtr Node) override {
dumpSpace(depth());
llvm::outs() << "[" << Node->getKind() << "]" << Node->getName() << "\n";
}
public:
SDKNodeDumpVisitor() {};
};
static StringRef getPrintedName(SDKContext &Ctx, Type Ty,
bool IsImplicitlyUnwrappedOptional = false) {
std::string S;
llvm::raw_string_ostream OS(S);
PrintOptions PO;
PO.SkipAttributes = true;
if (IsImplicitlyUnwrappedOptional)
PO.PrintOptionalAsImplicitlyUnwrapped = true;
Ty.print(OS, PO);
return Ctx.buffer(OS.str());
}
static StringRef getTypeName(SDKContext &Ctx, Type Ty,
bool IsImplicitlyUnwrappedOptional) {
if (Ty->getKind() == TypeKind::Paren) {
return Ctx.buffer("Paren");
}
if (Ty->isVoid()) {
return Ctx.buffer("Void");
}
if (auto *NAT = dyn_cast<NameAliasType>(Ty.getPointer())) {
return NAT->getDecl()->getNameStr();
}
if (Ty->getAnyNominal()) {
if (IsImplicitlyUnwrappedOptional) {
assert(Ty->getOptionalObjectType());
return StringRef("ImplicitlyUnwrappedOptional");
}
return Ty->getAnyNominal()->getNameStr();
}
#define TYPE(id, parent) \
if (Ty->getKind() == TypeKind::id) { \
return Ctx.buffer(#id); \
}
#include "swift/AST/TypeNodes.def"
llvm_unreachable("Unhandled type name.");
}
static StringRef calculateUsr(SDKContext &Ctx, ValueDecl *VD) {
llvm::SmallString<64> SS;
llvm::raw_svector_ostream OS(SS);
if (!ide::printDeclUSR(VD, OS)) {
return Ctx.buffer(SS.str());
}
return StringRef();
}
static StringRef calculateLocation(SDKContext &SDKCtx, Decl *D) {
if (SDKCtx.getOpts().AvoidLocation)
return StringRef();
auto &Ctx = D->getASTContext();
auto &Importer = static_cast<ClangImporter &>(*Ctx.getClangModuleLoader());
clang::SourceManager &SM = Importer.getClangPreprocessor().getSourceManager();
if (ClangNode CN = D->getClangNode()) {
clang::SourceLocation Loc = CN.getLocation();
Loc = SM.getFileLoc(Loc);
if (Loc.isValid())
return SDKCtx.buffer(Loc.printToString(SM));
}
return StringRef();
}
static bool isFunctionTypeNoEscape(Type Ty) {
if (auto *AFT = Ty->getAs<AnyFunctionType>()) {
return AFT->getExtInfo().isNoEscape();
}
return false;
}
/// Converts a DeclBaseName to a string by assigning special names strings and
/// escaping identifiers that would clash with these strings using '`'
static StringRef getEscapedName(DeclBaseName name) {
switch (name.getKind()) {
case DeclBaseName::Kind::Subscript:
return "subscript";
case DeclBaseName::Kind::Constructor:
return "init";
case DeclBaseName::Kind::Destructor:
return "deinit";
case DeclBaseName::Kind::Normal:
return llvm::StringSwitch<StringRef>(name.getIdentifier().str())
.Case("subscript", "`subscript`")
.Case("init", "`init`")
.Case("deinit", "`deinit`")
.Default(name.getIdentifier().str());
}
}
static StringRef getPrintedName(SDKContext &Ctx, ValueDecl *VD) {
llvm::SmallString<32> Result;
DeclName DM = VD->getFullName();
if (isa<AbstractFunctionDecl>(VD) || isa<SubscriptDecl>(VD)) {
if (DM.getBaseName().empty()) {
Result.append("_");
} else {
Result.append(getEscapedName(DM.getBaseName()));
}
Result.append("(");
for (auto Arg : DM.getArgumentNames()) {
Result.append(Arg.empty() ? "_" : Arg.str());
Result.append(":");
}
Result.append(")");
return Ctx.buffer(Result.str());
}
Result.append(getEscapedName(DM.getBaseName()));
return Ctx.buffer(Result.str());
}
static bool isFuncThrowing(ValueDecl *VD) {
if (auto AF = dyn_cast<AbstractFunctionDecl>(VD)) {
return AF->hasThrows();
}
return false;
}
static Optional<uint8_t> getSelfIndex(ValueDecl *VD) {
if (auto AF = dyn_cast<AbstractFunctionDecl>(VD)) {
if (AF->isImportAsInstanceMember())
return AF->getSelfIndex();
}
return None;
}
static ReferenceOwnership getReferenceOwnership(ValueDecl *VD) {
if (auto OA = VD->getAttrs().getAttribute<ReferenceOwnershipAttr>()) {
return OA->get();
}
return ReferenceOwnership::Strong;
}
// Get a requirement with all types canonicalized.
Requirement getCanonicalRequirement(Requirement &Req) {
auto kind = Req.getKind();
if (kind == RequirementKind::Layout) {
return Requirement(kind, Req.getFirstType()->getCanonicalType(),
Req.getLayoutConstraint());
} else {
return Requirement(kind, Req.getFirstType()->getCanonicalType(),
Req.getSecondType()->getCanonicalType());
}
}
static StringRef printGenericSignature(SDKContext &Ctx, Decl *D) {
llvm::SmallString<32> Result;
llvm::raw_svector_ostream OS(Result);
if (auto *PD = dyn_cast<ProtocolDecl>(D)) {
if (PD->getRequirementSignature().empty())
return StringRef();
OS << "<";
bool First = true;
for (auto Req: PD->getRequirementSignature()) {
if (!First) {
OS << ", ";
} else {
First = false;
}
if (Ctx.checkingABI())
getCanonicalRequirement(Req).print(OS, PrintOptions::printInterface());
else
Req.print(OS, PrintOptions::printInterface());
}
OS << ">";
return Ctx.buffer(OS.str());
}
if (auto *GC = D->getAsGenericContext()) {
if (auto *Sig = GC->getGenericSignature()) {
if (Ctx.checkingABI())
Sig->getCanonicalSignature()->print(OS);
else
Sig->print(OS);
return Ctx.buffer(OS.str());
}
}
return StringRef();
}
static Optional<uint8_t> getSimilarMemberCount(NominalTypeDecl *NTD,
ValueDecl *VD,
llvm::function_ref<bool(Decl*)> Check) {
if (!Check(VD))
return None;
auto Members = NTD->getMembers();
auto End = std::find(Members.begin(), Members.end(), VD);
assert(End != Members.end());
return std::count_if(Members.begin(), End, Check);
}
Optional<uint8_t> SDKContext::getFixedBinaryOrder(ValueDecl *VD) const {
// We don't need fixed binary order when checking API stability.
if (!checkingABI())
return None;
auto *NTD = dyn_cast_or_null<NominalTypeDecl>(VD->getDeclContext()->
getAsDecl());
if (!NTD || isa<ProtocolDecl>(NTD) || NTD->isResilient())
return None;
// The relative order of stored properties matters for non-resilient type.
auto isStored = [](Decl *M) {
if (auto *STD = dyn_cast<AbstractStorageDecl>(M)) {
return STD->hasStorage() && !STD->isStatic();
}
return false;
};
// The relative order of non-final instance functions matters for non-resilient
// class.
auto isNonfinalFunc = [](Decl *M) {
if (auto *FD = dyn_cast<FuncDecl>(M)) {
return !isa<AccessorDecl>(FD) && !FD->isFinal();
}
return false;
};
switch (NTD->getKind()) {
case DeclKind::Enum: {
return getSimilarMemberCount(NTD, VD, [](Decl *M) {
return isa<EnumElementDecl>(M);
});
}
case DeclKind::Struct: {
return getSimilarMemberCount(NTD, VD, isStored);
}
case DeclKind::Class: {
if (auto count = getSimilarMemberCount(NTD, VD, isStored)) {
return count;
} else {
return getSimilarMemberCount(NTD, VD, isNonfinalFunc);
}
}
default:
llvm_unreachable("bad nominal type kind.");
}
}
SDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, Type Ty, TypeInitInfo Info) :
Ctx(Ctx), Name(getTypeName(Ctx, Ty, Info.IsImplicitlyUnwrappedOptional)),
PrintedName(getPrintedName(Ctx, Ty, Info.IsImplicitlyUnwrappedOptional)),
ParamValueOwnership(Info.ValueOwnership),
HasDefaultArg(Info.hasDefaultArgument) {
if (isFunctionTypeNoEscape(Ty))
TypeAttrs.push_back(TypeAttrKind::TAK_noescape);
// If this is a nominal type, get its Usr.
if (auto *ND = Ty->getAnyNominal()) {
Usr = calculateUsr(Ctx, ND);
}
}
SDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, Decl *D):
Ctx(Ctx), DKind(D->getKind()),
Location(calculateLocation(Ctx, D)),
ModuleName(D->getModuleContext()->getName().str()),
GenericSig(printGenericSignature(Ctx, D)),
IsImplicit(D->isImplicit()),
IsDeprecated(D->getAttrs().getDeprecated(D->getASTContext())) {
// Capture all attributes.
auto AllAttrs = D->getAttrs();
std::transform(AllAttrs.begin(), AllAttrs.end(), std::back_inserter(DeclAttrs),
[](DeclAttribute *attr) { return attr->getKind(); });
}
SDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, OperatorDecl *OD):
SDKNodeInitInfo(Ctx, cast<Decl>(OD)) {
Name = OD->getName().str();
PrintedName = OD->getName().str();
}
SDKNodeInitInfo::SDKNodeInitInfo(SDKContext &Ctx, ValueDecl *VD)
: SDKNodeInitInfo(Ctx, cast<Decl>(VD)) {
Name = VD->hasName() ? getEscapedName(VD->getBaseName()) : Ctx.buffer("_");
PrintedName = getPrintedName(Ctx, VD);
Usr = calculateUsr(Ctx, VD);
IsThrowing = isFuncThrowing(VD);
IsStatic = VD->isStatic();
IsOverriding = VD->getOverriddenDecl();
IsProtocolReq = isa<ProtocolDecl>(VD->getDeclContext()) && VD->isProtocolRequirement();
IsOpen = Ctx.getAccessLevel(VD) == AccessLevel::Open;
IsInternal = Ctx.getAccessLevel(VD) < AccessLevel::Public;
SelfIndex = getSelfIndex(VD);
FixedBinaryOrder = Ctx.getFixedBinaryOrder(VD);
ReferenceOwnership = getReferenceOwnership(VD);
// Calculate usr for its super class.
if (auto *CD = dyn_cast_or_null<ClassDecl>(VD)) {
if (auto *Super = CD->getSuperclassDecl()) {
SuperclassUsr = calculateUsr(Ctx, Super);
for (auto T = CD->getSuperclass(); T; T = T->getSuperclass()) {
SuperclassNames.push_back(getPrintedName(Ctx, T->getCanonicalType()));
}
}
}
#define CASE(BASE, KIND, KEY) case BASE::KIND: KEY = #KIND; break;
if (auto *FD = dyn_cast<FuncDecl>(VD)) {
switch(FD->getSelfAccessKind()) {
CASE(SelfAccessKind, Mutating, FuncSelfKind)
CASE(SelfAccessKind, __Consuming, FuncSelfKind)
CASE(SelfAccessKind, NonMutating, FuncSelfKind)
}
}
#undef CASE
// Get enum raw type name if this is an enum.
if (auto *ED = dyn_cast<EnumDecl>(VD)) {
if (auto RT = ED->getRawType()) {
if (auto *D = RT->getNominalOrBoundGenericNominal()) {
EnumRawTypeName = D->getName().str();
}
}
}
if (auto *VAD = dyn_cast<VarDecl>(VD)) {
IsLet = VAD->isLet();
}
// Record whether a subscript has getter/setter.
if (auto *SD = dyn_cast<SubscriptDecl>(VD)) {
HasSetter = SD->getSetter();
}
if (auto *VAR = dyn_cast<AbstractStorageDecl>(VD)) {
HasStorage = VAR->hasStorage();
HasDidset = VAR->getDidSetFunc();
HasWillset = VAR->getWillSetFunc();
}
}
SDKNode *SDKNodeInitInfo::createSDKNode(SDKNodeKind Kind) {
switch(Kind) {
#define NODE_KIND(X, NAME) \
case SDKNodeKind::X: \
return static_cast<SDKNode*>(new (Ctx.allocator().Allocate<SDKNode##X>()) \
SDKNode##X(*this)); \
break;
#include "swift/IDE/DigesterEnums.def"
}
}
// Recursively construct a node that represents a type, for instance,
// representing the return value type of a function decl.
SDKNode *swift::ide::api::
SwiftDeclCollector::constructTypeNode(Type T, TypeInitInfo Info) {
if (Ctx.checkingABI()) {
T = T->getCanonicalType();
}
if (auto NAT = dyn_cast<NameAliasType>(T.getPointer())) {
SDKNode* Root = SDKNodeInitInfo(Ctx, T, Info).createSDKNode(SDKNodeKind::TypeAlias);
Root->addChild(constructTypeNode(NAT->getSinglyDesugaredType()));
return Root;
}
if (auto Fun = T->getAs<AnyFunctionType>()) {
SDKNode* Root = SDKNodeInitInfo(Ctx, T, Info).createSDKNode(SDKNodeKind::TypeFunc);
// Still, return type first
Root->addChild(constructTypeNode(Fun->getResult()));
auto Input = AnyFunctionType::composeInput(Fun->getASTContext(),
Fun->getParams(),
/*canonicalVararg=*/false);
Root->addChild(constructTypeNode(Input));
return Root;
}
SDKNode* Root = SDKNodeInitInfo(Ctx, T, Info).createSDKNode(SDKNodeKind::TypeNominal);
// Keep paren type as a stand-alone level.
if (auto *PT = dyn_cast<ParenType>(T.getPointer())) {
Root->addChild(constructTypeNode(PT->getSinglyDesugaredType()));
return Root;
}
// Handle the case where Type has sub-types.
if (auto BGT = T->getAs<BoundGenericType>()) {
for (auto Arg : BGT->getGenericArgs()) {
Root->addChild(constructTypeNode(Arg));
}
} else if (auto Tup = T->getAs<TupleType>()) {
for (auto Elt : Tup->getElementTypes())
Root->addChild(constructTypeNode(Elt));
} else if (auto MTT = T->getAs<AnyMetatypeType>()) {
Root->addChild(constructTypeNode(MTT->getInstanceType()));
} else if (auto ATT = T->getAs<ArchetypeType>()) {
for (auto Pro : ATT->getConformsTo()) {
Root->addChild(constructTypeNode(Pro->getDeclaredType()));
}
}
return Root;
}
std::vector<SDKNode*> swift::ide::api::
SwiftDeclCollector::createParameterNodes(ParameterList *PL) {
std::vector<SDKNode*> Result;
for (auto param: *PL) {
TypeInitInfo Info;
Info.IsImplicitlyUnwrappedOptional = param->getAttrs().
hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
Info.hasDefaultArgument = param->getDefaultArgumentKind() !=
DefaultArgumentKind::None;
switch (param->getValueOwnership()) {
#define CASE(KIND) case ValueOwnership::KIND: Info.ValueOwnership = #KIND; break;
CASE(Owned)
CASE(InOut)
CASE(Shared)
case ValueOwnership::Default: break;
#undef CASE
}
Result.push_back(constructTypeNode(param->getInterfaceType(), Info));
}
return Result;
}
// Construct a node for a function decl. The first child of the function decl
// is guaranteed to be the return value type of this function.
// We sometimes skip the first parameter because it can be metatype of dynamic
// this if the function is a member function.
SDKNode *swift::ide::api::
SwiftDeclCollector::constructFunctionNode(FuncDecl* FD,
SDKNodeKind Kind) {
auto Func = SDKNodeInitInfo(Ctx, FD).createSDKNode(Kind);
TypeInitInfo Info;
Info.IsImplicitlyUnwrappedOptional = FD->getAttrs().
hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
Func->addChild(constructTypeNode(FD->getResultInterfaceType(), Info));
for (auto *Node : createParameterNodes(FD->getParameters()))
Func->addChild(Node);
return Func;
}
SDKNode* swift::ide::api::
SwiftDeclCollector::constructInitNode(ConstructorDecl *CD) {
auto Func = SDKNodeInitInfo(Ctx, CD).createSDKNode(SDKNodeKind::DeclConstructor);
Func->addChild(constructTypeNode(CD->getResultInterfaceType()));
for (auto *Node : createParameterNodes(CD->getParameters()))
Func->addChild(Node);
return Func;
}
bool swift::ide::api::
SDKContext::shouldIgnore(Decl *D, const Decl* Parent) const {
// Exclude all clang nodes if we're comparing Swift decls specifically.
if (Opts.SwiftOnly && isFromClang(D)) {
return true;
}
if (checkingABI()) {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
// Private vars with fixed binary orders can have ABI-impact, so we should
// whitelist them if we're checking ABI.
if (getFixedBinaryOrder(VD).hasValue())
return false;
// Typealias should have no impact on ABI.
if (isa<TypeAliasDecl>(VD))
return true;
}
} else {
if (D->isPrivateStdlibDecl(false))
return true;
if (AvailableAttr::isUnavailable(D))
return true;
}
if (auto VD = dyn_cast<ValueDecl>(D)) {
if (VD->getBaseName().empty())
return true;
switch (getAccessLevel(VD)) {
case AccessLevel::Internal:
case AccessLevel::Private:
case AccessLevel::FilePrivate:
return true;
case AccessLevel::Public:
case AccessLevel::Open:
break;
}
}
if (auto *ClangD = D->getClangDecl()) {
if (isa<clang::ObjCIvarDecl>(ClangD))
return true;
if (isa<clang::FieldDecl>(ClangD))
return true;
if (ClangD->hasAttr<clang::SwiftPrivateAttr>())
return true;
// If this decl is a synthesized member from a conformed clang protocol, we
// should ignore this member to reduce redundancy.
if (Parent &&
!isa<swift::ProtocolDecl>(Parent) &&
isa<clang::ObjCProtocolDecl>(ClangD->getDeclContext()))
return true;
}
return false;
}
SDKNode *swift::ide::api::
SwiftDeclCollector::constructTypeDeclNode(NominalTypeDecl *NTD) {
auto TypeNode = SDKNodeInitInfo(Ctx, NTD).createSDKNode(SDKNodeKind::DeclType);
addConformancesToTypeDecl(cast<SDKNodeDeclType>(TypeNode), NTD);
addMembersToRoot(TypeNode, NTD);
for (auto Ext : NTD->getExtensions()) {
HandledExtensions.insert(Ext);
addMembersToRoot(TypeNode, Ext);
}
return TypeNode;
}
/// Create a node for stand-alone extensions. In the sdk dump, we don't have
/// a specific node for extension. Members in extensions are inlined to the
/// extended types. If the extended types are from a different module, we have to
/// synthesize this type node to include those extension members, since these
/// extension members are legit members of the module.
SDKNode *swift::ide::api::
SwiftDeclCollector::constructExternalExtensionNode(NominalTypeDecl *NTD,
ArrayRef<ExtensionDecl*> AllExts) {
auto *TypeNode = SDKNodeInitInfo(Ctx, NTD).createSDKNode(SDKNodeKind::DeclType);
addConformancesToTypeDecl(cast<SDKNodeDeclType>(TypeNode), NTD);
// The members of the extensions are the only members of this synthesized type.
for (auto *Ext: AllExts) {
HandledExtensions.insert(Ext);
addMembersToRoot(TypeNode, Ext);
}
return TypeNode;
}
SDKNode *swift::ide::api::
SwiftDeclCollector::constructVarNode(ValueDecl *VD) {
auto Var = SDKNodeInitInfo(Ctx, VD).createSDKNode(SDKNodeKind::DeclVar);
TypeInitInfo Info;
Info.IsImplicitlyUnwrappedOptional = VD->getAttrs().
hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
Var->addChild(constructTypeNode(VD->getInterfaceType(), Info));
if (auto VAD = dyn_cast<AbstractStorageDecl>(VD)) {
if (auto Getter = VAD->getGetter())
Var->addChild(constructFunctionNode(Getter, SDKNodeKind::DeclGetter));
if (auto Setter = VAD->getSetter()) {
if (Setter->getFormalAccess() > AccessLevel::Internal)
Var->addChild(constructFunctionNode(Setter, SDKNodeKind::DeclSetter));
}
}
return Var;
}
SDKNode *swift::ide::api::
SwiftDeclCollector::constructTypeAliasNode(TypeAliasDecl *TAD) {
auto Alias = SDKNodeInitInfo(Ctx, TAD).createSDKNode(SDKNodeKind::DeclTypeAlias);
Alias->addChild(constructTypeNode(TAD->getUnderlyingTypeLoc().getType()));
return Alias;
}
SDKNode *swift::ide::api::
SwiftDeclCollector::constructAssociatedTypeNode(AssociatedTypeDecl *ATD) {
auto Asso = SDKNodeInitInfo(Ctx, ATD).
createSDKNode(SDKNodeKind::DeclAssociatedType);
if (auto DT = ATD->getDefaultDefinitionType()) {
Asso->addChild(constructTypeNode(DT));
}
return Asso;
}
SDKNode *swift::ide::api::
SwiftDeclCollector::constructSubscriptDeclNode(SubscriptDecl *SD) {
auto Subs = SDKNodeInitInfo(Ctx, SD).createSDKNode(SDKNodeKind::DeclSubscript);
Subs->addChild(constructTypeNode(SD->getElementInterfaceType()));
for (auto *Node: createParameterNodes(SD->getIndices()))
Subs->addChild(Node);
return Subs;
}
void swift::ide::api::
SwiftDeclCollector::addMembersToRoot(SDKNode *Root, IterableDeclContext *Context) {
for (auto *Member : Context->getMembers()) {
if (Ctx.shouldIgnore(Member, Context->getDecl()))
continue;
if (auto Func = dyn_cast<FuncDecl>(Member)) {
Root->addChild(constructFunctionNode(Func, SDKNodeKind::DeclFunction));
} else if (auto CD = dyn_cast<ConstructorDecl>(Member)) {
Root->addChild(constructInitNode(CD));
} else if (auto VD = dyn_cast<VarDecl>(Member)) {
Root->addChild(constructVarNode(VD));
} else if (auto TAD = dyn_cast<TypeAliasDecl>(Member)) {
Root->addChild(constructTypeAliasNode(TAD));
} else if (auto EED = dyn_cast<EnumElementDecl>(Member)) {
Root->addChild(constructVarNode(EED));
} else if (auto NTD = dyn_cast<NominalTypeDecl>(Member)) {
Root->addChild(constructTypeDeclNode(NTD));
} else if (auto ATD = dyn_cast<AssociatedTypeDecl>(Member)) {
Root->addChild(constructAssociatedTypeNode(ATD));
} else if (auto SD = dyn_cast<SubscriptDecl>(Member)) {
Root->addChild(constructSubscriptDeclNode(SD));
} else if (isa<PatternBindingDecl>(Member)) {
// All containing variables should have been handled.
} else if (isa<DestructorDecl>(Member)) {
// deinit has no impact.
} else {
llvm_unreachable("unhandled member decl kind.");
}
}
}
SDKNode *swift::ide::api::
SwiftDeclCollector::constructTypeWitnessNode(AssociatedTypeDecl *Assoc,
Type Ty) {
auto *Witness = SDKNodeInitInfo(Ctx, Assoc).createSDKNode(SDKNodeKind::TypeWitness);
Witness->addChild(constructTypeNode(Ty));
return Witness;
}
SDKNode *swift::ide::api::
SwiftDeclCollector::constructConformanceNode(ProtocolConformance *Conform) {
if (Ctx.checkingABI())
Conform = Conform->getCanonicalConformance();
auto ConfNode = cast<SDKNodeConformance>(SDKNodeInitInfo(Ctx,
Conform->getProtocol()).createSDKNode(SDKNodeKind::Conformance));
Conform->forEachTypeWitness(nullptr,
[&](AssociatedTypeDecl *assoc, Type ty, TypeDecl *typeDecl) -> bool {
ConfNode->addChild(constructTypeWitnessNode(assoc, ty));
return false;
});
return ConfNode;
}
void swift::ide::api::
SwiftDeclCollector::addConformancesToTypeDecl(SDKNodeDeclType *Root,
NominalTypeDecl *NTD) {
for (auto &Conf: NTD->getAllConformances()) {
if (!Ctx.shouldIgnore(Conf->getProtocol()))
Root->addConformance(constructConformanceNode(Conf));
}
}
void SwiftDeclCollector::printTopLevelNames() {
for (auto &Node : RootNode->getChildren()) {
llvm::outs() << Node->getKind() << ": " << Node->getName() << '\n';
}
}
void SwiftDeclCollector::lookupVisibleDecls(ArrayRef<ModuleDecl *> Modules) {
for (auto M: Modules) {
llvm::SmallVector<Decl*, 512> Decls;
M->getDisplayDecls(Decls);
for (auto D : Decls) {
if (Ctx.shouldIgnore(D))
continue;
if (KnownDecls.count(D))
continue;
KnownDecls.insert(D);
if (auto VD = dyn_cast<ValueDecl>(D))
foundDecl(VD, DeclVisibilityKind::DynamicLookup);
else
processDecl(D);
}
}
// Now sort the macros before processing so that we can have deterministic
// output.
llvm::array_pod_sort(ClangMacros.begin(), ClangMacros.end(),
[](ValueDecl * const *lhs,
ValueDecl * const *rhs) -> int {
return (*lhs)->getBaseName().userFacingName().compare(
(*rhs)->getBaseName().userFacingName());
});
for (auto *VD : ClangMacros)
processValueDecl(VD);
// Collect extensions to types from other modules and synthesize type nodes
// for them.
llvm::MapVector<NominalTypeDecl*, llvm::SmallVector<ExtensionDecl*, 4>> ExtensionMap;
for (auto *D: KnownDecls) {
if (auto *Ext = dyn_cast<ExtensionDecl>(D)) {
if (HandledExtensions.find(Ext) == HandledExtensions.end()) {
ExtensionMap[Ext->getExtendedNominal()].push_back(Ext);
}
}
}
for (auto Pair: ExtensionMap) {
RootNode->addChild(constructExternalExtensionNode(Pair.first, Pair.second));
}
}
SDKNode *SwiftDeclCollector::constructOperatorDeclNode(OperatorDecl *OD) {
return SDKNodeInitInfo(Ctx, OD).createSDKNode(SDKNodeKind::DeclOperator);
}
void SwiftDeclCollector::processDecl(Decl *D) {
assert(!isa<ValueDecl>(D));
if (auto *OD = dyn_cast<OperatorDecl>(D)) {
RootNode->addChild(constructOperatorDeclNode(OD));
}
}
void SwiftDeclCollector::processValueDecl(ValueDecl *VD) {
if (auto FD = dyn_cast<FuncDecl>(VD)) {
RootNode->addChild(constructFunctionNode(FD, SDKNodeKind::DeclFunction));
} else if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) {
RootNode->addChild(constructTypeDeclNode(NTD));
} else if (auto VAD = dyn_cast<VarDecl>(VD)) {
RootNode->addChild(constructVarNode(VAD));
} else if (auto TAD = dyn_cast<TypeAliasDecl>(VD)) {
RootNode->addChild(constructTypeAliasNode(TAD));
} else {
llvm_unreachable("unhandled value decl");
}
}
void SwiftDeclCollector::foundDecl(ValueDecl *VD, DeclVisibilityKind Reason) {
if (VD->getClangMacro()) {
// Collect macros, we will sort them afterwards.
ClangMacros.push_back(VD);
return;
}
processValueDecl(VD);
}
void SDKNode::output(json::Output &out, KeyKind Key, bool Value) {
if (Value)
out.mapRequired(getKeyContent(Ctx, Key).data(), Value);
}
void SDKNode::output(json::Output &out, KeyKind Key, StringRef Value) {
if (!Value.empty())
out.mapRequired(getKeyContent(Ctx, Key).data(), Value);
}
void SDKNode::jsonize(json::Output &out) {
auto Kind = getKind();
out.mapRequired(getKeyContent(Ctx, KeyKind::KK_kind).data(), Kind);
output(out, KeyKind::KK_name, Name);
output(out, KeyKind::KK_printedName, PrintedName);
out.mapOptional(getKeyContent(Ctx, KeyKind::KK_children).data(), Children);
}
void SDKNodeDecl::jsonize(json::Output &out) {
SDKNode::jsonize(out);
out.mapRequired(getKeyContent(Ctx, KeyKind::KK_declKind).data(), DKind);
output(out, KeyKind::KK_usr, Usr);
output(out, KeyKind::KK_location, Location);
output(out, KeyKind::KK_moduleName, ModuleName);
output(out, KeyKind::KK_genericSig, GenericSig);
output(out, KeyKind::KK_static, IsStatic);
output(out, KeyKind::KK_deprecated,IsDeprecated);
output(out, KeyKind::KK_protocolReq, IsProtocolReq);
output(out, KeyKind::KK_overriding, IsOverriding);
output(out, KeyKind::KK_implicit, IsImplicit);
output(out, KeyKind::KK_isOpen, IsOpen);
output(out, KeyKind::KK_isInternal, IsInternal);
out.mapOptional(getKeyContent(Ctx, KeyKind::KK_declAttributes).data(), DeclAttributes);
out.mapOptional(getKeyContent(Ctx, KeyKind::KK_fixedbinaryorder).data(), FixedBinaryOrder);
// Strong reference is implied, no need for serialization.
if (getReferenceOwnership() != ReferenceOwnership::Strong) {
uint8_t Raw = uint8_t(getReferenceOwnership());
out.mapRequired(getKeyContent(Ctx, KeyKind::KK_ownership).data(), Raw);
}
}
void SDKNodeDeclAbstractFunc::jsonize(json::Output &out) {
SDKNodeDecl::jsonize(out);
output(out, KeyKind::KK_throwing, IsThrowing);
out.mapOptional(getKeyContent(Ctx, KeyKind::KK_selfIndex).data(), SelfIndex);
}
void SDKNodeDeclFunction::jsonize(json::Output &out) {
SDKNodeDeclAbstractFunc::jsonize(out);
output(out, KeyKind::KK_funcSelfKind, FuncSelfKind);
}
void SDKNodeDeclType::jsonize(json::Output &out) {
SDKNodeDecl::jsonize(out);
output(out, KeyKind::KK_superclassUsr, SuperclassUsr);
output(out, KeyKind::KK_enumRawTypeName, EnumRawTypeName);
out.mapOptional(getKeyContent(Ctx, KeyKind::KK_superclassNames).data(), SuperclassNames);
out.mapOptional(getKeyContent(Ctx, KeyKind::KK_conformances).data(), Conformances);
}
void SDKNodeType::jsonize(json::Output &out) {
SDKNode::jsonize(out);
out.mapOptional(getKeyContent(Ctx, KeyKind::KK_typeAttributes).data(), TypeAttributes);
output(out, KeyKind::KK_hasDefaultArg, HasDefaultArg);
output(out, KeyKind::KK_paramValueOwnership, ParamValueOwnership);
}
void SDKNodeTypeNominal::jsonize(json::Output &out) {
SDKNodeType::jsonize(out);
output(out, KeyKind::KK_usr, USR);
}
void SDKNodeDeclSubscript::jsonize(json::Output &out) {
SDKNodeDeclAbstractFunc::jsonize(out);
output(out, KeyKind::KK_hasSetter, HasSetter);
output(out, KeyKind::KK_hasStorage, HasStorage);
output(out, KeyKind::KK_hasDidset, HasDidSet);
output(out, KeyKind::KK_hasWillset, HasWillSet);
}
void SDKNodeDeclVar::jsonize(json::Output &out) {
SDKNodeDecl::jsonize(out);
output(out, KeyKind::KK_isLet, IsLet);
output(out, KeyKind::KK_hasStorage, HasStorage);
output(out, KeyKind::KK_hasDidset, HasDidSet);
output(out, KeyKind::KK_hasWillset, HasWillSet);
}
namespace swift {
namespace json {
// In the namespace of swift::json, we define several functions so that the
// JSON serializer will know how to interpret and dump types defined in this
// file.
template<>
struct ScalarEnumerationTraits<TypeAttrKind> {
static void enumeration(Output &out, TypeAttrKind &value) {
#define TYPE_ATTR(X) out.enumCase(value, #X, TypeAttrKind::TAK_##X);
#include "swift/AST/Attr.def"
}
};
template<>
struct ScalarEnumerationTraits<DeclAttrKind> {
static void enumeration(Output &out, DeclAttrKind &value) {
#define DECL_ATTR(_, Name, ...) out.enumCase(value, #Name, DeclAttrKind::DAK_##Name);
#include "swift/AST/Attr.def"
}
};
template<>
struct ScalarEnumerationTraits<DeclKind> {
static void enumeration(Output &out, DeclKind &value) {
#define DECL(X, PARENT) out.enumCase(value, #X, DeclKind::X);
#include "swift/AST/DeclNodes.def"
}
};
template<>
struct ObjectTraits<SDKNode *> {
static void mapping(Output &out, SDKNode *&value) {
value->jsonize(out);
}
};
template<>
struct ArrayTraits<ArrayRef<SDKNode*>> {
static size_t size(Output &out, ArrayRef<SDKNode *> &seq) {
return seq.size();
}
static SDKNode *&element(Output &, ArrayRef<SDKNode *> &seq,
size_t index) {
return const_cast<SDKNode *&>(seq[index]);
}
};
template<>
struct ArrayTraits<ArrayRef<TypeAttrKind>> {
static size_t size(Output &out, ArrayRef<TypeAttrKind> &seq) {
return seq.size();
}
static TypeAttrKind& element(Output &, ArrayRef<TypeAttrKind> &seq,
size_t index) {
return const_cast<TypeAttrKind&>(seq[index]);
}
};
template<>
struct ArrayTraits<ArrayRef<DeclAttrKind>> {
static size_t size(Output &out, ArrayRef<DeclAttrKind> &seq) {
return seq.size();
}
static DeclAttrKind& element(Output &, ArrayRef<DeclAttrKind> &seq,
size_t index) {
return const_cast<DeclAttrKind&>(seq[index]);
}
};
template<>
struct ArrayTraits<ArrayRef<StringRef>> {
static size_t size(Output &out, ArrayRef<StringRef> &seq) {
return seq.size();
}
static StringRef& element(Output &, ArrayRef<StringRef> &seq,
size_t index) {
return const_cast<StringRef&>(seq[index]);
}
};
} // namespace json
} // namespace swift
namespace {// Anonymous namespace.
// Serialize a forest of SDKNode trees to the given stream.
static void emitSDKNodeRoot(llvm::raw_ostream &os, SDKNode *&Root) {
json::Output yout(os);
yout << Root;
}
// Deserialize an SDKNode tree.
std::pair<std::unique_ptr<llvm::MemoryBuffer>, SDKNode*>
static parseJsonEmit(SDKContext &Ctx, StringRef FileName) {
namespace yaml = llvm::yaml;
// Load the input file.
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
vfs::getFileOrSTDIN(*Ctx.getSourceMgr().getFileSystem(), FileName);
if (!FileBufOrErr) {
llvm_unreachable("Failed to read JSON file");
}
StringRef Buffer = FileBufOrErr->get()->getBuffer();
yaml::Stream Stream(llvm::MemoryBufferRef(Buffer, FileName),
Ctx.getSourceMgr().getLLVMSourceMgr());
SDKNode *Result = nullptr;
for (auto DI = Stream.begin(); DI != Stream.end(); ++ DI) {
assert(DI != Stream.end() && "Failed to read a document");
yaml::Node *N = DI->getRoot();
assert(N && "Failed to find a root");
Result = SDKNode::constructSDKNode(Ctx, cast<yaml::MappingNode>(N));
if (Ctx.getDiags().hadAnyError())
exit(1);
}
return {std::move(FileBufOrErr.get()), Result};
}
static std::string getDumpFilePath(StringRef OutputDir, StringRef FileName) {
std::string Path = OutputDir;
Path += "/";
Path += FileName;
int Suffix = 0;
auto ConstructPath = [&]() {
return Path + (Suffix == 0 ? "" : std::to_string(Suffix)) + ".js";
};
for (; fs::exists(ConstructPath()); Suffix ++);
return ConstructPath();
}
} // End of anonymous namespace
// Construct all roots vector from a given file where a forest was
// previously dumped.
void SwiftDeclCollector::deSerialize(StringRef Filename) {
auto Pair = parseJsonEmit(Ctx, Filename);
OwnedBuffers.push_back(std::move(Pair.first));
RootNode = std::move(Pair.second);
}
// Serialize the content of all roots to a given file using JSON format.
void SwiftDeclCollector::serialize(StringRef Filename) {
std::error_code EC;
llvm::raw_fd_ostream fs(Filename, EC, llvm::sys::fs::F_None);
emitSDKNodeRoot(fs, RootNode);
}
int swift::ide::api::dumpSwiftModules(const CompilerInvocation &InitInvok,
const llvm::StringSet<> &ModuleNames,
StringRef OutputDir,
const std::vector<std::string> PrintApis,
CheckerOptions Opts) {
if (!fs::exists(OutputDir)) {
llvm::errs() << "Output directory '" << OutputDir << "' does not exist.\n";
return 1;
}
std::vector<ModuleDecl*> Modules;
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation)) {
llvm::errs() << "Failed to setup the compiler instance\n";
return 1;
}
auto &Context = CI.getASTContext();
for (auto &Entry : ModuleNames) {
StringRef Name = Entry.first();
if (Opts.Verbose)
llvm::errs() << "Loading module: " << Name << "...\n";
auto *M = Context.getModuleByName(Name);
if (!M) {
if (Opts.Verbose)
llvm::errs() << "Failed to load module: " << Name << '\n';
if (Opts.AbortOnModuleLoadFailure)
return 1;
}
Modules.push_back(M);
}
PrintingDiagnosticConsumer PDC;
SDKContext Ctx(Opts);
Ctx.getDiags().addConsumer(PDC);
for (auto M : Modules) {
SwiftDeclCollector Collector(Ctx);
SmallVector<Decl*, 256> Decls;
M->getTopLevelDecls(Decls);
for (auto D : Decls) {
if (auto VD = dyn_cast<ValueDecl>(D))
Collector.foundDecl(VD, DeclVisibilityKind::VisibleAtTopLevel);
}
std::string Path = getDumpFilePath(OutputDir, M->getName().str());
Collector.serialize(Path);
if (Opts.Verbose)
llvm::errs() << "Dumped to "<< Path << "\n";
}
return 0;
}
int swift::ide::api::dumpSDKContent(const CompilerInvocation &InitInvok,
const llvm::StringSet<> &ModuleNames,
StringRef OutputFile, CheckerOptions Opts) {
CompilerInvocation Invocation(InitInvok);
CompilerInstance CI;
// Display diagnostics to stderr.
PrintingDiagnosticConsumer PrintDiags;
CI.addDiagnosticConsumer(&PrintDiags);
if (CI.setup(Invocation)) {
llvm::errs() << "Failed to setup the compiler instance\n";
return 1;
}
auto &Ctx = CI.getASTContext();
// Load standard library so that Clang importer can use it.
auto *Stdlib = Ctx.getStdlibModule(/*loadIfAbsent=*/true);
if (!Stdlib) {
llvm::errs() << "Failed to load Swift stdlib\n";
return 1;
}
std::vector<ModuleDecl *> Modules;
for (auto &Entry : ModuleNames) {
StringRef Name = Entry.getKey();
if (Opts.Verbose)
llvm::errs() << "Loading module: " << Name << "...\n";
auto *M = Ctx.getModuleByName(Name);
if (!M) {
llvm::errs() << "Failed to load module: " << Name << '\n';
if (Opts.AbortOnModuleLoadFailure)
return 1;
} else {
Modules.push_back(M);
}
}
if (Opts.Verbose)
llvm::errs() << "Scanning symbols...\n";
SDKContext SDKCtx(Opts);
SwiftDeclCollector Collector(SDKCtx);
Collector.lookupVisibleDecls(Modules);
if (Opts.Verbose)
llvm::errs() << "Dumping SDK...\n";
Collector.serialize(OutputFile);
if (Opts.Verbose)
llvm::errs() << "Dumped to "<< OutputFile << "\n";
return 0;
}
int swift::ide::api::deserializeSDKDump(StringRef dumpPath, StringRef OutputPath,
CheckerOptions Opts) {
std::error_code EC;
llvm::raw_fd_ostream FS(OutputPath, EC, llvm::sys::fs::F_None);
if (!fs::exists(dumpPath)) {
llvm::errs() << dumpPath << " does not exist\n";
return 1;
}
PrintingDiagnosticConsumer PDC;
SDKContext Ctx(Opts);
Ctx.getDiags().addConsumer(PDC);
SwiftDeclCollector Collector(Ctx);
Collector.deSerialize(dumpPath);
Collector.serialize(OutputPath);
return 0;
}
int swift::ide::api::findDeclUsr(StringRef dumpPath, CheckerOptions Opts) {
std::error_code EC;
if (!fs::exists(dumpPath)) {
llvm::errs() << dumpPath << " does not exist\n";
return 1;
}
PrintingDiagnosticConsumer PDC;
SDKContext Ctx(Opts);
Ctx.getDiags().addConsumer(PDC);
SwiftDeclCollector Collector(Ctx);
Collector.deSerialize(dumpPath);
struct FinderByLocation: SDKNodeVisitor {
StringRef Location;
FinderByLocation(StringRef Location): Location(Location) {}
void visit(SDKNode* Node) override {
if (auto *D = dyn_cast<SDKNodeDecl>(Node)) {
if (D->getLocation().find(Location) != StringRef::npos &&
!D->getUsr().empty()) {
llvm::outs() << D->getFullyQualifiedName() << ": " << D->getUsr() << "\n";
}
}
}
};
if (!Opts.LocationFilter.empty()) {
FinderByLocation Finder(Opts.LocationFilter);
Collector.visitAllRoots(Finder);
}
return 0;
}
| {
"content_hash": "828b32c8831f72a7dfaae8ccccbde79a",
"timestamp": "",
"source": "github",
"line_count": 1963,
"max_line_length": 93,
"avg_line_length": 34.256749872643915,
"alnum_prop": 0.6592213663266216,
"repo_name": "alblue/swift",
"id": "f084e9f42356e2987a285e8d92b0b4d80841191b",
"size": "67246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/swift-api-digester/ModuleAnalyzerNodes.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "34"
},
{
"name": "C",
"bytes": "206200"
},
{
"name": "C++",
"bytes": "30858398"
},
{
"name": "CMake",
"bytes": "470534"
},
{
"name": "D",
"bytes": "1107"
},
{
"name": "DTrace",
"bytes": "2438"
},
{
"name": "Emacs Lisp",
"bytes": "57216"
},
{
"name": "LLVM",
"bytes": "70800"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "395731"
},
{
"name": "Objective-C++",
"bytes": "243585"
},
{
"name": "Perl",
"bytes": "2211"
},
{
"name": "Python",
"bytes": "1366983"
},
{
"name": "Ruby",
"bytes": "2091"
},
{
"name": "Shell",
"bytes": "215345"
},
{
"name": "Swift",
"bytes": "25268413"
},
{
"name": "Vim script",
"bytes": "16250"
}
],
"symlink_target": ""
} |
package org.opencb.cellbase.lib.impl.core;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.opencb.cellbase.core.api.query.AbstractQuery;
import org.opencb.cellbase.core.api.query.ProjectionQueryOptions;
import org.opencb.cellbase.core.models.DataRelease;
import org.opencb.cellbase.core.result.CellBaseDataResult;
import org.opencb.cellbase.lib.iterator.CellBaseIterator;
import org.opencb.commons.datastore.core.DataResult;
import org.opencb.commons.datastore.core.FacetField;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.mongodb.MongoDBCollection;
import org.opencb.commons.datastore.mongodb.MongoDataStore;
import java.util.List;
public class ReleaseMongoDBAdaptor extends MongoDBAdaptor implements CellBaseCoreDBAdaptor {
private MongoDBCollection mongoDBCollection;
private final String DATA_RELEASE_COLLECTION_NAME = "data_release";
public ReleaseMongoDBAdaptor(MongoDataStore mongoDataStore) {
super(mongoDataStore);
init();
}
private void init() {
logger.debug("ReleaseMongoDBAdaptor: in 'constructor'");
mongoDBCollection = mongoDataStore.getCollection(DATA_RELEASE_COLLECTION_NAME);
}
public CellBaseDataResult<DataRelease> getAll() {
return new CellBaseDataResult<>(mongoDBCollection.find(new BsonDocument(), null, DataRelease.class, new QueryOptions()));
}
public DataResult insert(DataRelease dataRelease) throws JsonProcessingException {
Document document = Document.parse(new ObjectMapper().writeValueAsString(dataRelease));
return mongoDBCollection.insert(document, QueryOptions.empty());
}
public void update(int release, String field, Object value) {
Bson query = Filters.eq("release", release);
Document projection = new Document(field, true);
Bson update = Updates.set(field, value);
QueryOptions queryOptions = new QueryOptions("replace", true);
mongoDBCollection.findAndUpdate(query, projection, null, update, queryOptions);
}
@Override
public CellBaseDataResult query(AbstractQuery query) {
return null;
}
@Override
public List<CellBaseDataResult> query(List queries) {
return null;
}
@Override
public CellBaseIterator iterator(AbstractQuery query) {
return null;
}
@Override
public CellBaseDataResult<Long> count(AbstractQuery query) {
return null;
}
@Override
public CellBaseDataResult<String> distinct(AbstractQuery query) {
return null;
}
@Override
public List<CellBaseDataResult> info(List ids, ProjectionQueryOptions queryOptions, int dataRelease) {
return null;
}
@Override
public CellBaseDataResult<FacetField> aggregationStats(AbstractQuery query) {
return null;
}
@Override
public CellBaseDataResult groupBy(AbstractQuery query) {
return null;
}
}
| {
"content_hash": "792b70855c81bcc3d4ecf52cc3f4bee6",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 129,
"avg_line_length": 32.63265306122449,
"alnum_prop": 0.7410881801125704,
"repo_name": "opencb/cellbase",
"id": "f91ce65495b31844c88bc435e9eba7554f190f55",
"size": "3792",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "cellbase-lib/src/main/java/org/opencb/cellbase/lib/impl/core/ReleaseMongoDBAdaptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "92703"
},
{
"name": "Dockerfile",
"bytes": "4569"
},
{
"name": "HTML",
"bytes": "10388"
},
{
"name": "Java",
"bytes": "3470698"
},
{
"name": "JavaScript",
"bytes": "2458859"
},
{
"name": "Jupyter Notebook",
"bytes": "15424"
},
{
"name": "Mustache",
"bytes": "3207"
},
{
"name": "Perl",
"bytes": "107545"
},
{
"name": "Python",
"bytes": "173110"
},
{
"name": "R",
"bytes": "50286"
},
{
"name": "Shell",
"bytes": "12696"
},
{
"name": "Smarty",
"bytes": "396"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
namespace Pook.SlackAPI
{
public class QueueHandler
{
public static QueueHandler<T> Start<T>(Func<T, Task> handler, CancellationToken? token = null, int maxDegreeOfParallelism = 5)
{
var q = new QueueHandler<T>(handler, token, maxDegreeOfParallelism);
q.Start();
return q;
}
public static QueueHandler<T> StartWithAction<T>(Action<T> handler, CancellationToken? token = null, int maxDegreeOfParallelism = 5)
{
var q = new QueueHandler<T>(x => { handler(x); return Task.FromResult(0); }, token, maxDegreeOfParallelism);
q.Start();
return q;
}
}
public class QueueHandler<T>
{
public QueueHandler(Func<T, Task> handler, CancellationToken? token = null, int maxDegreeOfParallelism = 5)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
this.handler = handler;
this.token = token ?? CancellationToken.None;
this.maxDegreeOfParallelism = maxDegreeOfParallelism;
}
private readonly Func<T, Task> handler;
private readonly CancellationToken token;
private readonly int maxDegreeOfParallelism;
private readonly BlockingCollection<T> queue = new BlockingCollection<T>();
public void Start()
{
Task.Factory
.StartNew(Loop, token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(t =>
{
if (t.Exception != null)
Trace.TraceError(t.Exception.Message);
Trace.TraceInformation("HandlerLoop finished");
}, CancellationToken.None);
}
private void Loop()
{
var action = new ActionBlock<T>(
async x => await handler(x),
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism }
);
foreach (var item in queue.GetConsumingEnumerable())
action.Post(item);
action.Complete();
}
public void Add(T item)
{
queue.Add(item, token);
}
}
} | {
"content_hash": "e2713e7e059d0312fde258259c2335d0",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 134,
"avg_line_length": 29.17391304347826,
"alnum_prop": 0.7153502235469449,
"repo_name": "AndyPook/Slack",
"id": "b06cf2b5c9d0ce32e4e8af6f582749b1bfccfa47",
"size": "2013",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SlackAPI/QueueHandler.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "92893"
}
],
"symlink_target": ""
} |
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeProcessHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{
public SafeProcessHandle(System.IntPtr existingHandle, bool ownsHandle) : base(default(bool)) { }
public override bool IsInvalid { get { throw null; } }
protected override bool ReleaseHandle() { throw null; }
}
}
namespace System.Diagnostics
{
public partial class DataReceivedEventArgs : System.EventArgs
{
internal DataReceivedEventArgs() { }
public string Data { get { throw null; } }
}
public delegate void DataReceivedEventHandler(object sender, System.Diagnostics.DataReceivedEventArgs e);
public partial class Process : System.ComponentModel.Component
{
public IntPtr Handle { get { throw null; } }
public int HandleCount { get { throw null; } }
public IntPtr MainWindowHandle { get { throw null; } }
public string MainWindowTitle { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int NonpagedSystemMemorySize { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedMemorySize { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedSystemMemorySize { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakPagedMemorySize { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakVirtualMemorySize { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakWorkingSet { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PrivateMemorySize { get { throw null; } }
public bool Responding { get { throw null; } }
public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get { throw null; } set { } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int VirtualMemorySize { get { throw null; } }
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int WorkingSet { get { throw null; } }
public void Close() { }
public bool CloseMainWindow() { throw null; }
protected override void Dispose(bool disposing) { }
public bool WaitForInputIdle() { throw null; }
public bool WaitForInputIdle(int milliseconds) { throw null; }
public override string ToString() { throw null; }
public Process() { }
public int BasePriority { get { throw null; } }
[System.ComponentModel.DefaultValueAttribute(false)]
public bool EnableRaisingEvents { get { throw null; } set { } }
public int ExitCode { get { throw null; } }
public System.DateTime ExitTime { get { throw null; } }
public bool HasExited { get { throw null; } }
public int Id { get { throw null; } }
public string MachineName { get { throw null; } }
public System.Diagnostics.ProcessModule MainModule { get { throw null; } }
public System.IntPtr MaxWorkingSet { get { throw null; } set { } }
public System.IntPtr MinWorkingSet { get { throw null; } set { } }
public System.Diagnostics.ProcessModuleCollection Modules { get { throw null; } }
public long NonpagedSystemMemorySize64 { get { throw null; } }
public long PagedMemorySize64 { get { throw null; } }
public long PagedSystemMemorySize64 { get { throw null; } }
public long PeakPagedMemorySize64 { get { throw null; } }
public long PeakVirtualMemorySize64 { get { throw null; } }
public long PeakWorkingSet64 { get { throw null; } }
public bool PriorityBoostEnabled { get { throw null; } set { } }
public System.Diagnostics.ProcessPriorityClass PriorityClass { get { throw null; } set { } }
public long PrivateMemorySize64 { get { throw null; } }
public System.TimeSpan PrivilegedProcessorTime { get { throw null; } }
public string ProcessName { get { throw null; } }
public System.IntPtr ProcessorAffinity { get { throw null; } set { } }
public Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle { get { throw null; } }
public int SessionId { get { throw null; } }
public System.IO.StreamReader StandardError { get { throw null; } }
public System.IO.StreamWriter StandardInput { get { throw null; } }
public System.IO.StreamReader StandardOutput { get { throw null; } }
public System.Diagnostics.ProcessStartInfo StartInfo { get { throw null; } set { } }
public System.DateTime StartTime { get { throw null; } }
public System.Diagnostics.ProcessThreadCollection Threads { get { throw null; } }
public System.TimeSpan TotalProcessorTime { get { throw null; } }
public System.TimeSpan UserProcessorTime { get { throw null; } }
public long VirtualMemorySize64 { get { throw null; } }
public long WorkingSet64 { get { throw null; } }
public event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived { add { } remove { } }
public event System.EventHandler Exited { add { } remove { } }
public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived { add { } remove { } }
public void BeginErrorReadLine() { }
public void BeginOutputReadLine() { }
public void CancelErrorRead() { }
public void CancelOutputRead() { }
public static void EnterDebugMode() { }
public static System.Diagnostics.Process GetCurrentProcess() { throw null; }
public static System.Diagnostics.Process GetProcessById(int processId) { throw null; }
public static System.Diagnostics.Process GetProcessById(int processId, string machineName) { throw null; }
public static System.Diagnostics.Process[] GetProcesses() { throw null; }
public static System.Diagnostics.Process[] GetProcesses(string machineName) { throw null; }
public static System.Diagnostics.Process[] GetProcessesByName(string processName) { throw null; }
public static System.Diagnostics.Process[] GetProcessesByName(string processName, string machineName) { throw null; }
public void Kill() { }
public static void LeaveDebugMode() { }
protected void OnExited() { }
public void Refresh() { }
public bool Start() { throw null; }
public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo startInfo) { throw null; }
public static System.Diagnostics.Process Start(string fileName) { throw null; }
public static System.Diagnostics.Process Start(string fileName, string arguments) { throw null; }
[System.CLSCompliant(false)]
public static System.Diagnostics.Process Start(string fileName, string userName, System.Security.SecureString password, string domain) { throw null; }
[System.CLSCompliant(false)]
public static System.Diagnostics.Process Start(string fileName, string arguments, string userName, System.Security.SecureString password, string domain) { throw null; }
public void WaitForExit() { }
public bool WaitForExit(int milliseconds) { throw null; }
}
public partial class ProcessModule : System.ComponentModel.Component
{
internal ProcessModule() { }
public System.IntPtr BaseAddress { get { throw null; } }
public System.IntPtr EntryPointAddress { get { throw null; } }
public string FileName { get { throw null; } }
public int ModuleMemorySize { get { throw null; } }
public string ModuleName { get { throw null; } }
public FileVersionInfo FileVersionInfo { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class ProcessModuleCollection : System.Collections.ReadOnlyCollectionBase
{
protected ProcessModuleCollection() { }
public ProcessModuleCollection(System.Diagnostics.ProcessModule[] processModules) { }
public System.Diagnostics.ProcessModule this[int index] { get { throw null; } }
public bool Contains(System.Diagnostics.ProcessModule module) { throw null; }
public void CopyTo(System.Diagnostics.ProcessModule[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessModule module) { throw null; }
}
public enum ProcessPriorityClass
{
AboveNormal = 32768,
BelowNormal = 16384,
High = 128,
Idle = 64,
Normal = 32,
RealTime = 256,
}
public sealed partial class ProcessStartInfo
{
public ProcessStartInfo() { }
public ProcessStartInfo(string fileName) { }
public ProcessStartInfo(string fileName, string arguments) { }
public string Arguments { get { throw null; } set { } }
public System.Collections.ObjectModel.Collection<string> ArgumentList { get { throw null; } }
public bool CreateNoWindow { get { throw null; } set { } }
public string Domain { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public System.Collections.Generic.IDictionary<string, string> Environment { get { throw null; } }
public string FileName { get { throw null; } set { } }
public bool LoadUserProfile { get { throw null; } set { } }
[System.CLSCompliant(false)]
public System.Security.SecureString Password { get { throw null; } set { } }
public bool RedirectStandardError { get { throw null; } set { } }
public bool RedirectStandardInput { get { throw null; } set { } }
public bool RedirectStandardOutput { get { throw null; } set { } }
public System.Text.Encoding StandardErrorEncoding { get { throw null; } set { } }
public System.Text.Encoding StandardInputEncoding { get { throw null; } set { } }
public System.Text.Encoding StandardOutputEncoding { get { throw null; } set { } }
public string UserName { get { throw null; } set { } }
public bool UseShellExecute { get { throw null; } set { } }
public string WorkingDirectory { get { throw null; } set { } }
public bool ErrorDialog { get { throw null; } set { } }
public System.IntPtr ErrorDialogParentHandle { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public string Verb { get { throw null; } set { } }
public string[] Verbs { get { throw null; } }
[System.ComponentModel.DefaultValueAttribute(null)]
public System.Diagnostics.ProcessWindowStyle WindowStyle { get { throw null ; } set { } }
public System.Collections.Specialized.StringDictionary EnvironmentVariables { get { throw null; } }
}
public partial class ProcessThread : System.ComponentModel.Component
{
internal ProcessThread() { }
public int BasePriority { get { throw null; } }
public int CurrentPriority { get { throw null; } }
public int Id { get { throw null; } }
public int IdealProcessor { set { } }
public bool PriorityBoostEnabled { get { throw null; } set { } }
public System.Diagnostics.ThreadPriorityLevel PriorityLevel { get { throw null; } set { } }
public System.TimeSpan PrivilegedProcessorTime { get { throw null; } }
public System.IntPtr ProcessorAffinity { set { } }
public System.IntPtr StartAddress { get { throw null; } }
public System.DateTime StartTime { get { throw null; } }
public System.Diagnostics.ThreadState ThreadState { get { throw null; } }
public System.TimeSpan TotalProcessorTime { get { throw null; } }
public System.TimeSpan UserProcessorTime { get { throw null; } }
public System.Diagnostics.ThreadWaitReason WaitReason { get { throw null; } }
public void ResetIdealProcessor() { }
}
public partial class ProcessThreadCollection : System.Collections.ReadOnlyCollectionBase
{
protected ProcessThreadCollection() { }
public ProcessThreadCollection(System.Diagnostics.ProcessThread[] processThreads) { }
public System.Diagnostics.ProcessThread this[int index] { get { throw null; } }
public int Add(System.Diagnostics.ProcessThread thread) { throw null; }
public bool Contains(System.Diagnostics.ProcessThread thread) { throw null; }
public void CopyTo(System.Diagnostics.ProcessThread[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessThread thread) { throw null; }
public void Insert(int index, System.Diagnostics.ProcessThread thread) { }
public void Remove(System.Diagnostics.ProcessThread thread) { }
}
public enum ThreadPriorityLevel
{
AboveNormal = 1,
BelowNormal = -1,
Highest = 2,
Idle = -15,
Lowest = -2,
Normal = 0,
TimeCritical = 15,
}
public enum ThreadState
{
Initialized = 0,
Ready = 1,
Running = 2,
Standby = 3,
Terminated = 4,
Transition = 6,
Unknown = 7,
Wait = 5,
}
public enum ThreadWaitReason
{
EventPairHigh = 7,
EventPairLow = 8,
ExecutionDelay = 4,
Executive = 0,
FreePage = 1,
LpcReceive = 9,
LpcReply = 10,
PageIn = 2,
PageOut = 12,
Suspended = 5,
SystemAllocation = 3,
Unknown = 13,
UserRequest = 6,
VirtualMemory = 11,
}
public enum ProcessWindowStyle
{
Hidden = 1,
Maximized = 3,
Minimized = 2,
Normal = 0,
}
[System.AttributeUsage(AttributeTargets.All)]
public class MonitoringDescriptionAttribute : System.ComponentModel.DescriptionAttribute
{
public MonitoringDescriptionAttribute(string description) { throw null; }
public override string Description { get { throw null; } }
}
}
| {
"content_hash": "94190e0bf8bc4d3a921d6956ded853de",
"timestamp": "",
"source": "github",
"line_count": 264,
"max_line_length": 187,
"avg_line_length": 57.85606060606061,
"alnum_prop": 0.6685216708131465,
"repo_name": "Jiayili1/corefx",
"id": "8e33640e9fb9dcc475778f9379f1f634bf109259",
"size": "15717",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "src/System.Diagnostics.Process/ref/System.Diagnostics.Process.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "327222"
},
{
"name": "ASP",
"bytes": "1687"
},
{
"name": "Batchfile",
"bytes": "24745"
},
{
"name": "C",
"bytes": "1113348"
},
{
"name": "C#",
"bytes": "139663920"
},
{
"name": "C++",
"bytes": "696253"
},
{
"name": "CMake",
"bytes": "63626"
},
{
"name": "DIGITAL Command Language",
"bytes": "26402"
},
{
"name": "Groovy",
"bytes": "41755"
},
{
"name": "HTML",
"bytes": "653"
},
{
"name": "Makefile",
"bytes": "9085"
},
{
"name": "Objective-C",
"bytes": "9948"
},
{
"name": "OpenEdge ABL",
"bytes": "139178"
},
{
"name": "Perl",
"bytes": "3895"
},
{
"name": "PowerShell",
"bytes": "43073"
},
{
"name": "Python",
"bytes": "1535"
},
{
"name": "Roff",
"bytes": "4236"
},
{
"name": "Shell",
"bytes": "72621"
},
{
"name": "Visual Basic",
"bytes": "827108"
},
{
"name": "XSLT",
"bytes": "462346"
}
],
"symlink_target": ""
} |
repetier-library
================
A library to communicate with 3D printers using repetier-firmware
| {
"content_hash": "33f704b391226e2d5f523c0adc93e678",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 65,
"avg_line_length": 25.25,
"alnum_prop": 0.7029702970297029,
"repo_name": "fablab-bayreuth/repetier-library",
"id": "eed64c40a46bbf3c92c388e459160893c0c857a8",
"size": "101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1177"
},
{
"name": "C++",
"bytes": "12652"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>qcert: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.15.1 / qcert - 1.0.5</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
qcert
<small>
1.0.5
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-11 09:27:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-11 09:27:55 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.15.1 Formal proof management system
dune 3.4.1 Fast, portable, and opinionated build system
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler
ocamlfind 1.9.1 A library manager for OCaml
ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "jeromesimeon@me.com"
homepage: "https://querycert.github.io"
dev-repo: "git+https://github.com/querycert/qcert"
bug-reports: "https://github.com/querycert/qcert/issues"
authors: [ "Josh Auerbach" "Martin Hirzel" "Louis Mandel" "Avi Shinnar" "Jerome Simeon" ]
license: "Apache-2.0"
build: [
[make "-j%{jobs}%" "qcert-coq"]
]
install: [
[make "install-coq"]
]
depends: [
"ocaml"
"coq" {>= "8.7.2" & < "8.8"}
]
synopsis: "A platform for implementing and verifying query compilers"
url {
src: "https://github.com/querycert/qcert/archive/v1.0.5.tar.gz"
checksum: "md5=3904c818b69823498769cacc1774c5d6"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-qcert.1.0.5 coq.8.15.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.15.1).
The following dependencies couldn't be met:
- coq-qcert -> coq < 8.8 -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-qcert.1.0.5</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "4b8b964e0cc77e60711707e5f8ad2232",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 159,
"avg_line_length": 41.37951807228916,
"alnum_prop": 0.5319551608676664,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "e6bb85706dac30e3802c69ea49a881cb108bbdd2",
"size": "6894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.15.1/qcert/1.0.5.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
static const char UNUSED *bitcoin_strings[] = {
QT_TRANSLATE_NOOP("bitcoin-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=bitcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Bitcoin Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC address %s port %u for listening: "
"%s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Cannot obtain a lock on data directory %s. Bitcoin Core is probably already "
"running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Continuously rate-limit free transactions to <n>*1000 bytes per minute "
"(default:%u)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Distributed under the MIT/X11 software license, see the accompanying file "
"COPYING or <http://www.opensource.org/licenses/mit-license.php>."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Fees (in BTC/Kb) smaller than this are considered zero fee for relaying "
"(default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Fees (in BTC/Kb) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Flush database activity from memory pool to disk log every <n> megabytes "
"(default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"How thorough the block verification of -checkblocks is (0-4, default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"If paytxfee is not set, include enough fee so transactions are confirmed on "
"average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"In this mode -genproclimit controls how many blocks are generated "
"immediately."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Log transaction priority and fee per kB when mining blocks (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set the processor limit for when generation is on (-1 = unlimited, default: "
"%d)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software "
"written by Eric Young and UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Unable to bind to %s on this computer. Bitcoin Core is probably already "
"running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong Bitcoin Core will not work properly."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Whitelist peers connecting from the given netmask or IP address. Can be "
"specified multiple times."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("bitcoin-core", "(default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "(default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "<category> can be:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Acceptable ciphers (default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -whitebind address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connection options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"),
QT_TRANSLATE_NOOP("bitcoin-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("bitcoin-core", "Could not parse -rpcbind value %s as network address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Disable safemode, override a real safe mode event (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("bitcoin-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of Bitcoin Core"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error opening block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: A fatal internal error occured, see debug.log for details"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("bitcoin-core", "Fee (in BTC/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Force safe mode (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Generate coins (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("bitcoin-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("bitcoin-core", "Importing..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("bitcoin-core", "Information"),
QT_TRANSLATE_NOOP("bitcoin-core", "Initialization sanity check failed. Bitcoin Core is shutting down."),
QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -onion address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Keep at most <n> unconnectable blocks in memory (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Limit size of signature cache to <n> entries (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Node relay options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("bitcoin-core", "Only accept block chain matching built-in checkpoints (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Print block on startup, if found in block index"),
QT_TRANSLATE_NOOP("bitcoin-core", "Print block tree on startup (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("bitcoin-core", "RPC server options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Randomly drop 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("bitcoin-core", "Randomly fuzz 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("bitcoin-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Run a thread to flush wallet periodically (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Stop running after importing blocks from disk (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "This help message"),
QT_TRANSLATE_NOOP("bitcoin-core", "This is experimental software."),
QT_TRANSLATE_NOOP("bitcoin-core", "This is intended for regression testing tools and app development."),
QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("bitcoin-core", "Transaction too large"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart Bitcoin Core to complete"),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("bitcoin-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("bitcoin-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "on startup"),
QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"),
};
| {
"content_hash": "0023418b0f149ddc041ac23af1397bc3",
"timestamp": "",
"source": "github",
"line_count": 291,
"max_line_length": 109,
"avg_line_length": 65.70446735395188,
"alnum_prop": 0.7342050209205021,
"repo_name": "cnote-coin/cnote",
"id": "1073b6a472618246dfe54790ae72c77606cc4478",
"size": "19275",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "src/qt/bitcoinstrings.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "482152"
},
{
"name": "C++",
"bytes": "2555998"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Makefile",
"bytes": "8683"
},
{
"name": "Objective-C",
"bytes": "1080"
},
{
"name": "Objective-C++",
"bytes": "6310"
},
{
"name": "Shell",
"bytes": "8483"
},
{
"name": "TypeScript",
"bytes": "5343050"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Apworks.Events;
using System.Linq;
using Apworks.Snapshots;
namespace Apworks.Repositories
{
public class EventSourcingDomainRepository : EventPublishingDomainRepository
{
private readonly IEventStore eventStore;
private readonly ISnapshotProvider snapshotProvider;
private bool disposed = false;
public EventSourcingDomainRepository(IEventStore eventStore,
IEventPublisher publisher,
ISnapshotProvider snapshotProvider)
: base(publisher)
{
this.eventStore = eventStore;
this.snapshotProvider = snapshotProvider;
}
public override TAggregateRoot GetById<TKey, TAggregateRoot>(TKey id)
=> this.GetById<TKey, TAggregateRoot>(id, AggregateRootWithEventSourcing<TKey>.MaxVersion);
public override TAggregateRoot GetById<TKey, TAggregateRoot>(TKey id, long version)
{
var sequenceMin = EventStore.MinimalSequence;
var aggregateRoot = this.ActivateAggregateRoot<TKey, TAggregateRoot>();
if (this.snapshotProvider.Enabled)
{
(var shouldCreate, var snapshot) = this.snapshotProvider.CheckSnapshot<TKey, TAggregateRoot>(id, version);
if (snapshot != null)
{
aggregateRoot.RestoreSnapshot(snapshot);
sequenceMin = snapshot.Version + 1;
}
}
var events = this.eventStore.Load<TKey>(typeof(TAggregateRoot).AssemblyQualifiedName, id, sequenceMin, version);
aggregateRoot.Replay(events.Select(e => e as IDomainEvent));
return aggregateRoot;
}
public override async Task<TAggregateRoot> GetByIdAsync<TKey, TAggregateRoot>(TKey id, CancellationToken cancellationToken)
=> await this.GetByIdAsync<TKey, TAggregateRoot>(id, AggregateRootWithEventSourcing<TKey>.MaxVersion, cancellationToken);
public override async Task<TAggregateRoot> GetByIdAsync<TKey, TAggregateRoot>(TKey id, long version, CancellationToken cancellationToken)
{
var sequenceMin = EventStore.MinimalSequence;
var aggregateRoot = this.ActivateAggregateRoot<TKey, TAggregateRoot>();
if (this.snapshotProvider.Enabled)
{
(var shouldCreate, var snapshot) = await this.snapshotProvider.CheckSnapshotAsync<TKey, TAggregateRoot>(id, version);
if (snapshot != null)
{
aggregateRoot.RestoreSnapshot(snapshot);
sequenceMin = snapshot.Version + 1;
}
}
var events = await this.eventStore.LoadAsync<TKey>(typeof(TAggregateRoot).AssemblyQualifiedName,
id,
sequenceMin,
version,
cancellationToken: cancellationToken);
aggregateRoot.Replay(events.Select(e => e as IDomainEvent));
return aggregateRoot;
}
public override void Save<TKey, TAggregateRoot>(TAggregateRoot aggregateRoot)
{
// Saves the uncommitted events to the event store.
var uncommittedEvents = aggregateRoot.UncommittedEvents;
this.eventStore.Save(uncommittedEvents); // This will save the uncommitted events in a transaction.
// Publishes the events.
this.Publisher.PublishAll(uncommittedEvents);
// Purges the uncommitted events.
((IPurgeable)aggregateRoot).Purge();
// Checks and saves the snapshot.
if (this.snapshotProvider.Enabled)
{
(var shouldCreate, var ss) = this.snapshotProvider.CheckSnapshot<TKey, TAggregateRoot>(aggregateRoot.Id, aggregateRoot.Version);
if (shouldCreate)
{
var snapshot = aggregateRoot.TakeSnapshot();
this.snapshotProvider.SaveSnapshot(snapshot);
}
}
}
public override async Task SaveAsync<TKey, TAggregateRoot>(TAggregateRoot aggregateRoot, CancellationToken cancellationToken)
{
// Saves the uncommitted events to the event store.
var uncommittedEvents = aggregateRoot.UncommittedEvents;
await this.eventStore.SaveAsync(uncommittedEvents, cancellationToken); // This will save the uncommitted events in a transaction.
// Publishes the events.
await this.Publisher.PublishAllAsync(uncommittedEvents, cancellationToken);
// Purges the uncommitted events.
((IPurgeable)aggregateRoot).Purge();
// Checks and saves the snapshot.
if (this.snapshotProvider.Enabled)
{
(var shouldCreate, var ss) = await this.snapshotProvider.CheckSnapshotAsync<TKey, TAggregateRoot>(aggregateRoot.Id, aggregateRoot.Version, cancellationToken);
if (shouldCreate)
{
var snapshot = aggregateRoot.TakeSnapshot();
await this.snapshotProvider.SaveSnapshotAsync(snapshot, cancellationToken);
}
}
}
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
this.eventStore.Dispose();
}
disposed = true;
base.Dispose(disposing);
}
}
}
}
| {
"content_hash": "7e51397ba1ef7080bd9449e9358d3cd5",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 174,
"avg_line_length": 40.719424460431654,
"alnum_prop": 0.6128975265017668,
"repo_name": "daxnet/apworks-core",
"id": "59dbac365966a9a41c201499ea6ccf56b706b571",
"size": "5662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Apworks/Repositories/EventSourcingDomainRepository.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "779"
},
{
"name": "C#",
"bytes": "655529"
},
{
"name": "Makefile",
"bytes": "608"
},
{
"name": "PowerShell",
"bytes": "342"
},
{
"name": "Python",
"bytes": "5151"
}
],
"symlink_target": ""
} |
#import <FBSnapshotTestCase/FBSnapshotTestCasePlatform.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
/**
Similar to our much-loved XCTAssert() macros. Use this to perform your test. No need to write an explanation, though.
@param view The view to snapshot
@param identifier An optional identifier, used if there are multiple snapshot tests in a given -test method.
@param suffixes An NSOrderedSet of strings for the different suffixes
@param tolerance The percentage of pixels that can differ and still count as an 'identical' view
*/
#define FBSnapshotVerifyViewWithOptions(view__, identifier__, suffixes__, tolerance__) \
{ \
NSString *envReferenceImageDirectory = [NSProcessInfo processInfo].environment[@"FB_REFERENCE_IMAGE_DIR"]; \
NSError *error__ = nil; \
BOOL comparisonSuccess__; \
XCTAssertTrue((suffixes__.count > 0), @"Suffixes set cannot be empty %@", suffixes__); \
XCTAssertNotNil(envReferenceImageDirectory, @"Missing value for referenceImagesDirectory - Set FB_REFERENCE_IMAGE_DIR as Environment variable in your scheme.");\
for (NSString *suffix__ in suffixes__) { \
NSString *referenceImagesDirectory__ = [NSString stringWithFormat:@"%@%@", envReferenceImageDirectory, suffix__]; \
comparisonSuccess__ = [self compareSnapshotOfView:(view__) referenceImagesDirectory:referenceImagesDirectory__ identifier:(identifier__) tolerance:(tolerance__) error:&error__]; \
if (comparisonSuccess__ || self.recordMode) break; \
} \
XCTAssertTrue(comparisonSuccess__, @"Snapshot comparison failed: %@", error__); \
XCTAssertFalse(self.recordMode, @"Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!"); \
}
#define FBSnapshotVerifyView(view__, identifier__) \
{ \
FBSnapshotVerifyViewWithOptions(view__, identifier__, FBSnapshotTestCaseDefaultSuffixes(), 0); \
}
/**
Similar to our much-loved XCTAssert() macros. Use this to perform your test. No need to write an explanation, though.
@param layer The layer to snapshot
@param identifier An optional identifier, used is there are multiple snapshot tests in a given -test method.
@param suffixes An NSOrderedSet of strings for the different suffixes
@param tolerance The percentage of pixels that can differ and still count as an 'identical' layer
*/
#define FBSnapshotVerifyLayerWithOptions(layer__, identifier__, suffixes__, tolerance__) \
{ \
NSString *envReferenceImageDirectory = [NSProcessInfo processInfo].environment[@"FB_REFERENCE_IMAGE_DIR"]; \
NSError *error__ = nil; \
BOOL comparisonSuccess__; \
XCTAssertTrue((suffixes__.count > 0), @"Suffixes set cannot be empty %@", suffixes__); \
XCTAssertNotNil(envReferenceImageDirectory, @"Missing value for referenceImagesDirectory - Set FB_REFERENCE_IMAGE_DIR as Environment variable in your scheme.");\
for (NSString *suffix__ in suffixes__) { \
NSString *referenceImagesDirectory__ = [NSString stringWithFormat:@"%@%@", envReferenceImageDirectory, suffix__]; \
comparisonSuccess__ = [self compareSnapshotOfLayer:(layer__) referenceImagesDirectory:referenceImagesDirectory__ identifier:(identifier__) tolerance:(tolerance__) error:&error__]; \
if (comparisonSuccess__ || self.recordMode) break; \
} \
XCTAssertTrue(comparisonSuccess__, @"Snapshot comparison failed: %@", error__); \
XCTAssertFalse(self.recordMode, @"Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!"); \
}
#define FBSnapshotVerifyLayer(layer__, identifier__) \
{ \
FBSnapshotVerifyLayerWithOptions(layer__, identifier__, FBSnapshotTestCaseDefaultSuffixes(), 0); \
}
/**
The base class of view snapshotting tests. If you have small UI component, it's often easier to configure it in a test
and compare an image of the view to a reference image that write lots of complex layout-code tests.
In order to flip the tests in your subclass to record the reference images set @c recordMode to @c YES.
For example:
@code
- (void)setUp
{
[super setUp];
self.recordMode = YES;
}
@endcode
*/
@interface FBSnapshotTestCase : XCTestCase
/**
When YES, the test macros will save reference images, rather than performing an actual test.
*/
@property (readwrite, nonatomic, assign) BOOL recordMode;
/**
When YES, renders a snapshot of the complete view hierarchy as visible onscreen.
There are several things that do not work if renderInContext: is used.
- UIVisualEffect #70
- UIAppearance #91
- Size Classes #92
@attention If the view does't belong to a UIWindow, it will create one and add the view as a subview.
*/
@property (readwrite, nonatomic, assign) BOOL usesDrawViewHierarchyInRect;
- (void)setUp NS_REQUIRES_SUPER;
- (void)tearDown NS_REQUIRES_SUPER;
/**
Performs the comparison or records a snapshot of the layer if recordMode is YES.
@param layer The Layer to snapshot
@param referenceImagesDirectory The directory in which reference images are stored.
@param identifier An optional identifier, used if there are multiple snapshot tests in a given -test method.
@param tolerance The percentage difference to still count as identical - 0 mean pixel perfect, 1 means I don't care
@param errorPtr An error to log in an XCTAssert() macro if the method fails (missing reference image, images differ, etc).
@returns YES if the comparison (or saving of the reference image) succeeded.
*/
- (BOOL)compareSnapshotOfLayer:(CALayer *)layer
referenceImagesDirectory:(NSString *)referenceImagesDirectory
identifier:(NSString *)identifier
tolerance:(CGFloat)tolerance
error:(NSError **)errorPtr;
/**
Performs the comparison or records a snapshot of the view if recordMode is YES.
@param view The view to snapshot
@param referenceImagesDirectory The directory in which reference images are stored.
@param identifier An optional identifier, used if there are multiple snapshot tests in a given -test method.
@param tolerance The percentage difference to still count as identical - 0 mean pixel perfect, 1 means I don't care
@param errorPtr An error to log in an XCTAssert() macro if the method fails (missing reference image, images differ, etc).
@returns YES if the comparison (or saving of the reference image) succeeded.
*/
- (BOOL)compareSnapshotOfView:(UIView *)view
referenceImagesDirectory:(NSString *)referenceImagesDirectory
identifier:(NSString *)identifier
tolerance:(CGFloat)tolerance
error:(NSError **)errorPtr;
@end
| {
"content_hash": "5b1536aa8e6ce8b84687d0973551e6dd",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 181,
"avg_line_length": 49.45112781954887,
"alnum_prop": 0.7507982362779383,
"repo_name": "soppysonny/wikipedia-ios",
"id": "e4bd1170736a260a04a82f2cc1187e4f73b9c58c",
"size": "6884",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Pods/FBSnapshotTestCase/FBSnapshotTestCase/FBSnapshotTestCase.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6462"
},
{
"name": "C++",
"bytes": "2691"
},
{
"name": "CSS",
"bytes": "8256"
},
{
"name": "HTML",
"bytes": "1004759"
},
{
"name": "JavaScript",
"bytes": "77532"
},
{
"name": "Makefile",
"bytes": "5533"
},
{
"name": "Objective-C",
"bytes": "1917425"
},
{
"name": "PHP",
"bytes": "6635"
},
{
"name": "Ruby",
"bytes": "15612"
},
{
"name": "Shell",
"bytes": "7004"
},
{
"name": "Swift",
"bytes": "75165"
}
],
"symlink_target": ""
} |
<!--
Safe sample
input : get the field userData from the variable $_GET via an object
sanitize : use of the function htmlentities. Sanitizes the query but has a high chance to produce unexpected results
File : use of untrusted data in the body
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head/>
<body>
<?php
class Input{
public function getInput(){
return $_GET['UserData'] ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
$tainted = htmlentities($tainted, ENT_QUOTES);
echo $tainted ;
?>
<h1>Hello World!</h1>
</body>
</html>
| {
"content_hash": "52697af1a1b502e3b4a5466904184d7d",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 116,
"avg_line_length": 22.936507936507937,
"alnum_prop": 0.7550173010380623,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "0e5944770093b36748252bc8502be7a4d4cb5a9f",
"size": "1445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XSS/CWE_79/safe/CWE_79__object-directGet__func_htmlentities__Use_untrusted_data-body.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
<?php
// DIC configuration
$container = $app->getContainer();
// view renderer
$container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer'];
return new Slim\Views\PhpRenderer($settings['template_path']);
};
// monolog
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
if ($settings['debug']) $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG));
else $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::INFO));
return $logger;
};
// database
$container['db'] = function ($c) {
$capsule = new Illuminate\Database\Capsule\Manager;
$capsule->addConnection($c->get('settings')['database']);
return $capsule;
};
$container->db->setAsGlobal();
$container->db->bootEloquent();
$container->db->connection()->setEventDispatcher(new Illuminate\Events\Dispatcher(new Illuminate\Container\Container));
$container->db->connection()->listen(function ($query) use ($app) {
$app->getContainer()->logger->addDebug('{'.$query->time.' ms} {'.$query->sql.'}', $query->bindings);
}); | {
"content_hash": "18595428a9faab24659132c9cfb1cd96",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 126,
"avg_line_length": 37.73529411764706,
"alnum_prop": 0.6679657053780202,
"repo_name": "pjuros/slim3-skeleton",
"id": "7db18053e08e1692ee1945e4e2b6c840c2862302",
"size": "1283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/dependencies.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "323"
},
{
"name": "CSS",
"bytes": "687419"
},
{
"name": "HTML",
"bytes": "10177"
},
{
"name": "JavaScript",
"bytes": "1080787"
},
{
"name": "PHP",
"bytes": "17210"
}
],
"symlink_target": ""
} |
package org.jetbrains.plugins.scala
package lang
package psi
package api
package statements
package params
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.nonvalue.Parameter
import org.jetbrains.plugins.scala.lang.psi.types.result.TypingContext
/**
* @author Alexander Podkhalyuzin
* Date: 21.03.2008
*/
trait ScParameterClause extends ScalaPsiElement {
def parameters: Seq[ScParameter]
def effectiveParameters: Seq[ScParameter]
//hack: no ClassParamList present at the moment
def unsafeClassParameters = effectiveParameters.asInstanceOf[Seq[ScClassParameter]]
def paramTypes: Seq[ScType] = parameters.map(_.getType(TypingContext.empty).getOrAny)
def isImplicit: Boolean
def implicitToken: Option[PsiElement] = Option(findFirstChildByType(ScalaTokenTypes.kIMPLICIT))
def hasRepeatedParam: Boolean = parameters.lastOption.exists(_.isRepeatedParameter)
def getSmartParameters: Seq[Parameter] = effectiveParameters.map(new Parameter(_))
/**
* add parameter as last parameter in clause
* if clause has repeated parameter, add before this parameter.
*/
def addParameter(param: ScParameter): ScParameterClause
} | {
"content_hash": "b66b1e3076c0cb5a929c660c21f4b78e",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 97,
"avg_line_length": 31.11904761904762,
"alnum_prop": 0.7934200459066565,
"repo_name": "JetBrains/intellij-scala-historical",
"id": "6f1830dfd706fc6db4fc1ee21c96671dc1e97521",
"size": "1307",
"binary": false,
"copies": "2",
"ref": "refs/heads/idea15.x",
"path": "src/org/jetbrains/plugins/scala/lang/psi/api/statements/params/ScParameterClause.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "33967"
},
{
"name": "Java",
"bytes": "988876"
},
{
"name": "Lex",
"bytes": "34288"
},
{
"name": "Scala",
"bytes": "6286115"
},
{
"name": "Shell",
"bytes": "232"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MusicPimp.ViewModels
{
public class MotdVM : ViewModelBase
{
private string motd = "No messages today!";
public string Motd
{
get { return motd; }
set { SetProperty(ref motd, value); }
}
public void Update(string input)
{
Motd = input;
}
}
}
| {
"content_hash": "e1973da216eeb412a5171d5a858ba2b6",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 51,
"avg_line_length": 20.652173913043477,
"alnum_prop": 0.5810526315789474,
"repo_name": "malliina/musicpimp-uwp",
"id": "e130c99611702d636b13b0e90e8857b90a4e52f1",
"size": "477",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MusicPimp-UWP/ViewModels/MotdVM.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "107720"
}
],
"symlink_target": ""
} |
Compute the coordinates of a circle placed at a given latitude and longitude.
# Usage
call MakeCircleCoord (`coord`, `lat`, `lon`, `theta0`, `cinterval`, `cnum`, `exitstatus`)
# Parameters
`coord` : output, real\*8, dimension(360/`cinterval`, 2)
: The latitude (:,1) and longitude (:,2) coordinates of the circle in degrees. If not specified, `cintervaL` is assumed to 1.
`lat` : input, real\*8
: The latitude of the center of the circle in degrees.
`lon` : input, real\*8
: The longitude of the center of the circle in degrees.
`theta0` : input, real\*8
: The angular radius of the circle in degrees.
`cinterval` : optional, input, real\*8, default = 1
: Angular spacing in degrees of the output latitude and longitude points. If not present, the default is 1.
`cnum` : optional, output, integer
: Number of elements in the output arrays.
`exitstatus` : output, optional, integer
: If present, instead of executing a STOP when an error is encountered, the variable exitstatus will be returned describing the error. 0 = No errors; 1 = Improper dimensions of input array; 2 = Improper bounds for input variable; 3 = Error allocating memory; 4 = File IO error.
# Description
`MakeCircleCoord` will calculate the latitude and longitude coordinates of a circle of angular radius `theta0` placed on a sphere at position (`lat`, `lon`). This is useful for plotting circles on geographic maps. The first index in the output vectors corresponds to the point directly north of the cirlce origin, and subsequent points are arranged in a clockwise manner. Input and output units are in degrees.
# See also
[makeellipsecoord](makeellipsecoord.html)
| {
"content_hash": "974015fda404ef27ba95f437aa54cd7d",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 410,
"avg_line_length": 46.25,
"alnum_prop": 0.7429429429429429,
"repo_name": "ioshchepkov/SHTOOLS",
"id": "14950218a67d97c5f7fffdaf79f21e66082f3f47",
"size": "1684",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/fdoc/makecirclecoord.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Fortran",
"bytes": "1204574"
},
{
"name": "Makefile",
"bytes": "26801"
},
{
"name": "Python",
"bytes": "290300"
}
],
"symlink_target": ""
} |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.node import PipeUnderground
log = logging.getLogger(__name__)
class TestPipeUnderground(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_pipeunderground(self):
pyidf.validation_level = ValidationLevel.error
obj = PipeUnderground()
# alpha
var_name = "Name"
obj.name = var_name
# object-list
var_construction_name = "object-list|Construction Name"
obj.construction_name = var_construction_name
# node
var_fluid_inlet_node_name = "node|Fluid Inlet Node Name"
obj.fluid_inlet_node_name = var_fluid_inlet_node_name
# node
var_fluid_outlet_node_name = "node|Fluid Outlet Node Name"
obj.fluid_outlet_node_name = var_fluid_outlet_node_name
# alpha
var_sun_exposure = "SunExposed"
obj.sun_exposure = var_sun_exposure
# real
var_pipe_inside_diameter = 0.0001
obj.pipe_inside_diameter = var_pipe_inside_diameter
# real
var_pipe_length = 0.0001
obj.pipe_length = var_pipe_length
# alpha
var_soil_material_name = "Soil Material Name"
obj.soil_material_name = var_soil_material_name
# alpha
var_undisturbed_ground_temperature_model_type = "Site:GroundTemperature:Undisturbed:FiniteDifference"
obj.undisturbed_ground_temperature_model_type = var_undisturbed_ground_temperature_model_type
# object-list
var_undisturbed_ground_temperature_model_name = "object-list|Undisturbed Ground Temperature Model Name"
obj.undisturbed_ground_temperature_model_name = var_undisturbed_ground_temperature_model_name
idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
with open(self.path, mode='r') as f:
for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertEqual(idf2.pipeundergrounds[0].name, var_name)
self.assertEqual(idf2.pipeundergrounds[0].construction_name, var_construction_name)
self.assertEqual(idf2.pipeundergrounds[0].fluid_inlet_node_name, var_fluid_inlet_node_name)
self.assertEqual(idf2.pipeundergrounds[0].fluid_outlet_node_name, var_fluid_outlet_node_name)
self.assertEqual(idf2.pipeundergrounds[0].sun_exposure, var_sun_exposure)
self.assertAlmostEqual(idf2.pipeundergrounds[0].pipe_inside_diameter, var_pipe_inside_diameter)
self.assertAlmostEqual(idf2.pipeundergrounds[0].pipe_length, var_pipe_length)
self.assertEqual(idf2.pipeundergrounds[0].soil_material_name, var_soil_material_name)
self.assertEqual(idf2.pipeundergrounds[0].undisturbed_ground_temperature_model_type, var_undisturbed_ground_temperature_model_type)
self.assertEqual(idf2.pipeundergrounds[0].undisturbed_ground_temperature_model_name, var_undisturbed_ground_temperature_model_name) | {
"content_hash": "69f8f8e91f575fbc3255043ab6fb37fd",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 139,
"avg_line_length": 42.36486486486486,
"alnum_prop": 0.6889952153110048,
"repo_name": "rbuffat/pyidf",
"id": "2e951d342ca9df4737920641062aed282e12cb49",
"size": "3135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_pipeunderground.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "22271673"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
-->
<config>
<sections>
<web>
<groups>
<default>
<fields>
<cms_home_page translate="label" module="cms">
<label>CMS Home Page</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_cms_page</source_model>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</cms_home_page>
<cms_no_route translate="label" module="cms">
<label>CMS No Route Page</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_cms_page</source_model>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</cms_no_route>
<cms_no_cookies translate="label" module="cms">
<label>CMS No Cookies Page</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_cms_page</source_model>
<sort_order>3</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</cms_no_cookies>
<show_cms_breadcrumbs translate="label" module="cms">
<label>Show Breadcrumbs for CMS Pages</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>5</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</show_cms_breadcrumbs>
</fields>
</default>
</groups>
</web>
<cms translate="label" module="cms">
<label>Content Management</label>
<tab>general</tab>
<frontend_type>text</frontend_type>
<sort_order>1001</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<groups>
<wysiwyg translate="label">
<label>WYSIWYG Options</label>
<frontend_type>text</frontend_type>
<sort_order>100</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<enabled translate="label">
<label>Enable WYSIWYG Editor</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_cms_wysiwyg_enabled</source_model>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</enabled>
</fields>
</wysiwyg>
</groups>
</cms>
</sections>
</config>
| {
"content_hash": "efe4dca4683190eaee3b0ebaedf79952",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 107,
"avg_line_length": 49.46341463414634,
"alnum_prop": 0.4334319526627219,
"repo_name": "cesarfelip3/cleverva",
"id": "f7f0404f560b40dc6ba8b4157020611fc37c7b33",
"size": "4997",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "app/code/core/Mage/Cms/etc/system.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "20018"
},
{
"name": "ApacheConf",
"bytes": "12014"
},
{
"name": "Batchfile",
"bytes": "1036"
},
{
"name": "CSS",
"bytes": "1998129"
},
{
"name": "HTML",
"bytes": "5272065"
},
{
"name": "JavaScript",
"bytes": "1126004"
},
{
"name": "PHP",
"bytes": "47608047"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Ruby",
"bytes": "288"
},
{
"name": "Shell",
"bytes": "8761"
},
{
"name": "XSLT",
"bytes": "2066"
}
],
"symlink_target": ""
} |
# frozen_string_literal: true
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# config.secret_key = 'd0acf5229989d2def7090e91f2d7a584b6eee8d2545048675ed17784aaeda8e3b3131b0679797a863177e83592b234847c931f67a4f5b7c7177a96f2e445acf0'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = 'no-reply@' + Rails.application.secrets.domain_name
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# encryptor), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = '8256050ff68a604580668684d7193e604267ea746508eb775f21ab3d4aea2758bb843a1f0848fa42463394ee91fdb80620f9489589d8d182db04d98e113f7726'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| {
"content_hash": "1e73a13c40c2a46df78339d7abe4d6c9",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 154,
"avg_line_length": 49.13076923076923,
"alnum_prop": 0.7418976045091592,
"repo_name": "kathyonu/rails-stripe-rspec-tests",
"id": "70790bf5b996f9051c40b6bc32329611649f7477",
"size": "12774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/initializers/devise.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "224185"
}
],
"symlink_target": ""
} |
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
from allauth.account.models import EmailAddress
class MyAccountAdapter(DefaultAccountAdapter):
def pre_social_login(self, request, sociallogin):
"""
Invoked just after a user successfully authenticates via a
social provider, but before the login is actually processed
(and before the pre_social_login signal is emitted).
We're trying to solve different use cases:
- social account already exists, just go on
- social account has no email or email is unknown, just go on
- social account's email exists, link social account to existing user
"""
# Ignore existing social accounts, just do this stuff for new ones
if sociallogin.is_existing:
return
# some social logins don't have an email address, e.g. facebook accounts
# with mobile numbers only, but allauth takes care of this case so just
# ignore it
if 'email' not in sociallogin.account.extra_data:
return
# check if given email address already exists.
# Note: __iexact is used to ignore cases
try:
email = sociallogin.account.extra_data['email'].lower()
email_address = EmailAddress.objects.get(email__iexact=email)
# if it does not, let allauth take care of this new social account
except EmailAddress.DoesNotExist:
return
# if it does, connect this new social login to the existing user
user = email_address.user
sociallogin.connect(request, user)
def join_social_account(self, request, sociallogin):
if sociallogin.is_existing:
print sociallogin
return
def get_login_redirect_url(self, request):
path = "/accounts/dashboard/{username}/"
return path.format(username=request.user.username)
| {
"content_hash": "0fdf5edaf16a68e52653586005c6e2d6",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 80,
"avg_line_length": 40.04081632653061,
"alnum_prop": 0.663098878695209,
"repo_name": "c24b/playlab",
"id": "6520070f55ad1281630c486f1b2f2a95511497d5",
"size": "1990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "playlab/adapter.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "112952"
},
{
"name": "HTML",
"bytes": "70400"
},
{
"name": "JavaScript",
"bytes": "99591"
},
{
"name": "Python",
"bytes": "18480"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AssemblyInfoReplacementParams - FAKE - F# Make</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />
<script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/fake">github page</a></li>
</ul>
<h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>AssemblyInfoReplacementParams</h1>
<div class="xmldoc">
</div>
<h3>Record Fields</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Record Field</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1200', 1200)" onmouseover="showTip(event, '1200', 1200)">
AssemblyCompany
</code>
<div class="tip" id="1200">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L209-209" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1201', 1201)" onmouseover="showTip(event, '1201', 1201)">
AssemblyConfiguration
</code>
<div class="tip" id="1201">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L211-211" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1202', 1202)" onmouseover="showTip(event, '1202', 1202)">
AssemblyCopyright
</code>
<div class="tip" id="1202">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L210-210" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1203', 1203)" onmouseover="showTip(event, '1203', 1203)">
AssemblyFileVersion
</code>
<div class="tip" id="1203">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L207-207" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1204', 1204)" onmouseover="showTip(event, '1204', 1204)">
AssemblyInformationalVersion
</code>
<div class="tip" id="1204">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L208-208" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1205', 1205)" onmouseover="showTip(event, '1205', 1205)">
AssemblyMetadata
</code>
<div class="tip" id="1205">
<strong>Signature:</strong> (string * string) list<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L212-212" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1206', 1206)" onmouseover="showTip(event, '1206', 1206)">
AssemblyVersion
</code>
<div class="tip" id="1206">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L206-206" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1207', 1207)" onmouseover="showTip(event, '1207', 1207)">
OutputFileName
</code>
<div class="tip" id="1207">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/AssemblyInfoHelper.fs#L205-205" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<a href="http://fsharp.github.io/FAKE/index.html">
<img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" />
</a>
<ul class="nav nav-list" id="menu">
<li class="nav-header">FAKE - F# Make</li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li>
<li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li>
<li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li>
<li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li>
<li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li>
<li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li>
<li class="nav-header">Tutorials</li>
<li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li>
<li><a href="http://fsharp.github.io/FAKE/cache.html">Build script caching</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li>
<li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li>
<li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li>
<li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li>
<li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li>
<li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li>
<li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li>
<li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li>
<li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li>
<li><a href="http://fsharp.github.io/FAKE/soft-dependencies.html">Soft dependencies</a></li>
<li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li>
<li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li>
<li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li>
<li><a href="http://fsharp.github.io/FAKE/fluentmigrator.html">FluentMigrator support</a></li>
<li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li>
<li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li>
<li><a href="http://fsharp.github.io/FAKE/wix.html">WiX Setup Generation</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/iis.html">Fake.IIS</a></li>
<li class="nav-header">Reference</li>
<li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
| {
"content_hash": "ae0c66ab50e5cad93b4506804e043aeb",
"timestamp": "",
"source": "github",
"line_count": 252,
"max_line_length": 209,
"avg_line_length": 46.37301587301587,
"alnum_prop": 0.5610987506417936,
"repo_name": "dcastro/AutoFixture",
"id": "235f06e5529c34012215baa57299afaf7ccd63ec",
"size": "11686",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Packages/FAKE.4.19.0/docs/apidocs/fake-assemblyinfohelper-assemblyinforeplacementparams.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3598457"
},
{
"name": "F#",
"bytes": "43535"
},
{
"name": "PowerShell",
"bytes": "861"
},
{
"name": "Puppet",
"bytes": "170"
},
{
"name": "Shell",
"bytes": "230"
},
{
"name": "Smalltalk",
"bytes": "2018"
},
{
"name": "XSLT",
"bytes": "17270"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAuditingPolicyOperations _auditingPolicy;
/// <summary>
/// Represents all the operations to manage Azure SQL Database and
/// Database Server Audit policy. Contains operations to: Create,
/// Retrieve and Update audit policy.
/// </summary>
public virtual IAuditingPolicyOperations AuditingPolicy
{
get { return this._auditingPolicy; }
}
private ICapabilitiesOperations _capabilities;
/// <summary>
/// Represents all the operations for determining the set of
/// capabilites available in a specified region.
/// </summary>
public virtual ICapabilitiesOperations Capabilities
{
get { return this._capabilities; }
}
private IDatabaseActivationOperations _databaseActivation;
/// <summary>
/// Represents all the operations for operating pertaining to
/// activation on Azure SQL Data Warehouse databases. Contains
/// operations to: Pause and Resume databases
/// </summary>
public virtual IDatabaseActivationOperations DatabaseActivation
{
get { return this._databaseActivation; }
}
private IDatabaseBackupOperations _databaseBackup;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// database backups.
/// </summary>
public virtual IDatabaseBackupOperations DatabaseBackup
{
get { return this._databaseBackup; }
}
private IDatabaseOperations _databases;
/// <summary>
/// Represents all the operations for operating on Azure SQL Databases.
/// Contains operations to: Create, Retrieve, Update, and Delete
/// databases, and also includes the ability to get the event logs for
/// a database.
/// </summary>
public virtual IDatabaseOperations Databases
{
get { return this._databases; }
}
private IDataMaskingOperations _dataMasking;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// data masking. Contains operations to: Create, Retrieve, Update,
/// and Delete data masking rules, as well as Create, Retreive and
/// Update data masking policy.
/// </summary>
public virtual IDataMaskingOperations DataMasking
{
get { return this._dataMasking; }
}
private IElasticPoolOperations _elasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Elastic Pools. Contains operations to: Create, Retrieve, Update,
/// and Delete.
/// </summary>
public virtual IElasticPoolOperations ElasticPools
{
get { return this._elasticPools; }
}
private IFirewallRuleOperations _firewallRules;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Server Firewall Rules. Contains operations to: Create, Retrieve,
/// Update, and Delete firewall rules.
/// </summary>
public virtual IFirewallRuleOperations FirewallRules
{
get { return this._firewallRules; }
}
private IImportExportOperations _importExport;
/// <summary>
/// Represents all the operations for import/export on Azure SQL
/// Databases. Contains operations to: Import, Export, Get
/// Import/Export status for a database.
/// </summary>
public virtual IImportExportOperations ImportExport
{
get { return this._importExport; }
}
private IRecommendedElasticPoolOperations _recommendedElasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL
/// Recommended Elastic Pools. Contains operations to: Retrieve.
/// </summary>
public virtual IRecommendedElasticPoolOperations RecommendedElasticPools
{
get { return this._recommendedElasticPools; }
}
private IRecommendedIndexOperations _recommendedIndexes;
/// <summary>
/// Represents all the operations for managing recommended indexes on
/// Azure SQL Databases. Contains operations to retrieve recommended
/// index and update state.
/// </summary>
public virtual IRecommendedIndexOperations RecommendedIndexes
{
get { return this._recommendedIndexes; }
}
private IReplicationLinkOperations _databaseReplicationLinks;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Replication Links. Contains operations to: Delete and Retrieve
/// replication links.
/// </summary>
public virtual IReplicationLinkOperations DatabaseReplicationLinks
{
get { return this._databaseReplicationLinks; }
}
private ISecureConnectionPolicyOperations _secureConnection;
/// <summary>
/// Represents all the operations for managing Azure SQL Database
/// secure connection. Contains operations to: Create, Retrieve and
/// Update secure connection policy .
/// </summary>
public virtual ISecureConnectionPolicyOperations SecureConnection
{
get { return this._secureConnection; }
}
private ISecurityAlertPolicyOperations _securityAlertPolicy;
/// <summary>
/// Represents all the operations to manage Azure SQL Database and
/// Database Server Security Alert policy. Contains operations to:
/// Create, Retrieve and Update policy.
/// </summary>
public virtual ISecurityAlertPolicyOperations SecurityAlertPolicy
{
get { return this._securityAlertPolicy; }
}
private IServerAdministratorOperations _serverAdministrators;
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// Active Directory Administrators. Contains operations to: Create,
/// Retrieve, Update, and Delete Azure SQL Server Active Directory
/// Administrators.
/// </summary>
public virtual IServerAdministratorOperations ServerAdministrators
{
get { return this._serverAdministrators; }
}
private IServerCommunicationLinkOperations _communicationLinks;
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// communication links. Contains operations to: Create, Retrieve,
/// Update, and Delete.
/// </summary>
public virtual IServerCommunicationLinkOperations CommunicationLinks
{
get { return this._communicationLinks; }
}
private IServerDisasterRecoveryConfigurationOperations _serverDisasterRecoveryConfigurations;
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// disaster recovery configurations. Contains operations to: Create,
/// Retrieve, Update, and Delete.
/// </summary>
public virtual IServerDisasterRecoveryConfigurationOperations ServerDisasterRecoveryConfigurations
{
get { return this._serverDisasterRecoveryConfigurations; }
}
private IServerOperations _servers;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Servers. Contains operations to: Create, Retrieve, Update, and
/// Delete servers.
/// </summary>
public virtual IServerOperations Servers
{
get { return this._servers; }
}
private IServerUpgradeOperations _serverUpgrades;
/// <summary>
/// Represents all the operations for Azure SQL Database Server Upgrade
/// </summary>
public virtual IServerUpgradeOperations ServerUpgrades
{
get { return this._serverUpgrades; }
}
private IServiceObjectiveOperations _serviceObjectives;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Service Objectives. Contains operations to: Retrieve service
/// objectives.
/// </summary>
public virtual IServiceObjectiveOperations ServiceObjectives
{
get { return this._serviceObjectives; }
}
private IServiceTierAdvisorOperations _serviceTierAdvisors;
/// <summary>
/// Represents all the operations for operating on service tier
/// advisors. Contains operations to: Retrieve.
/// </summary>
public virtual IServiceTierAdvisorOperations ServiceTierAdvisors
{
get { return this._serviceTierAdvisors; }
}
private ITransparentDataEncryptionOperations _transparentDataEncryption;
/// <summary>
/// Represents all the operations of Azure SQL Database Transparent
/// Data Encryption. Contains operations to: Retrieve, and Update
/// Transparent Data Encryption.
/// </summary>
public virtual ITransparentDataEncryptionOperations TransparentDataEncryption
{
get { return this._transparentDataEncryption; }
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
public SqlManagementClient()
: base()
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._capabilities = new CapabilitiesOperations(this);
this._databaseActivation = new DatabaseActivationOperations(this);
this._databaseBackup = new DatabaseBackupOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._importExport = new ImportExportOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._recommendedIndexes = new RecommendedIndexOperations(this);
this._databaseReplicationLinks = new ReplicationLinkOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._securityAlertPolicy = new SecurityAlertPolicyOperations(this);
this._serverAdministrators = new ServerAdministratorOperations(this);
this._communicationLinks = new ServerCommunicationLinkOperations(this);
this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._capabilities = new CapabilitiesOperations(this);
this._databaseActivation = new DatabaseActivationOperations(this);
this._databaseBackup = new DatabaseBackupOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._importExport = new ImportExportOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._recommendedIndexes = new RecommendedIndexOperations(this);
this._databaseReplicationLinks = new ReplicationLinkOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._securityAlertPolicy = new SecurityAlertPolicyOperations(this);
this._serverAdministrators = new ServerAdministratorOperations(this);
this._communicationLinks = new ServerCommunicationLinkOperations(this);
this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SqlManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of SqlManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<SqlManagementClient> client)
{
base.Clone(client);
if (client is SqlManagementClient)
{
SqlManagementClient clonedClient = ((SqlManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| {
"content_hash": "f27004c5706080a7d35c942d9a1b1402",
"timestamp": "",
"source": "github",
"line_count": 535,
"max_line_length": 113,
"avg_line_length": 40.56448598130841,
"alnum_prop": 0.6100359413878905,
"repo_name": "Matt-Westphal/azure-sdk-for-net",
"id": "109e0e965492c9dd02f2eccd50377997407c7802",
"size": "22490",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/ResourceManagement/Sql/SqlManagement/Generated/SqlManagementClient.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "118"
},
{
"name": "Batchfile",
"bytes": "817"
},
{
"name": "C#",
"bytes": "61175068"
},
{
"name": "CSS",
"bytes": "685"
},
{
"name": "Cucumber",
"bytes": "89597"
},
{
"name": "JavaScript",
"bytes": "1719"
},
{
"name": "PowerShell",
"bytes": "24280"
},
{
"name": "Shell",
"bytes": "45"
}
],
"symlink_target": ""
} |
package org.hisp.dhis.datasetreport;
import java.util.Map;
import java.util.Set;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.Period;
/**
* @author Lars Helge Overland
*/
public interface DataSetReportStore
{
String SEPARATOR = "-";
/**
* Get a mapping from dimensional identifiers to aggregated values.
*
* @param dataSet the data set.
* @param period the period.
* @param unit the organisation unit.
* @param dimensions the dimensions on the analytics dimension format, e.g.
* <dim-id>:<dim-item>;<dim-item>
* @return a mapping from dimensional identifiers to aggregated values.
*/
Map<String, Object> getAggregatedValues( DataSet dataSet, Period period, OrganisationUnit unit, Set<String> dimensions );
/**
* Get a mapping from dimensional identifiers to aggregated sub-total values.
*
* @param dataSet the data set.
* @param period the period.
* @param unit the organisation unit.
* @param dimensions the dimensions on the analytics dimension format, e.g.
* <dim-id>:<dim-item>;<dim-item>
* @return a mapping from dimensional identifiers to aggregated sub-total values.
*/
Map<String, Object> getAggregatedSubTotals( DataSet dataSet, Period period, OrganisationUnit unit, Set<String> dimensions );
/**
* Get a mapping from dimensional identifiers to aggregated total values.
*
* @param dataSet the data set.
* @param period the period.
* @param unit the organisation unit.
* @param dimensions the dimensions on the analytics dimension format, e.g.
* <dim-id>:<dim-item>;<dim-item>
* @return a mapping from dimensional identifiers to aggregated total values.
*/
Map<String, Object> getAggregatedTotals( DataSet dataSet, Period period, OrganisationUnit unit, Set<String> dimensions );
/**
* Get a mapping from dimensional identifiers to aggregated indicator values.
*
* @param dataSet the data set.
* @param period the period.
* @param unit the organisation unit.
* @param dimensions the dimensions on the analytics dimension format, e.g.
* <dim-id>:<dim-item>;<dim-item>
* @return a mapping from dimensional identifiers to aggregated indicator values.
*/
Map<String, Object> getAggregatedIndicatorValues( DataSet dataSet, Period period, OrganisationUnit unit, Set<String> dimensions );
}
| {
"content_hash": "156ca931a6bc6fdebfb218fe3478f510",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 134,
"avg_line_length": 38.34848484848485,
"alnum_prop": 0.6878704069537732,
"repo_name": "HRHR-project/palestine",
"id": "c30efb0a5061da822edd2a9f4bb672fa81ebe91c",
"size": "4087",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "dhis-2/dhis-api/src/main/java/org/hisp/dhis/datasetreport/DataSetReportStore.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "349044"
},
{
"name": "Game Maker Language",
"bytes": "20893"
},
{
"name": "HTML",
"bytes": "449001"
},
{
"name": "Java",
"bytes": "16145967"
},
{
"name": "JavaScript",
"bytes": "3960411"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "394"
},
{
"name": "XSLT",
"bytes": "8281"
}
],
"symlink_target": ""
} |
__credits__ = ["Daniel McDonald", "Greg Caporaso", "Doug Wendel",
"Jai Ram Rideout"]
| {
"content_hash": "977f8edb1965566c03e194da08d6bd7e",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 65,
"avg_line_length": 50,
"alnum_prop": 0.56,
"repo_name": "biocore/pyqi",
"id": "87fe705947355ce3e5afe5bf02d0e8553bff9737",
"size": "473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyqi/interfaces/optparse/config/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "198067"
},
{
"name": "Shell",
"bytes": "5092"
}
],
"symlink_target": ""
} |
require 'simplecov'
if ENV['CI']
require 'coveralls'
Coveralls.wear!('rails')
end
SimpleCov.start do
add_filter 'spec/dummy'
add_group 'Controllers', 'app/controllers'
add_group 'Models', 'app/models'
add_group 'Serializers', 'app/serializers'
add_group 'Libraries', 'lib'
end
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'rspec/rails'
require 'rspec/its'
require 'database_cleaner'
require 'ffaker'
require 'json_spec'
require 'shoulda/matchers'
Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f }
require 'spree/testing_support/factories'
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.include JsonSpec::Helpers
config.infer_spec_type_from_file_location!
config.mock_with :rspec
config.color = true
config.use_transactional_fixtures = false
config.fail_fast = ENV['FAIL_FAST'] || false
config.order = "random"
config.before :suite do
ActiveModel::Serializer.config.adapter = :json_api
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
end
config.before :each do
DatabaseCleaner.strategy = RSpec.current_example.metadata[:js] ? :truncation : :transaction
DatabaseCleaner.start
end
config.after :each do
DatabaseCleaner.clean
end
end
| {
"content_hash": "9bb96711331045678fec14339faab846",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 95,
"avg_line_length": 23.894736842105264,
"alnum_prop": 0.7217327459618208,
"repo_name": "spree-contrib/spree_api_v2",
"id": "1dbaa79f9bb4baa0876ede4a59c569fb3fd815e5",
"size": "1362",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ruby",
"bytes": "70902"
}
],
"symlink_target": ""
} |
{% load i18n thumbnail sekizai_tags %}
{% addtoblock "css" %}<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}cmsplugin_filer_folder/css/slideshow.css" media="screen, projection" />{% endaddtoblock "css" %}
{% addtoblock "js" %}<script type="text/javascript" src="{{ STATIC_URL }}cmsplugin_filer_folder/js/jquery.cycle.lite-1.0.js"></script>{% endaddtoblock "js" %}
{% addtoblock "js" %}
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function ($) {
$('.cmsplugin_filer_folder_slideshow').cycle({
fx: 'fade'
});
});
//]]>
</script>
{% endaddtoblock %}
{% firstof object.title object.folder.name %}
{% if object.view_option == "list" %}
<div class="cmsplugin_filer_folder_list" id="folder_{{ instance.id }}">
<!--The files should go there -->
{% if folder_folders %}
<p>{% trans "Folders" %}</p>
<ul>
{% for folder in folder_folders %}
<li>{{ folder }}</li>
{% endfor %}
</ul>
{% endif %}
{% if folder_files %}
<p>{% trans "Files" %}</p>
<ul>
{% for files in folder_files %}
<li>{{ files }}</li>
{% endfor %}
</ul>
{% endif %}
{% if folder_images %}
<p>{% trans "Images" %}</p>
<ul>
{% for image in folder_images %}
<li><img src="{% thumbnail image.file 32x32 crop="True" upscale="True" %}" width="32" height="32" alt="{{ image.label }}"></li>
{% endfor %}
</ul>
{% endif %}
</div>
{% else %}
<!-- start: slideshow -->
<div class="cmsplugin_filer_folder_slideshow" id="folder_{{ object.id }}">
{% for image in folder_images %}
<img src="{% thumbnail image.file 200x200 crop="True" upscale="True" %}">
{% endfor %}
</div>
<!-- end: gallery -->
{% endif %}
| {
"content_hash": "f3392592c569861ed0ab59b2f478ec35",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 179,
"avg_line_length": 34.70909090909091,
"alnum_prop": 0.5133577789418544,
"repo_name": "jschneier/cmsplugin-filer",
"id": "119711c9c97251637e732275791fce9280bb90f0",
"size": "1909",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "cmsplugin_filer_folder/templates/cmsplugin_filer_folder/plugins/folder/default.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "157"
},
{
"name": "HTML",
"bytes": "8144"
},
{
"name": "Python",
"bytes": "544506"
},
{
"name": "Shell",
"bytes": "189"
}
],
"symlink_target": ""
} |
void DumpHex(void *pData, int byteLen) {
if(byteLen <= 0) return;
uint8_t *head = (uint8_t*) pData;
printf("The %d bytes starting at 0x%"PRIxPTR " are:", byteLen, (uintptr_t)pData);
for(int ind = 0; ind < byteLen; ++ind) {
printf(" %02" PRIx8, head[ind]);
}
printf("\n");
}
int main(int argc, char **argv) {
char charVal = '0';
int32_t intVal = 1;
float floatVal = 1.0;
double doubleVal = 1.0;
typedef struct {
char charVal;
int32_t intVal;
float floatVal;
double doubleVal;
} Ex2Struct;
Ex2Struct tmp = {'0', 1, 1.0, 1.0};
unsigned char buf[sizeof(tmp)];
memset(buf, 0, sizeof(buf));
size_t offset = 0;
memcpy(buf + offset, &tmp.charVal, sizeof(tmp.charVal));
offset += sizeof(tmp.charVal);
memcpy(buf + offset, &tmp.intVal, sizeof(tmp.intVal));
offset += sizeof(tmp.intVal);
memcpy(buf + offset, &tmp.floatVal, sizeof(tmp.floatVal));
offset += sizeof(tmp.floatVal);
memcpy(buf + offset, &tmp.doubleVal, sizeof(tmp.doubleVal));
DumpHex(&charVal, sizeof(char));
DumpHex(&intVal, sizeof(int32_t));
DumpHex(&floatVal, sizeof(float));
DumpHex(&doubleVal, sizeof(double));
DumpHex(&buf, sizeof(tmp));
return EXIT_SUCCESS;
}
| {
"content_hash": "8efe91dbc1eef48bb66f3c9063262168",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 82,
"avg_line_length": 24.395833333333332,
"alnum_prop": 0.659265584970111,
"repo_name": "tavaresdong/courses-notes",
"id": "c96f20571762bc3723fc8ef5afb290bfaa65f0c3",
"size": "1273",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "uw_cse333/exs/ex2/ex2.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Charity",
"bytes": "1424511"
},
{
"name": "Erlang",
"bytes": "2777606"
},
{
"name": "HTML",
"bytes": "11932"
},
{
"name": "Java",
"bytes": "91253"
},
{
"name": "Python",
"bytes": "132602"
},
{
"name": "Shell",
"bytes": "314"
}
],
"symlink_target": ""
} |
package org.springframework.messaging.simp;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.AbstractMessageCondition;
import org.springframework.util.Assert;
/**
* {@code MessageCondition} that matches by the message type obtained via
* {@link SimpMessageHeaderAccessor#getMessageType(Map)}.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class SimpMessageTypeMessageCondition extends AbstractMessageCondition<SimpMessageTypeMessageCondition> {
public static final SimpMessageTypeMessageCondition MESSAGE =
new SimpMessageTypeMessageCondition(SimpMessageType.MESSAGE);
public static final SimpMessageTypeMessageCondition SUBSCRIBE =
new SimpMessageTypeMessageCondition(SimpMessageType.SUBSCRIBE);
private final SimpMessageType messageType;
/**
* A constructor accepting a message type.
* @param messageType the message type to match messages to
*/
public SimpMessageTypeMessageCondition(SimpMessageType messageType) {
Assert.notNull(messageType, "MessageType must not be null");
this.messageType = messageType;
}
public SimpMessageType getMessageType() {
return this.messageType;
}
@Override
protected Collection<?> getContent() {
return Collections.singletonList(this.messageType);
}
@Override
protected String getToStringInfix() {
return " || ";
}
@Override
public SimpMessageTypeMessageCondition combine(SimpMessageTypeMessageCondition other) {
return other;
}
@Override
@Nullable
public SimpMessageTypeMessageCondition getMatchingCondition(Message<?> message) {
SimpMessageType actual = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
return (actual != null && actual.equals(this.messageType) ? this : null);
}
@Override
public int compareTo(SimpMessageTypeMessageCondition other, Message<?> message) {
Object actual = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
if (actual != null) {
if (actual.equals(this.messageType) && actual.equals(other.getMessageType())) {
return 0;
}
else if (actual.equals(this.messageType)) {
return -1;
}
else if (actual.equals(other.getMessageType())) {
return 1;
}
}
return 0;
}
}
| {
"content_hash": "1fca801bef4fe74f0b6091e2e7e2ce16",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 112,
"avg_line_length": 27.197674418604652,
"alnum_prop": 0.7725523728088927,
"repo_name": "spring-projects/spring-framework",
"id": "522cd82fc7005c25df3c1b4a5850ceec949ac1d9",
"size": "2960",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageTypeMessageCondition.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "32003"
},
{
"name": "CSS",
"bytes": "1019"
},
{
"name": "Dockerfile",
"bytes": "257"
},
{
"name": "FreeMarker",
"bytes": "30820"
},
{
"name": "Groovy",
"bytes": "6902"
},
{
"name": "HTML",
"bytes": "1203"
},
{
"name": "Java",
"bytes": "43939386"
},
{
"name": "JavaScript",
"bytes": "280"
},
{
"name": "Kotlin",
"bytes": "571613"
},
{
"name": "PLpgSQL",
"bytes": "305"
},
{
"name": "Python",
"bytes": "254"
},
{
"name": "Ruby",
"bytes": "1060"
},
{
"name": "Shell",
"bytes": "5374"
},
{
"name": "Smarty",
"bytes": "700"
},
{
"name": "XSLT",
"bytes": "2945"
}
],
"symlink_target": ""
} |
package com.danielcotter.officeprank.web.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class EncryptionUtil {
public static String shaHash(String message)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] hash = new byte[0];
hash = md.digest(message.getBytes());
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
}
| {
"content_hash": "71493290076886424af17eee4a0b0f78",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 58,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.7368421052631579,
"repo_name": "danielcdev/officeprank-web",
"id": "18922b7ef82d2b5b1bfca8f97ef05c553e7ed3d2",
"size": "532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/danielcotter/officeprank/web/util/EncryptionUtil.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "10899"
}
],
"symlink_target": ""
} |
package com.jetbrains.python.psi;
import com.jetbrains.python.toolbox.Substring;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author vlan
*/
public interface StructuredDocString {
String getSummary();
String getDescription(); // for formatter
@NotNull
List<String> getParameters();
/**
* @return all names of parameters mentioned in the docstring as substrings.
*/
@NotNull
List<Substring> getParameterSubstrings();
/**
* @param paramName {@code null} can be used for unnamed parameters descriptors, e.g. in docstring following class attribute
*/
@Nullable
String getParamType(@Nullable String paramName);
/**
* @param paramName {@code null} can be used for unnamed parameters descriptors, e.g. in docstring following class attribute
*/
@Nullable
Substring getParamTypeSubstring(@Nullable String paramName);
/**
* @param paramName {@code null} can be used for unnamed parameters descriptors, e.g. in docstring following class attribute
*/
@Nullable
String getParamDescription(@Nullable String paramName);
/**
* Keyword arguments are those arguments that usually don't exist in function signature,
* but are passed e.g. via {@code **kwargs} mechanism.
*/
@NotNull
List<String> getKeywordArguments();
@NotNull
List<Substring> getKeywordArgumentSubstrings();
// getKeywordArgumentType(name)
// getKeywordArgumentTypeString(name)
@Nullable
String getKeywordArgumentDescription(@Nullable String paramName);
@Nullable
String getReturnType();
@Nullable
Substring getReturnTypeSubstring();
@Nullable
String getReturnDescription(); // for formatter
@NotNull
List<String> getRaisedExceptions(); // for formatter
@Nullable
String getRaisedExceptionDescription(@Nullable String exceptionName); // for formatter
// getAttributes
// getAttributeSubstrings
// getAttributeType(name)
// getAttributeTypeSubstring(name)
@Nullable
String getAttributeDescription(); // for formatter
// Tags related methods
}
| {
"content_hash": "bd342fdb8d687bfe50866171f0bec2cf",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 126,
"avg_line_length": 26.897435897435898,
"alnum_prop": 0.7402287893231649,
"repo_name": "nicolargo/intellij-community",
"id": "748fd22de426a9203fe7478dbece06aad88504b6",
"size": "2698",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "python/psi-api/src/com/jetbrains/python/psi/StructuredDocString.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "63518"
},
{
"name": "C",
"bytes": "214180"
},
{
"name": "C#",
"bytes": "1538"
},
{
"name": "C++",
"bytes": "190455"
},
{
"name": "CSS",
"bytes": "111474"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Cucumber",
"bytes": "14382"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "FLUX",
"bytes": "57"
},
{
"name": "Groff",
"bytes": "35232"
},
{
"name": "Groovy",
"bytes": "2271658"
},
{
"name": "HTML",
"bytes": "1737110"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "150041484"
},
{
"name": "JavaScript",
"bytes": "125292"
},
{
"name": "Kotlin",
"bytes": "914570"
},
{
"name": "Lex",
"bytes": "166177"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "87464"
},
{
"name": "Objective-C",
"bytes": "28878"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6570"
},
{
"name": "Python",
"bytes": "21639462"
},
{
"name": "Ruby",
"bytes": "1213"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "63606"
},
{
"name": "Smalltalk",
"bytes": "64"
},
{
"name": "TeX",
"bytes": "60798"
},
{
"name": "TypeScript",
"bytes": "6152"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
#include "../kd_library.h"
/*
// xmPlatformGetTimeUST : Get the current unadjusted system time in platform specific.
KDust xmPlatformGetTimeUST ( KDvoid )
{
long long ust = 0;
SystemTime::GetTicks ( ust );
ust *= 1000000LL;
return (KDust) ust;
}
// xmPlatformUSTAtEpoch : Get the UST corresponding to KDtime 0 in platform specific.
KDust xmPlatformUSTAtEpoch ( KDvoid )
{
return xmPlatformGetTimeUST ( );
}
KDint xmBbGettimeofday ( struct timeval* tv, struct timezone* tz )
{
return 0;
}
// xmPlatformSleep : The function sleep gives a simple way to make the program wait for a short interval.
KDvoid xmPlatformSleep ( KDust ust )
{
Thread::Sleep ( KD_N2M_SEC ( ust ) );
}
*/
| {
"content_hash": "1c3bedc0ac13cfeacb540b87f6acf64f",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 105,
"avg_line_length": 21.65625,
"alnum_prop": 0.7171717171717171,
"repo_name": "mcodegeeks/OpenKODE-Framework",
"id": "c1d45401949888ef7c360c92909cbd044cd67a41",
"size": "2070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "01_Develop/libXMKode/Source/BlackBerry/bb_time.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1292072"
},
{
"name": "C",
"bytes": "36964031"
},
{
"name": "C++",
"bytes": "86498790"
},
{
"name": "Cuda",
"bytes": "1295615"
},
{
"name": "GLSL",
"bytes": "244633"
},
{
"name": "Gnuplot",
"bytes": "1174"
},
{
"name": "HLSL",
"bytes": "153769"
},
{
"name": "HTML",
"bytes": "9848"
},
{
"name": "JavaScript",
"bytes": "1610772"
},
{
"name": "Lex",
"bytes": "83193"
},
{
"name": "Limbo",
"bytes": "2257"
},
{
"name": "Logos",
"bytes": "5463744"
},
{
"name": "Lua",
"bytes": "1094038"
},
{
"name": "Makefile",
"bytes": "69477"
},
{
"name": "Objective-C",
"bytes": "502497"
},
{
"name": "Objective-C++",
"bytes": "211576"
},
{
"name": "Perl",
"bytes": "12636"
},
{
"name": "Python",
"bytes": "170481"
},
{
"name": "Shell",
"bytes": "149"
},
{
"name": "Yacc",
"bytes": "40113"
}
],
"symlink_target": ""
} |
package com.twitter.finatra.http.tests.integration.doeverything.main.services
import com.google.inject.assistedinject.Assisted
import com.twitter.inject.annotations.Flag
import javax.inject.{Inject, Named}
import com.twitter.util.Duration
class ComplexService @Inject() (
exampleService: DoEverythingService,
defaultString: String,
@Named("str1") string1: String,
@Named("str2") string2: String,
defaultInt: Int,
@Flag("moduleDuration") duration1: Duration,
@Assisted name: String) {
assert(defaultString == "" || defaultString == "default string")
assert(string1 != null)
assert(string2 != null)
assert(defaultInt == 0 || defaultInt == 11)
def execute: String = exampleService.doit + " " + name + " " + duration1.inMillis
}
| {
"content_hash": "f9f8ea8fb711f9a0d8f413339b3998d0",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 83,
"avg_line_length": 32.73913043478261,
"alnum_prop": 0.7357237715803453,
"repo_name": "twitter/finatra",
"id": "d4e2c3910d53af8b331e4ba77f9d1d300138da52",
"size": "753",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "http-server/src/test/scala/com/twitter/finatra/http/tests/integration/doeverything/main/services/ComplexService.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "24"
},
{
"name": "Java",
"bytes": "124308"
},
{
"name": "Mustache",
"bytes": "958"
},
{
"name": "Scala",
"bytes": "2034894"
},
{
"name": "Shell",
"bytes": "1823"
},
{
"name": "Starlark",
"bytes": "160425"
},
{
"name": "Thrift",
"bytes": "5089"
}
],
"symlink_target": ""
} |
#import "IDEGroup.h"
@interface IDEGroup (InspectorProperties)
+ (id)keyPathsForValuesAffectingIdeInspectedIsNameEditable;
- (id)applicableInspectorsForCategory:(id)arg1 suggestion:(id)arg2;
- (BOOL)ideInspectedIsNameEditable;
- (id)ideInspectedRelativeLocationContainingFolderPlaceholder;
- (id)ideInspectedRelativeLocationPlaceholder;
- (BOOL)ideInspectedRelativeLocationShouldChooseDirectory;
- (BOOL)ideInspectedRelativeLocationShouldChooseFile;
@end
| {
"content_hash": "515a40769e59796cc85d76a233b3321b",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 67,
"avg_line_length": 32.785714285714285,
"alnum_prop": 0.8540305010893247,
"repo_name": "alloy/AxeMode",
"id": "a78df109612f3c82837bee7e65f4e55a41aeafb5",
"size": "597",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "XcodeHeaders/IDEKit/IDEGroup-InspectorProperties.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2710"
},
{
"name": "C++",
"bytes": "7889"
},
{
"name": "Objective-C",
"bytes": "2840787"
}
],
"symlink_target": ""
} |
package com.assylias.jbloomberg;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertTrue;
@Test(groups = "requires-bloomberg")
public class UserEntitlementsResultParserTest {
private DefaultBloombergSession session = null;
@BeforeClass
public void beforeClass() throws BloombergException {
session = new DefaultBloombergSession();
session.start();
}
@AfterClass
public void afterClass() throws BloombergException {
if (session != null) {
session.stop();
}
}
@Test
public void testLookupEntitlements_InvalidUser() throws Exception {
UserEntitlementsRequestBuilder uerb = new UserEntitlementsRequestBuilder(1);
UserEntitlements entitlements = session.submit(uerb).get(2, TimeUnit.SECONDS);
assertTrue(entitlements.getEids().isEmpty());
}
}
| {
"content_hash": "f44968e7d57b47e53673f3074cfcd03f",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 86,
"avg_line_length": 28.571428571428573,
"alnum_prop": 0.72,
"repo_name": "assylias/jBloomberg",
"id": "17182d80c162e4bfe9b0a10d8fde7360a3cc0e1e",
"size": "1000",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/assylias/jbloomberg/UserEntitlementsResultParserTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "403260"
}
],
"symlink_target": ""
} |
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_NO_IOSTREAM
// This file should not compile, if it does then
// BOOST_NO_IOSTREAM should not be defined.
// See file boost_no_iostream.ipp for details
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifdef BOOST_NO_IOSTREAM
#include "boost_no_iostream.ipp"
#else
#error "this file should not compile"
#endif
int main( int, char *[] )
{
return boost_no_iostream::test();
}
| {
"content_hash": "a1e540a30bac7dcd8a6ce533107efdd1",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 69,
"avg_line_length": 23.428571428571427,
"alnum_prop": 0.6920731707317073,
"repo_name": "Franky666/programmiersprachen-raytracer",
"id": "c2cac7efcf075f9fa1e66499684e620fe62defb7",
"size": "998",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "external/boost_1_59_0/libs/config/test/no_iostream_fail.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "905071"
},
{
"name": "C++",
"bytes": "46207"
},
{
"name": "CMake",
"bytes": "4419"
}
],
"symlink_target": ""
} |
//Dependencies
#include "stm32f2xx.h"
#include "stm32f2xx_gpio.h"
#include "stm32f2xx_rcc.h"
#include "core/net.h"
#include "ext_int_driver.h"
#include "debug.h"
/**
* @brief External interrupt line driver
**/
const ExtIntDriver extIntDriver =
{
extIntInit,
extIntEnableIrq,
extIntDisableIrq
};
/**
* @brief EXTI configuration
* @return Error code
**/
error_t extIntInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
//Enable GPIOB clock
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
//Enable SYSCFG clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
//Configure PB14 pin as an input
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//Connect EXTI Line14 to PB14 pin
SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOB, EXTI_PinSource14);
//Configure EXTI Line14
EXTI_InitStructure.EXTI_Line = EXTI_Line14;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
//Configure EXTI15_10 interrupt priority
NVIC_SetPriority(EXTI15_10_IRQn, NVIC_EncodePriority(3, 15, 0));
//Successful processing
return NO_ERROR;
}
/**
* @brief Enable external interrupts
**/
void extIntEnableIrq(void)
{
//Enable EXTI15_10 interrupt
NVIC_EnableIRQ(EXTI15_10_IRQn);
}
/**
* @brief Disable external interrupts
**/
void extIntDisableIrq(void)
{
//Disable EXTI15_10 interrupt
NVIC_DisableIRQ(EXTI15_10_IRQn);
}
/**
* @brief External interrupt handler
**/
void EXTI15_10_IRQHandler(void)
{
bool_t flag;
NetInterface *interface;
//Enter interrupt service routine
osEnterIsr();
//Point to the structure describing the network interface
interface = &netInterface[0];
//This flag will be set if a higher priority task must be woken
flag = FALSE;
//Check interrupt status
if(EXTI_GetITStatus(EXTI_Line14) != RESET)
{
//Clear interrupt flag
EXTI_ClearITPendingBit(EXTI_Line14);
//A PHY event is pending...
interface->phyEvent = TRUE;
//Notify the user that the link state has changed
flag = osSetEventFromIsr(&interface->nicRxEvent);
}
//Leave interrupt service routine
osExitIsr(flag);
}
| {
"content_hash": "d8b25da960651698131081c82b0c7b87",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 67,
"avg_line_length": 21.417391304347827,
"alnum_prop": 0.706049533089728,
"repo_name": "miragecentury/M2_SE_RTOS_Project",
"id": "97f0e35d735a9d085bee90fa55ec9cb974d8f712",
"size": "3429",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "Project/LPC1549_Keil/CycloneTCP_SSL_Crypto_Open_1_6_4/demo/st/stm3220g_eval/sntp_client_demo/src/ext_int_driver.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3487996"
},
{
"name": "Batchfile",
"bytes": "24092"
},
{
"name": "C",
"bytes": "84242987"
},
{
"name": "C++",
"bytes": "11815227"
},
{
"name": "CSS",
"bytes": "228804"
},
{
"name": "D",
"bytes": "102276"
},
{
"name": "HTML",
"bytes": "97193"
},
{
"name": "JavaScript",
"bytes": "233480"
},
{
"name": "Makefile",
"bytes": "3365112"
},
{
"name": "Objective-C",
"bytes": "46531"
},
{
"name": "Python",
"bytes": "3237"
},
{
"name": "Shell",
"bytes": "13510"
}
],
"symlink_target": ""
} |
#ifndef _ASM_ARM_MODULE_H
#define _ASM_ARM_MODULE_H
/*
* This file contains the arm architecture specific module code.
*/
#endif /* _ASM_ARM_MODULE_H */
| {
"content_hash": "315c1841d53aa0cea253ddbdebe6c3b6",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 64,
"avg_line_length": 22.285714285714285,
"alnum_prop": 0.6923076923076923,
"repo_name": "impedimentToProgress/UCI-BlueChip",
"id": "1157f178daec0c88062612c967941f2564999a00",
"size": "156",
"binary": false,
"copies": "108",
"ref": "refs/heads/master",
"path": "snapgear_linux/linux-2.6.21.1/include/asm-arm26/module.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AGS Script",
"bytes": "25338"
},
{
"name": "ASP",
"bytes": "4526"
},
{
"name": "Ada",
"bytes": "1075367"
},
{
"name": "Assembly",
"bytes": "2137017"
},
{
"name": "Awk",
"bytes": "133306"
},
{
"name": "Bison",
"bytes": "399484"
},
{
"name": "BlitzBasic",
"bytes": "101509"
},
{
"name": "C",
"bytes": "288543995"
},
{
"name": "C++",
"bytes": "7495614"
},
{
"name": "CSS",
"bytes": "2128"
},
{
"name": "Clojure",
"bytes": "3747"
},
{
"name": "Common Lisp",
"bytes": "239683"
},
{
"name": "Elixir",
"bytes": "790"
},
{
"name": "Emacs Lisp",
"bytes": "45827"
},
{
"name": "Erlang",
"bytes": "171340"
},
{
"name": "GAP",
"bytes": "3002"
},
{
"name": "Groff",
"bytes": "4517911"
},
{
"name": "Groovy",
"bytes": "26513"
},
{
"name": "HTML",
"bytes": "8141161"
},
{
"name": "Java",
"bytes": "481441"
},
{
"name": "JavaScript",
"bytes": "339345"
},
{
"name": "Logos",
"bytes": "16160"
},
{
"name": "M",
"bytes": "2443"
},
{
"name": "Makefile",
"bytes": "1309237"
},
{
"name": "Max",
"bytes": "3812"
},
{
"name": "Nemerle",
"bytes": "966202"
},
{
"name": "Objective-C",
"bytes": "376270"
},
{
"name": "OpenEdge ABL",
"bytes": "69290"
},
{
"name": "PHP",
"bytes": "11533"
},
{
"name": "PLSQL",
"bytes": "8464"
},
{
"name": "Pascal",
"bytes": "54420"
},
{
"name": "Perl",
"bytes": "6498220"
},
{
"name": "Perl6",
"bytes": "4155"
},
{
"name": "Prolog",
"bytes": "62574"
},
{
"name": "Python",
"bytes": "24287"
},
{
"name": "QMake",
"bytes": "8619"
},
{
"name": "R",
"bytes": "25999"
},
{
"name": "Ruby",
"bytes": "31311"
},
{
"name": "SAS",
"bytes": "15573"
},
{
"name": "Scala",
"bytes": "1506"
},
{
"name": "Scilab",
"bytes": "23534"
},
{
"name": "Shell",
"bytes": "6951414"
},
{
"name": "Smalltalk",
"bytes": "2661"
},
{
"name": "Stata",
"bytes": "7930"
},
{
"name": "Tcl",
"bytes": "1518344"
},
{
"name": "TeX",
"bytes": "1574651"
},
{
"name": "UnrealScript",
"bytes": "20822"
},
{
"name": "VHDL",
"bytes": "37384578"
},
{
"name": "Verilog",
"bytes": "376626"
},
{
"name": "Visual Basic",
"bytes": "180"
},
{
"name": "XS",
"bytes": "24500"
},
{
"name": "XSLT",
"bytes": "5872"
}
],
"symlink_target": ""
} |
layout: page
title: Fungsi
category: basics
order: 6
lang: my
---
Di dalam Elixir dan kebanyakan bahasa aturcara kefungsian, fungsi adalah rakyat kelas pertama. Kita akan belajar mengenai jenis-jenis fungsi di dalam Elixir, apa yang menyebabkan mereka berbeza, dan bagaimana menggunakan mereka.
{% include toc.html %}
## Fungsi Tanpa Nama
Seperti yang dibayangkan oleh namanya, fungsi tanpa nama(anonymous function) adalah fungsi yang tidak mempunyai nama. Sebagaimana kita lihat di dalam pelajaran `Enum`, mereka selalunya dihantar kepada fungsi-fungsi lain. Untuk mentakrifkan satu fungsi tanpa nama di dalam Elixir kita perlukan katakunci `fn` dan `end`. Di antara kedua katakunci ini kita boleh mentakrifkan beberapa parameter dan badan fungsi yang dipisahkan oleh `->`.
Mari lihat satu contoh mudah:
```elixir
iex> sum = fn (a, b) -> a + b end
iex> sum.(2, 3)
5
```
### Shorthand &
Oleh kerana fungsi tanpa nama amat lazim digunakan di dalam Elixir terdapat shorthand untuknya:
```elixir
iex> sum = &(&1 + &2)
iex> sum.(2, 3)
5
```
Sebagaimana tekaan anda, di dalam versi shorthand tersebut parameter kita disediakan kepada kita sebagai `&1`, `&2`, `&3`, dan seterusnya.
## Pemadanan Corak
Pemadanan corak(pattern matching) bukan hanya terhad kepada pembolehubah di dalam Elixir, ia juga boleh diaplikasikan kepada pengenalan fungsi(function signature) sebagaimana yang akan kita lihat di dalam bahagian ini.
Elixir menggunakan pemadanan corak untuk memastikan mana satu kumpulan parameter yang padan dan memanggil badan fungsi yang berkaitan:
```elixir
iex> handle_result = fn
...> {:ok, result} -> IO.puts "Handling result..."
...> {:error} -> IO.puts "An error has occurred!"
...> end
iex> some_result = 1
iex> handle_result.({:ok, some_result})
Handling result...
iex> handle_result.({:error})
An error has occurred!
```
## Fungsi Bernama
Kita boleh takrifkan fungsi-fungsi dengan nama supaya boleh dirujuk kemudian, fungsi-fungsi bernama ini ditakrifkan dengan katakunci `def` di dalam satu modul. Kita akan belajar lebih lanjut mengenai Modul di dalam pelajaran-pelajaran selepas ini, untuk masa sekarang kita akan fokus hanya kepada fungsi bernama.
Fungsi-fungsi yang ditakrifkan di dalam satu modul adalah tersedia untuk digunakan oleh modul-modul lain, ini adalah blok binaan penting di dalam Elixir:
```elixir
defmodule Greeter do
def hello(name) do
"Hello, " <> name
end
end
iex> Greeter.hello("Sean")
"Hello, Sean"
```
Jika fungsi kita hanya mengandungi satu baris, kita boleh pendekkan lagi dengan `do:`:
```elixir
defmodule Greeter do
def hello(name), do: "Hello, " <> name
end
```
Bersedia dengan pengetahuan mengenai pemadanan corak, kita akan meneroka rekursi menggunakan fungsi-fungsi bernama:
```elixir
defmodule Length do
def of([]), do: 0
def of([_|t]), do: 1 + of(t)
end
iex> Length.of []
0
iex> Length.of [1, 2, 3]
3
```
### Fungsi Terlindung
Jika kita tidak mahu modul-modul lain untuk mengakses sesatu fungsi, kita boleh gunakan fungsi-fungsi terlindung(private functions), yang hanya boleh dipanggil dari dalam modul mereka sahaja. Kita takrifkan fungsi terlindung di dalam Elixir dengan `defp`:
```elixir
defmodule Greeter do
def hello(name), do: phrase <> name
defp phrase, do: "Hello, "
end
iex> Greeter.hello("Sean")
"Hello, Sean"
iex> Greeter.phrase
** (UndefinedFunctionError) undefined function: Greeter.phrase/0
Greeter.phrase()
```
### Klausa Kawalan
Kita telah melihat sepintas lalu mengenai klausa kawalan(guard) di dalam bahagian [Control Structures](../control-structures), sekarang kita akan melihat bagaimana kita boleh aplikasikan mereka kepada fungsi-fungsi bernama. Sebaik sahaja Elixir berjaya memadankan corak satu fungsi, apa-apa klausa kawalan pada fungsi tersebut akan diuji.
Di dalam contoh di bawah kita ada dua fungsi yang mempunyai pengenalan yang sama, kita bergantung kepada klausa kawalan untuk menentukan yang mana satu akan digunakan berdasarkan kepada jenis argumen:
```elixir
defmodule Greeter do
def hello(names) when is_list(names) do
names
|> Enum.join(", ")
|> hello
end
def hello(name) when is_binary(name) do
phrase <> name
end
defp phrase, do: "Hello, "
end
iex> Greeter.hello ["Sean", "Steve"]
"Hello, Sean, Steve"
```
### Argumen Lalai
Jika kita mahukan satu nilai lalai(default value) untuk satu argumen kita gunakan sintaks `argumen \\ nilai`:
```elixir
defmodule Greeter do
def hello(name, country \\ "en") do
phrase(country) <> name
end
defp phrase("en"), do: "Hello, "
defp phrase("es"), do: "Hola, "
end
iex> Greeter.hello("Sean", "en")
"Hello, Sean"
iex> Greeter.hello("Sean")
"Hello, Sean"
iex> Greeter.hello("Sean", "es")
"Hola, Sean"
```
Jika kita gabungkan contoh klausa kawalan dengan argumen lalai(default argument), kita akan menemui satu isu. Mari lihat bagaimana rupa isu tersebut:
```elixir
defmodule Greeter do
def hello(names, country \\ "en") when is_list(names) do
names
|> Enum.join(", ")
|> hello(country)
end
def hello(name, country \\ "en") when is_binary(name) do
phrase(country) <> name
end
defp phrase("en"), do: "Hello, "
defp phrase("es"), do: "Hola, "
end
** (CompileError) def hello/2 has default values and multiple clauses, define a function head with the defaults
```
Elixir tidak sukakan argumen lalai di dalam beberapa fungsi-fungsi yang berjaya dipadankan, ia boleh jadi mengelirukan. Untuk mengatasi keadaan ini kita tambahkan satu kepala fungsi bersama argumen lalai kita:
```elixir
defmodule Greeter do
def hello(names, country \\ "en")
def hello(names, country) when is_list(names) do
names
|> Enum.join(", ")
|> hello(country)
end
def hello(name, country) when is_binary(name) do
phrase(country) <> name
end
defp phrase("en"), do: "Hello, "
defp phrase("es"), do: "Hola, "
end
iex> Greeter.hello ["Sean", "Steve"]
"Hello, Sean, Steve"
iex> Greeter.hello ["Sean", "Steve"], "es"
"Hola, Sean, Steve"
```
| {
"content_hash": "befc0ed0bfb310a3f3f2aab9612bbc4f",
"timestamp": "",
"source": "github",
"line_count": 208,
"max_line_length": 438,
"avg_line_length": 28.89903846153846,
"alnum_prop": 0.7266677757444685,
"repo_name": "ElixirVietnam/elixir-school",
"id": "5d0f56eb031335428843cc04307beeafd17ae136",
"size": "6015",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "my/lessons/basics/functions.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45639"
},
{
"name": "HTML",
"bytes": "8386"
},
{
"name": "JavaScript",
"bytes": "4281"
},
{
"name": "Ruby",
"bytes": "2107"
}
],
"symlink_target": ""
} |
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-event-loop/EventLoop.h"
#include "jerryscript-mbed-library-registry/wrap_tools.h"
#include "mbed.h"
/**
* InterruptIn#rise (native JavaScript method)
*
* Register a rise callback for an InterruptIn
*
* @param cb Callback function, or null to detach previously attached callback.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, rise) {
CHECK_ARGUMENT_COUNT(InterruptIn, rise, (args_count == 1));
// Detach the rise callback when InterruptIn::rise(null) is called
if (jerry_value_is_null(args[1])) {
uintptr_t native_handle;
jerry_get_object_native_handle(this_obj, &native_handle);
InterruptIn *this_interruptin = (InterruptIn*) native_handle;
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_rise");
jerry_value_t cb_func = jerry_get_property(this_obj, property_name);
jerry_release_value(property_name);
// Only drop the callback if it exists
if (jerry_value_is_function(cb_func)) {
// Ensure that the EventLoop frees memory used by the callback.
mbed::js::EventLoop::getInstance().dropCallback(cb_func);
}
this_interruptin->rise(0);
return jerry_create_undefined();
}
// Assuming we actually have a callback now...
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, rise, 0, function);
uintptr_t native_handle;
jerry_get_object_native_handle(this_obj, &native_handle);
InterruptIn *this_interruptin = reinterpret_cast<InterruptIn*>(native_handle);
jerry_value_t f = args[0];
// Pass the function to EventLoop.
mbed::Callback<void()> cb = mbed::js::EventLoop::getInstance().wrapFunction(f);
this_interruptin->rise(cb);
// Keep track of our callback internally.
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_rise");
jerry_set_property(this_obj, property_name, f);
jerry_release_value(property_name);
return jerry_create_undefined();
}
/**
* InterruptIn#fall (native JavaScript method)
*
* Register a fall callback for an InterruptIn
*
* @param cb Callback function, or null to detach previously attached callback.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, fall) {
CHECK_ARGUMENT_COUNT(InterruptIn, fall, (args_count == 1));
// Detach the fall callback when InterruptIn::fall(null) is called
if (jerry_value_is_null(args[1])) {
uintptr_t native_handle;
jerry_get_object_native_handle(this_obj, &native_handle);
InterruptIn *this_interruptin = (InterruptIn*) native_handle;
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_fall");
jerry_value_t cb_func = jerry_get_property(this_obj, property_name);
jerry_release_value(property_name);
// Only drop the callback if it exists
if (jerry_value_is_function(cb_func)) {
// Ensure that the EventLoop frees memory used by the callback.
mbed::js::EventLoop::getInstance().dropCallback(cb_func);
}
this_interruptin->fall(0);
return jerry_create_undefined();
}
// Assuming we actually have a callback now...
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, fall, 0, function);
uintptr_t native_handle;
jerry_get_object_native_handle(this_obj, &native_handle);
InterruptIn *this_interruptin = reinterpret_cast<InterruptIn*>(native_handle);
jerry_value_t f = args[0];
// Pass the function to EventLoop.
mbed::Callback<void()> cb = mbed::js::EventLoop::getInstance().wrapFunction(f);
this_interruptin->fall(cb);
// Keep track of our callback internally.
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_fall");
jerry_set_property(this_obj, property_name, f);
jerry_release_value(property_name);
return jerry_create_undefined();
}
/**
* InterruptIn#mode (native JavaScript method)
*
* Set the mode of the InterruptIn pin.
*
* @param mode PullUp, PullDown, PullNone
*/
DECLARE_CLASS_FUNCTION(InterruptIn, mode) {
CHECK_ARGUMENT_COUNT(InterruptIn, mode, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, mode, 0, number);
uintptr_t native_handle;
jerry_get_object_native_handle(this_obj, &native_handle);
InterruptIn *native_ptr = reinterpret_cast<InterruptIn*>(native_handle);
int pull = jerry_get_number_value(args[0]);
native_ptr->mode((PinMode)pull);
return jerry_create_undefined();
}
/**
* InterruptIn#disable_irq (native JavaScript method)
*
* Disable IRQ. See InterruptIn.h in mbed-os sources for more details.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, disable_irq) {
CHECK_ARGUMENT_COUNT(InterruptIn, disable_irq, (args_count == 0));
uintptr_t native_handle;
jerry_get_object_native_handle(this_obj, &native_handle);
InterruptIn *native_ptr = reinterpret_cast<InterruptIn*>(native_handle);
native_ptr->disable_irq();
return jerry_create_undefined();
}
/**
* InterruptIn#enable_irq (native JavaScript method)
*
* Enable IRQ. See InterruptIn.h in mbed-os sources for more details.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, enable_irq) {
CHECK_ARGUMENT_COUNT(InterruptIn, enable_irq, (args_count == 0));
uintptr_t native_handle;
jerry_get_object_native_handle(this_obj, &native_handle);
InterruptIn *native_ptr = reinterpret_cast<InterruptIn*>(native_handle);
native_ptr->enable_irq();
return jerry_create_undefined();
}
/**
* InterruptIn#destructor
*
* Called if/when the InterruptIn object is GC'ed.
*/
void NAME_FOR_CLASS_NATIVE_DESTRUCTOR(InterruptIn) (uintptr_t handle) {
InterruptIn *native_ptr = reinterpret_cast<InterruptIn*>(handle);
native_ptr->rise(0);
native_ptr->fall(0);
delete native_ptr;
}
/**
* InterruptIn (native JavaScript constructor)
*
* @param pin PinName
*
* @returns JavaScript object wrapping InterruptIn native object
*/
DECLARE_CLASS_CONSTRUCTOR(InterruptIn) {
CHECK_ARGUMENT_COUNT(InterruptIn, __constructor, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, __constructor, 0, number);
int pin = jerry_get_number_value(args[0]);
uintptr_t native_handle = (uintptr_t)new InterruptIn((PinName)pin);
jerry_value_t js_object = jerry_create_object();
jerry_set_object_native_handle(js_object, native_handle, NAME_FOR_CLASS_NATIVE_DESTRUCTOR(InterruptIn));
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, rise);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, fall);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, mode);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, enable_irq);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, disable_irq);
return js_object;
}
| {
"content_hash": "cdcf98db9b05f637cef70d1747c1e7ca",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 108,
"avg_line_length": 33.01951219512195,
"alnum_prop": 0.6900576156005318,
"repo_name": "tilmannOSG/jerryscript",
"id": "dcdcf16cfca1931a291e110cae82a77a2b4b4ebf",
"size": "7363",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "targets/mbedos5/jerryscript-mbed/jerryscript-mbed-drivers/source/InterruptIn.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3812"
},
{
"name": "C",
"bytes": "2390168"
},
{
"name": "C++",
"bytes": "217022"
},
{
"name": "CMake",
"bytes": "28188"
},
{
"name": "JavaScript",
"bytes": "1449473"
},
{
"name": "Makefile",
"bytes": "12577"
},
{
"name": "Python",
"bytes": "20064"
},
{
"name": "Shell",
"bytes": "4371"
}
],
"symlink_target": ""
} |
package io.astefanutti.metrics.cdi.se;
import com.codahale.metrics.health.HealthCheckRegistry;
import io.astefanutti.metrics.cdi.MetricsExtension;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(Arquillian.class)
public class HealthCheckRegistryProducerMethodBeanTest {
@Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(JavaArchive.class)
// HealthCheck registry bean
.addClass(HealthCheckRegistryProducerMethodBean.class)
// Test bean
.addClass(HealthCheckBean.class)
// MetricsCDI Extension
.addPackage(MetricsExtension.class.getPackage())
// Bean archive deployment Descriptior
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Inject
private HealthCheckRegistry registry;
@Inject
private HealthCheckBean bean;
@Test
@InSequence(1)
public void healthCheckNotCalledYet() {
assertThat("HealthCheck is not registered correctly", registry.getNames(), contains("HealthCheckBean"));
assertThat("Execution hasn't occurred yet.", bean.getCheckCount(), is(equalTo(0l)));
}
@Test
@InSequence(2)
public void healthCheckInvoked() {
assertThat("HealthCheck is not registered correctly", registry.getNames(), contains("HealthCheckBean"));
registry.runHealthChecks();
assertThat("Execution count is incorrect.", bean.getCheckCount(), is(equalTo(1l)));
}
}
| {
"content_hash": "eebac771914d9466a909527224dd23c8",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 112,
"avg_line_length": 33.77049180327869,
"alnum_prop": 0.7325242718446602,
"repo_name": "astefanutti/metrics-cdi",
"id": "00fae7cd1db7c59368ca9464a5897be32030cd09",
"size": "2696",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "envs/se/src/test/java/io/astefanutti/metrics/cdi/se/HealthCheckRegistryProducerMethodBeanTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "333646"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "29705da59d7f30754c2f344e9a2defbe",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "52b088d083880c6cecea8dad71c54427d4e4dfdd",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Hydrophyllum/Hydrophyllum macrophyllum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package io.fabianterhorst.isometric.shapes;
import io.fabianterhorst.isometric.Path;
import io.fabianterhorst.isometric.Point;
import io.fabianterhorst.isometric.Shape;
/**
* Created by fabianterhorst on 02.04.17.
*/
public class Pyramid extends Shape {
public Pyramid(Point origin) {
this(origin, 1, 1, 1);
}
public Pyramid(Point origin, double dx, double dy, double dz) {
super();
Path[] paths = new Path[4];
/* Path parallel to the x-axis */
Path face1 = new Path(new Point[]{
origin,
new Point(origin.getX() + dx, origin.getY(), origin.getZ()),
new Point(origin.getX() + dx / 2.0, origin.getY() + dy / 2.0, origin.getZ() + dz)
});
/* Push the face, and its opposite face, by rotating around the Z-axis */
paths[0] = face1;
paths[1] = face1.rotateZ(origin.translate(dx / 2.0, dy / 2.0, 0), Math.PI);
/* Path parallel to the y-axis */
Path face2 = new Path(new Point[]{
origin,
new Point(origin.getX() + dx / 2, origin.getY() + dy / 2, origin.getZ() + dz),
new Point(origin.getX(), origin.getY() + dy, origin.getZ())
});
paths[2] = face2;
paths[3] = face2.rotateZ(origin.translate(dx / 2.0, dy / 2.0, 0), Math.PI);
setPaths(paths);
}
}
| {
"content_hash": "a7b0c6c41ec739959045c8574cb17d9b",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 97,
"avg_line_length": 32.857142857142854,
"alnum_prop": 0.5615942028985508,
"repo_name": "FabianTerhorst/Isometric",
"id": "c321e7f56ae8964538a1668938ce63df5a8e0bb8",
"size": "1380",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/src/main/java/io/fabianterhorst/isometric/shapes/Pyramid.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "76023"
},
{
"name": "Shell",
"bytes": "34"
}
],
"symlink_target": ""
} |
package com.whu.dailyexercise.activities;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.whu.dailyexercise.R;
import com.whu.dailyexercise.weatherinfo.GetAQI;
import com.whu.dailyexercise.weatherinfo.GetWeather;
import com.whu.dailyexercise.weatherinfo.ParseAQI;
import com.whu.dailyexercise.weatherinfo.ParseWeather;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class WeatherInfoActivity extends Activity {
private TextView weatherCity;
private TextView weatherTemperature;
private TextView weatherSpecific;
private TextView weatherWind;
private TextView weatherIndex;
private TextView airQuality;
private TextView weatherNowTemperature;
private RelativeLayout btn_back;
private String city="Î人ÊÐ";
private LocationClient mLocationClient = null;
private BDLocationListener myListener = new MyLocationListener();
private ProgressDialog mDialog;
private String isSuccess;
private ParseWeather b;
private ParseAQI d;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_info);
btn_back=(RelativeLayout) findViewById(R.id.top_left_bg);
weatherCity=(TextView)findViewById(R.id.weatherCity);
weatherTemperature=(TextView)findViewById(R.id.weatherTemperature);
weatherSpecific=(TextView)findViewById(R.id.weatherSpecific);
weatherWind=(TextView)findViewById(R.id.weatherWind);
weatherIndex=(TextView)findViewById(R.id.indexNumber);
airQuality=(TextView)findViewById(R.id.airqualityNumber);
weatherNowTemperature=(TextView)findViewById(R.id.weatherSSTemperature);
mDialog = new ProgressDialog(WeatherInfoActivity.this);
mDialog.setTitle("ͬ²½");
mDialog.setMessage("ÕýÔÚÇëÇó·þÎñÆ÷£¬ÇëÉÔºó...");
mDialog.show();
btn_back.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
WeatherInfoActivity.this.finish();
}
});
mLocationClient=new LocationClient(getApplicationContext());//ÉùÃ÷LocationClientÀà
mLocationClient.start();//¿ªÆô¶¨Î»
mLocationClient.registerLocationListener(myListener);//×¢²á¼àÌýÆ÷
/**
* ¶¨Î»·½Ê½µÄÉèÖÃ
*/
LocationClientOption option = new LocationClientOption();
option.setCoorType("bd09ll");//ÉèÖÃ×ø±êÀàÐÍ
option.setOpenGps(false);
option.setPriority(LocationClientOption.NetWorkFirst);
option.setLocationMode(LocationMode.Battery_Saving);
option.setIsNeedAddress(true);
mLocationClient.setLocOption(option);
if(mLocationClient!=null&&mLocationClient.isStarted())
{
mLocationClient.requestLocation();
}
else
{
Log.d("LocSDK4.1", "locClient is null or not started");
city="Î人ÊÐ";
}
Thread GetWeatherThread=new Thread(new GetWeatherThread());
GetWeatherThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.weather_info, menu);
return true;
}
class MyLocationListener implements BDLocationListener
{
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
if(location==null)
return;
if(location.getLocType()==BDLocation.TypeNetWorkLocation)
{
city=location.getCity();
}
else
{
city="Î人ÊÐ";
}
}
@Override
public void onReceivePoi(BDLocation location) {
// TODO Auto-generated method stub
}
}
Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch(msg.what)
{
case 0:mDialog.cancel();
weatherCity.setText(b.getCity());
weatherTemperature.setText(b.getNowDayTemperature());
weatherSpecific.setText(b.getNowDayWeather());
weatherWind.setText(b.getNowDayWind());
weatherIndex.setText(b.getUvIndex());
airQuality.setText("¿ÕÆøÖÊÁ¿£º"+d.getQuality());
Log.d("adsfas", "failture");
weatherNowTemperature.setText(b.getNewTemperature());
break;
}
}
};
class GetWeatherThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
GetWeather a=new GetWeather();
b=new ParseWeather(a.getRemoteInfo(city));
GetAQI c=new GetAQI();
d=new ParseAQI(c.getAQIDemo(city));
isSuccess="true";
Message msg = handler.obtainMessage();
if(isSuccess.equals("true"))
{
msg.what=0;
handler.sendMessage(msg);
}
}
}
}
| {
"content_hash": "23e0b89e8420d30cd0529d40123fbf4a",
"timestamp": "",
"source": "github",
"line_count": 190,
"max_line_length": 84,
"avg_line_length": 27.321052631578947,
"alnum_prop": 0.7108456944712002,
"repo_name": "liulin2012/DailyExercise",
"id": "345dc369faf2204b1c3c7ef91de99cd69f1b9fc2",
"size": "5191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DailyExerciseClient/src/com/whu/dailyexercise/activities/WeatherInfoActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1074"
},
{
"name": "Java",
"bytes": "458680"
}
],
"symlink_target": ""
} |
import {PartialObserver} from './Observer';
import {Operator} from './Operator';
import {Subscriber} from './Subscriber';
import {Subscription, AnonymousSubscription, TeardownLogic} from './Subscription';
import {root} from './util/root';
import {toSubscriber} from './util/toSubscriber';
import {IfObservable} from './observable/IfObservable';
import {ErrorObservable} from './observable/ErrorObservable';
import * as $$observable from 'symbol-observable';
export interface Subscribable<T> {
subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
error?: (error: any) => void,
complete?: () => void): AnonymousSubscription;
}
export type SubscribableOrPromise<T> = Subscribable<T> | Promise<T>;
export type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T>;
/**
* A representation of any set of values over any amount of time. This the most basic building block
* of RxJS.
*
* @class Observable<T>
*/
export class Observable<T> implements Subscribable<T> {
public _isScalar: boolean = false;
protected source: Observable<any>;
protected operator: Operator<any, T>;
/**
* @constructor
* @param {Function} subscribe the function that is called when the Observable is
* initially subscribed to. This function is given a Subscriber, to which new values
* can be `next`ed, or an `error` method can be called to raise an error, or
* `complete` can be called to notify of a successful completion.
*/
constructor(subscribe?: <R>(subscriber: Subscriber<R>) => TeardownLogic) {
if (subscribe) {
this._subscribe = subscribe;
}
}
// HACK: Since TypeScript inherits static properties too, we have to
// fight against TypeScript here so Subject can have a different static create signature
/**
* Creates a new cold Observable by calling the Observable constructor
* @static true
* @owner Observable
* @method create
* @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
* @return {Observable} a new cold observable
*/
static create: Function = <T>(subscribe?: <R>(subscriber: Subscriber<R>) => TeardownLogic) => {
return new Observable<T>(subscribe);
};
/**
* Creates a new Observable, with this Observable as the source, and the passed
* operator defined as the new observable's operator.
* @method lift
* @param {Operator} operator the operator defining the operation to take on the observable
* @return {Observable} a new observable with the Operator applied
*/
lift<R>(operator: Operator<T, R>): Observable<R> {
const observable = new Observable<R>();
observable.source = this;
observable.operator = operator;
return observable;
}
/**
* Registers handlers for handling emitted values, error and completions from the observable, and
* executes the observable's subscriber function, which will take action to set up the underlying data stream
* @method subscribe
* @param {PartialObserver|Function} observerOrNext (optional) either an observer defining all functions to be called,
* or the first of three possible handlers, which is the handler for each value emitted from the observable.
* @param {Function} error (optional) a handler for a terminal event resulting from an error. If no error handler is provided,
* the error will be thrown as unhandled
* @param {Function} complete (optional) a handler for a terminal event resulting from successful completion.
* @return {ISubscription} a subscription reference to the registered handlers
*/
subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
error?: (error: any) => void,
complete?: () => void): Subscription {
const { operator } = this;
const sink = toSubscriber(observerOrNext, error, complete);
if (operator) {
operator.call(sink, this);
} else {
sink.add(this._subscribe(sink));
}
if (sink.syncErrorThrowable) {
sink.syncErrorThrowable = false;
if (sink.syncErrorThrown) {
throw sink.syncErrorValue;
}
}
return sink;
}
/**
* @method forEach
* @param {Function} next a handler for each value emitted by the observable
* @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
* @return {Promise} a promise that either resolves on observable completion or
* rejects with the handled error
*/
forEach(next: (value: T) => void, PromiseCtor?: typeof Promise): Promise<void> {
if (!PromiseCtor) {
if (root.Rx && root.Rx.config && root.Rx.config.Promise) {
PromiseCtor = root.Rx.config.Promise;
} else if (root.Promise) {
PromiseCtor = root.Promise;
}
}
if (!PromiseCtor) {
throw new Error('no Promise impl found');
}
return new PromiseCtor<void>((resolve, reject) => {
const subscription = this.subscribe((value) => {
if (subscription) {
// if there is a subscription, then we can surmise
// the next handling is asynchronous. Any errors thrown
// need to be rejected explicitly and unsubscribe must be
// called manually
try {
next(value);
} catch (err) {
reject(err);
subscription.unsubscribe();
}
} else {
// if there is NO subscription, then we're getting a nexted
// value synchronously during subscription. We can just call it.
// If it errors, Observable's `subscribe` imple will ensure the
// unsubscription logic is called, then synchronously rethrow the error.
// After that, Promise will trap the error and send it
// down the rejection path.
next(value);
}
}, reject, resolve);
});
}
protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {
return this.source.subscribe(subscriber);
}
// `if` and `throw` are special snow flakes, the compiler sees them as reserved words
static if: typeof IfObservable.create;
static throw: typeof ErrorObservable.create;
/**
* An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
* @method Symbol.observable
* @return {Observable} this instance of the observable
*/
[$$observable]() {
return this;
}
}
| {
"content_hash": "020f365da77d80c64dee43801b80f291",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 128,
"avg_line_length": 37.71764705882353,
"alnum_prop": 0.674516531503431,
"repo_name": "tzerb/Learning",
"id": "1a256e6681bebb8353d92fd627718a12a940c0dc",
"size": "6412",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebApplication3/src/WebApplication3/jspm_packages/npm/rxjs@5.0.0-beta.9/src/Observable.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "315"
},
{
"name": "Batchfile",
"bytes": "215"
},
{
"name": "C#",
"bytes": "830980"
},
{
"name": "CSS",
"bytes": "20573"
},
{
"name": "Dart",
"bytes": "150305"
},
{
"name": "HTML",
"bytes": "312358"
},
{
"name": "JavaScript",
"bytes": "30051708"
},
{
"name": "Makefile",
"bytes": "194"
},
{
"name": "TypeScript",
"bytes": "2492312"
}
],
"symlink_target": ""
} |
static Animation* prv_create_bump_settle_animation(Layer *layer);
static Animation* prv_create_slide_settle_animation(Layer *layer);
static int prv_get_pixels_for_bump_settle(int anim_percent_complete) {
if (anim_percent_complete) {
return SETTLE_HEIGHT_DIFF - ((SETTLE_HEIGHT_DIFF * anim_percent_complete) / 100);
} else {
return 0;
}
}
static int prv_get_font_top_padding(GFont font) {
if (font == fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)) {
return 10;
} else if (font == fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD)) {
return 10;
} else {
return 0;
}
}
static int prv_get_y_offset_which_vertically_centers_font(GFont font, int height) {
int font_height = 0;
int font_top_padding = prv_get_font_top_padding(font);
if (font == fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)) {
font_height = 18;
} else if (font == fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD)) {
font_height = 14;
}
return (height / 2) - (font_height / 2) - font_top_padding;
}
static void prv_draw_cell_backgrounds(Layer *layer, GContext *ctx) {
SelectionLayerData *data = layer_get_data(layer);
// Loop over each cell and draw the background rectangles
for (int i = 0, current_x_offset = 0; i < data->num_cells; i++) {
if (data->cell_widths[i] == 0) {
continue;
}
int y_offset = 0;
if (data->selected_cell_idx == i && data->bump_is_upwards) {
y_offset = -prv_get_pixels_for_bump_settle(data->bump_settle_anim_progress);
}
int height = layer_get_bounds(layer).size.h;
if (data->selected_cell_idx == i) {
height += prv_get_pixels_for_bump_settle(data->bump_settle_anim_progress);
}
const GRect rect = GRect(current_x_offset, y_offset, data->cell_widths[i], height);
#ifdef PBL_SDK_3
GColor bg_color = data->inactive_background_color;
if (data->selected_cell_idx == i && !data->slide_amin_progress) {
bg_color = data->active_background_color;
}
graphics_context_set_fill_color(ctx, bg_color);
graphics_fill_rect(ctx, rect, 1, GCornerNone);
#elif PBL_SDK_2
graphics_context_set_stroke_color(ctx, GColorBlack);
graphics_draw_rect(ctx, rect);
if (data->selected_cell_idx == i && !data->slide_amin_progress){
layer_set_frame(inverter_layer_get_layer(data->inverter), rect);
}
#endif
current_x_offset += data->cell_widths[i] + data->cell_padding;
}
}
static void prv_draw_slider_slide(Layer *layer, GContext *ctx) {
SelectionLayerData *data = layer_get_data(layer);
int starting_x_offset = 0;
for (int i = 0; i < data->num_cells; i++) {
if (data->selected_cell_idx == i) {
break;
}
starting_x_offset += data->cell_widths[i] + data->cell_padding;
}
int next_cell_width = data->cell_widths[data->selected_cell_idx + 1];
if (!data->slide_is_forward) {
next_cell_width = data->cell_widths[data->selected_cell_idx - 1];
}
int slide_distance = next_cell_width + data->cell_padding;
int current_slide_distance = (slide_distance * data->slide_amin_progress) / 100;
if (!data->slide_is_forward) {
current_slide_distance = -current_slide_distance;
}
int current_x_offset = starting_x_offset + current_slide_distance;
int cur_cell_width = data->cell_widths[data->selected_cell_idx];
int total_cell_width_change = next_cell_width - cur_cell_width + data->cell_padding;
int current_cell_width_change = (total_cell_width_change * (int) data->slide_amin_progress) / 100;
int current_cell_width = cur_cell_width + current_cell_width_change;
if (!data->slide_is_forward) {
current_x_offset -= current_cell_width_change;
}
GRect rect = GRect(current_x_offset, 0, current_cell_width, layer_get_bounds(layer).size.h);
#ifdef PBL_COLOR
graphics_context_set_fill_color(ctx, data->active_background_color);
graphics_fill_rect(ctx, rect, 1, GCornerNone);
#else
layer_set_frame(inverter_layer_get_layer(data->inverter), rect);
#endif
}
static void prv_draw_slider_settle(Layer *layer, GContext *ctx) {
SelectionLayerData *data = layer_get_data(layer);
int starting_x_offset = 0;
for (int i = 0; i < data->num_cells; i++) {
if (data->selected_cell_idx == i) {
break;
}
starting_x_offset += data->cell_widths[i] + data->cell_padding;
}
int x_offset = starting_x_offset;
if (data->slide_is_forward) {
x_offset += data->cell_widths[data->selected_cell_idx];
}
int current_width = (data->cell_padding * data->slide_settle_anim_progress) / 100;
if (!data->slide_is_forward) {
x_offset -= current_width;
}
GRect rect = GRect(x_offset, 0, current_width, layer_get_bounds(layer).size.h);
#ifdef PBL_COLOR
graphics_context_set_fill_color(ctx, data->active_background_color);
graphics_fill_rect(ctx, rect, 1, GCornerNone);
#else
if (data->slide_is_forward) {
rect.origin.x -= data->cell_widths[data->selected_cell_idx];
rect.size.w += data->cell_widths[data->selected_cell_idx];
}
else
rect.size.w += data->cell_widths[data->selected_cell_idx];
layer_set_frame(inverter_layer_get_layer(data->inverter), rect);
#endif
}
static void prv_draw_text(Layer *layer, GContext *ctx) {
#ifndef PBL_COLOR
graphics_context_set_text_color(ctx, GColorBlack);
#endif
SelectionLayerData *data = layer_get_data(layer);
for (int i = 0, current_x_offset = 0; i < data->num_cells; i++) {
if (data->callbacks.get_cell_text) {
char *text = data->callbacks.get_cell_text(i, data->context);
if (text) {
int height = layer_get_bounds(layer).size.h;
if (data->selected_cell_idx == i) {
height += prv_get_pixels_for_bump_settle(data->bump_settle_anim_progress);
}
int y_offset = prv_get_y_offset_which_vertically_centers_font(data->font, height);
if (data->selected_cell_idx == i && data->bump_is_upwards) {
y_offset -= prv_get_pixels_for_bump_settle(data->bump_settle_anim_progress);
}
if (data->selected_cell_idx == i) {
int delta = (data->bump_text_anim_progress * prv_get_font_top_padding(data->font)) / 100;
if (data->bump_is_upwards) {
delta *= -1;
}
y_offset += delta;
}
GRect rect = GRect(current_x_offset, y_offset, data->cell_widths[i], height);
graphics_draw_text(ctx, text, data->font, rect, GTextOverflowModeFill, GTextAlignmentCenter, NULL);
}
}
current_x_offset += data->cell_widths[i] + data->cell_padding;
}
}
static void prv_draw_selection_layer(Layer *layer, GContext *ctx) {
SelectionLayerData *data = layer_get_data(layer);
prv_draw_cell_backgrounds(layer, ctx);
#ifndef PBL_COLOR
prv_draw_text(layer, ctx);
#endif
if (data->slide_amin_progress) {
prv_draw_slider_slide(layer, ctx);
}
if (data->slide_settle_anim_progress) {
prv_draw_slider_settle(layer, ctx);
}
#ifdef PBL_COLOR
prv_draw_text(layer, ctx);
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! Increment / Decrement Animation
//! This animation causes a the active cell to "bump" when the user presses the up button.
//! This animation has two parts:
//! 1) The "text to cell edge"
//! 2) The "background settle"
//! The "text to cell edge" (bump_text) moves the text until it hits the top / bottom of the cell.
//! The "background settle" (bump_settle) is a reaction to the "text to cell edge" animation.
//! The top of the cell immediately expands down giving the impression that the text "pushed" the
//! cell making it bigger. The cell then shrinks / settles back to its original height
//! with the text vertically centered
static void prv_bump_text_impl(struct Animation *animation, const AnimationProgress distance_normalized) {
Layer *layer = (Layer*) animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->bump_text_anim_progress = (100 * distance_normalized) / ANIMATION_NORMALIZED_MAX;
layer_mark_dirty(layer);
}
static void prv_bump_text_stopped(Animation *animation, bool finished, void *context) {
Layer *layer = (Layer*)animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->bump_text_anim_progress = 0;
if (data->bump_is_upwards == true) {
data->callbacks.increment(data->selected_cell_idx, 1, data->context);
} else {
data->callbacks.decrement(data->selected_cell_idx, 1, data->context);
}
animation_destroy(animation);
#ifndef PBL_SDK_3
Animation *bump_settle = prv_create_bump_settle_animation(layer);
animation_schedule(bump_settle);
#endif
}
static void prv_bump_settle_impl(struct Animation *animation, const AnimationProgress distance_normalized) {
Layer *layer = (Layer*)animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->bump_settle_anim_progress = (100 * distance_normalized) / ANIMATION_NORMALIZED_MAX;
layer_mark_dirty(layer);
}
static void prv_bump_settle_stopped(Animation *animation, bool finished, void *context) {
Layer *layer = (Layer*)animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->bump_settle_anim_progress = 0;
animation_destroy(animation);
}
static Animation* prv_create_bump_text_animation(Layer *layer) {
SelectionLayerData *data = layer_get_data(layer);
PropertyAnimation *bump_text_anim = property_animation_create_layer_frame(layer, NULL, NULL);
Animation *animation = property_animation_get_animation(bump_text_anim);
animation_set_curve(animation, AnimationCurveEaseIn);
animation_set_duration(animation, BUMP_TEXT_DURATION_MS);
AnimationHandlers anim_handler = {
.stopped = prv_bump_text_stopped,
};
animation_set_handlers(animation, anim_handler, layer);
data->bump_text_impl = (AnimationImplementation) {
.update = prv_bump_text_impl,
};
animation_set_implementation(animation, &data->bump_text_impl);
return animation;
}
static Animation* prv_create_bump_settle_animation(Layer *layer) {
SelectionLayerData *data = layer_get_data(layer);
PropertyAnimation *bump_settle_anim = property_animation_create_layer_frame(layer, NULL, NULL);
Animation *animation = property_animation_get_animation(bump_settle_anim);
animation_set_curve(animation, AnimationCurveEaseOut);
animation_set_duration(animation, BUMP_SETTLE_DURATION_MS);
AnimationHandlers anim_handler = {
.stopped = prv_bump_settle_stopped,
};
animation_set_handlers(animation, anim_handler, layer);
data->bump_settle_anim_impl = (AnimationImplementation) {
.update = prv_bump_settle_impl,
};
animation_set_implementation(animation, &data->bump_settle_anim_impl);
return animation;
}
static void prv_run_value_change_animation(Layer *layer) {
SelectionLayerData *data = layer_get_data(layer);
Animation *bump_text = prv_create_bump_text_animation(layer);
#ifdef PBL_SDK_3
Animation *bump_settle = prv_create_bump_settle_animation(layer);
data->value_change_animation = animation_sequence_create(bump_text, bump_settle, NULL);
animation_schedule(data->value_change_animation);
#else
animation_schedule(bump_text);
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! Slide Animation
//! This animation moves the "selection box" (active color) to the next cell to the right.
//! This animation has two parts:
//! 1) The "move and expand"
//! 2) The "settle"
//! The "move and expand" (slide) moves the selection box from the currently active cell to
//! the next cell to the right. At the same time the width is changed to be the size of the
//! next cell plus the size of the padding. This creates an overshoot effect.
//! The "settle" (slide_settle) removes the extra width that was added in the "move and expand"
//! step.
static void prv_slide_impl(struct Animation *animation, const AnimationProgress distance_normalized) {
Layer *layer = (Layer*) animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->slide_amin_progress = (100 * distance_normalized) / ANIMATION_NORMALIZED_MAX;
layer_mark_dirty(layer);
}
static void prv_slide_stopped(Animation *animation, bool finished, void *context) {
Layer *layer = (Layer*)animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->slide_amin_progress = 0;
if (data->slide_is_forward) {
data->selected_cell_idx++;
} else {
data->selected_cell_idx--;
}
animation_destroy(animation);
#ifndef PBL_SDK_3
Animation *settle_animation = prv_create_slide_settle_animation(layer);
animation_schedule(settle_animation);
#endif
}
static void prv_slide_settle_impl(struct Animation *animation, const AnimationProgress distance_normalized) {
Layer *layer = (Layer*)animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->slide_settle_anim_progress = 100 - ((100 * distance_normalized) / ANIMATION_NORMALIZED_MAX);
layer_mark_dirty(layer);
}
static void prv_slide_settle_stopped(Animation *animation, bool finished, void *context) {
Layer *layer = (Layer*) animation_get_context(animation);
SelectionLayerData *data = layer_get_data(layer);
data->slide_settle_anim_progress = 0;
animation_destroy(animation);
}
static Animation* prv_create_slide_animation(Layer *layer) {
SelectionLayerData *data = layer_get_data(layer);
PropertyAnimation *slide_amin = property_animation_create_layer_frame(layer, NULL, NULL);
Animation *animation = property_animation_get_animation(slide_amin);
animation_set_curve(animation, AnimationCurveEaseIn);
animation_set_duration(animation, SLIDE_DURATION_MS);
AnimationHandlers anim_handler = {
.stopped = prv_slide_stopped,
};
animation_set_handlers(animation, anim_handler, layer);
data->slide_amin_impl = (AnimationImplementation) {
.update = prv_slide_impl,
};
animation_set_implementation(animation, &data->slide_amin_impl);
return animation;
}
static Animation* prv_create_slide_settle_animation(Layer *layer) {
SelectionLayerData *data = layer_get_data(layer);
PropertyAnimation *slide_settle_anim = property_animation_create_layer_frame(layer, NULL, NULL);
Animation *animation = property_animation_get_animation(slide_settle_anim);
animation_set_curve(animation, AnimationCurveEaseOut);
animation_set_duration(animation, SLIDE_SETTLE_DURATION_MS);
AnimationHandlers anim_handler = {
.stopped = prv_slide_settle_stopped,
};
animation_set_handlers(animation, anim_handler, layer);
data->slide_settle_anim_impl = (AnimationImplementation) {
.update = prv_slide_settle_impl,
};
animation_set_implementation(animation, &data->slide_settle_anim_impl);
return animation;
}
static void prv_run_slide_animation(Layer *layer) {
SelectionLayerData *data = layer_get_data(layer);
Animation *over_animation = prv_create_slide_animation(layer);
#ifdef PBL_SDK_3
Animation *settle_animation = prv_create_slide_settle_animation(layer);
data->next_cell_animation = animation_sequence_create(over_animation, settle_animation, NULL);
animation_schedule(data->next_cell_animation);
#else
animation_schedule(over_animation);
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! Click handlers
void prv_up_click_handler(ClickRecognizerRef recognizer, void *context) {
Layer *layer = (Layer*)context;
SelectionLayerData *data = layer_get_data(layer);
if (data->is_active) {
if (click_recognizer_is_repeating(recognizer)) {
// Don't animate if the button is being held down. Just update the text
data->callbacks.increment(data->selected_cell_idx, click_number_of_clicks_counted(recognizer), data->context);
layer_mark_dirty(layer);
} else {
data->bump_is_upwards = true;
prv_run_value_change_animation(layer);
}
}
}
void prv_down_click_handler(ClickRecognizerRef recognizer, void *context) {
Layer *layer = (Layer*)context;
SelectionLayerData *data = layer_get_data(layer);
if (data->is_active) {
if (click_recognizer_is_repeating(recognizer)) {
// Don't animate if the button is being held down. Just update the text
data->callbacks.decrement(data->selected_cell_idx, click_number_of_clicks_counted(recognizer), data->context);
layer_mark_dirty(layer);
} else {
data->bump_is_upwards = false;
prv_run_value_change_animation(layer);
}
}
}
void prv_select_click_handler(ClickRecognizerRef recognizer, void *context) {
Layer *layer = (Layer*)context;
SelectionLayerData *data = layer_get_data(layer);
if (data->is_active) {
animation_unschedule(data->next_cell_animation);
if (data->selected_cell_idx >= data->num_cells - 1) {
data->selected_cell_idx = 0;
data->callbacks.complete(data->context);
} else {
data->slide_is_forward = true;
prv_run_slide_animation(layer);
}
}
}
void prv_back_click_handler(ClickRecognizerRef recognizer, void *context) {
Layer *layer = (Layer*)context;
SelectionLayerData *data = layer_get_data(layer);
if (data->is_active) {
animation_unschedule(data->next_cell_animation);
if (data->selected_cell_idx == 0) {
data->selected_cell_idx = 0;
window_stack_pop(true);
} else {
data->slide_is_forward = false;
prv_run_slide_animation(layer);
}
}
}
static void prv_click_config_provider(Layer *layer) {
window_set_click_context(BUTTON_ID_UP, layer);
window_set_click_context(BUTTON_ID_DOWN, layer);
window_set_click_context(BUTTON_ID_SELECT, layer);
window_set_click_context(BUTTON_ID_BACK, layer);
window_single_repeating_click_subscribe(BUTTON_ID_UP, BUTTON_HOLD_REPEAT_MS, prv_up_click_handler);
window_single_repeating_click_subscribe(BUTTON_ID_DOWN, BUTTON_HOLD_REPEAT_MS, prv_down_click_handler);
window_single_click_subscribe(BUTTON_ID_SELECT, prv_select_click_handler);
window_single_click_subscribe(BUTTON_ID_BACK, prv_back_click_handler);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//! API
static Layer* selection_layer_init(SelectionLayerData *selection_layer_, GRect frame, int num_cells) {
Layer *layer = layer_create_with_data(frame, sizeof(SelectionLayerData));
SelectionLayerData *selection_layer_data = layer_get_data(layer);
if (num_cells > MAX_SELECTION_LAYER_CELLS) {
num_cells = MAX_SELECTION_LAYER_CELLS;
}
// Set layer defaults
*selection_layer_data = (SelectionLayerData) {
#ifdef PBL_COLOR
.active_background_color = DEFAULT_ACTIVE_COLOR,
.inactive_background_color = DEFAULT_INACTIVE_COLOR,
#else
.inverter = inverter_layer_create(GRect(0, 0, 0, frame.size.h)),
#endif
.num_cells = num_cells,
.cell_padding = DEFAULT_CELL_PADDING,
.selected_cell_idx = DEFAULT_SELECTED_INDEX,
.font = fonts_get_system_font(DEFAULT_FONT),
.is_active = true,
};
for (int i = 0; i < num_cells; i++) {
selection_layer_data->cell_widths[i] = 0;
}
layer_set_frame(layer, frame);
layer_set_clips(layer, false);
layer_set_update_proc(layer, (LayerUpdateProc)prv_draw_selection_layer);
#ifndef PBL_COLOR
layer_add_child(layer, inverter_layer_get_layer(selection_layer_data->inverter));
#endif
return layer;
}
Layer* selection_layer_create(GRect frame, int num_cells) {
SelectionLayerData *selection_layer_data = NULL;
return selection_layer_init(selection_layer_data, frame, num_cells);
}
static void selection_layer_deinit(Layer* layer) {
#ifndef PBL_COLOR
SelectionLayerData *data = layer_get_data(layer);
inverter_layer_destroy(data->inverter);
#endif
layer_destroy(layer);
}
void selection_layer_destroy(Layer* layer) {
SelectionLayerData *data = layer_get_data(layer);
animation_unschedule_all();
if (data) {
selection_layer_deinit(layer);
}
}
void selection_layer_set_cell_width(Layer *layer, int idx, int width) {
SelectionLayerData *data = layer_get_data(layer);
if (data && idx < data->num_cells) {
data->cell_widths[idx] = width;
}
#ifndef PBL_COLOR
layer_set_bounds(inverter_layer_get_layer(data->inverter), GRect(0, 0, width, layer_get_bounds(inverter_layer_get_layer(data->inverter)).size.h));
#endif
}
void selection_layer_set_font(Layer *layer, GFont font) {
SelectionLayerData *data = layer_get_data(layer);
if (data) {
data->font = font;
}
}
void selection_layer_set_inactive_bg_color(Layer *layer, GColor color) {
SelectionLayerData *data = layer_get_data(layer);
if (data) {
data->inactive_background_color = color;
}
}
void selection_layer_set_active_bg_color(Layer *layer, GColor color) {
SelectionLayerData *data = layer_get_data(layer);
if (data) {
data->active_background_color = color;
}
}
void selection_layer_set_cell_padding(Layer *layer, int padding) {
SelectionLayerData *data = layer_get_data(layer);
if (data) {
data->cell_padding = padding;
}
}
void selection_layer_set_active(Layer *layer, bool is_active) {
SelectionLayerData *data = layer_get_data(layer);
if (data) {
if (is_active && !data->is_active) {
data->selected_cell_idx = 0;
} if (!is_active && data->is_active) {
data->selected_cell_idx = MAX_SELECTION_LAYER_CELLS + 1;
}
data->is_active = is_active;
layer_mark_dirty(layer);
}
}
void selection_layer_set_click_config_onto_window(Layer *layer, struct Window *window) {
if (layer && window) {
window_set_click_config_provider_with_context(window, (ClickConfigProvider)prv_click_config_provider, layer);
}
}
void selection_layer_set_callbacks(Layer *layer, void *context, SelectionLayerCallbacks callbacks) {
SelectionLayerData *data = layer_get_data(layer);
data->callbacks = callbacks;
data->context = context;
}
| {
"content_hash": "154f0bb32d24bf0d0ef4d8a032055e0f",
"timestamp": "",
"source": "github",
"line_count": 641,
"max_line_length": 148,
"avg_line_length": 34.135725429017164,
"alnum_prop": 0.684795027649559,
"repo_name": "Dragoon013/ui-patterns",
"id": "d46040d4398378cc3f5c4d1520a2b0c78270f52c",
"size": "22473",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/layers/selection_layer.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "66369"
},
{
"name": "C++",
"bytes": "479"
},
{
"name": "Objective-C",
"bytes": "623"
},
{
"name": "Python",
"bytes": "1119"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="animated-vector-drawable-24.2.1">
<CLASSES>
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/24.2.1/jars/classes.jar!/" />
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/24.2.1/res" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/env/android/24.1.2/extras/android/m2repository/com/android/support/animated-vector-drawable/24.2.1/animated-vector-drawable-24.2.1-sources.jar!/" />
<root url="jar://$USER_HOME$/env/android/24.1.2/extras/android/m2repository/com/android/support/animated-vector-drawable/24.2.1/animated-vector-drawable-24.2.1-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "211ce50b56ab74f59f81f45459b6e55e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 183,
"avg_line_length": 64.15384615384616,
"alnum_prop": 0.7110311750599521,
"repo_name": "imishx/ActivityRouter",
"id": "f83541c8da80784bb157558b1f636d65be7951bb",
"size": "834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/animated_vector_drawable_24_2_1.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "31857"
}
],
"symlink_target": ""
} |
package kafka.controller
import java.util.Properties
import java.util.concurrent.LinkedBlockingQueue
import kafka.api.RequestOrResponse
import kafka.common.TopicAndPartition
import kafka.integration.KafkaServerTestHarness
import kafka.server.{KafkaConfig, KafkaServer}
import kafka.utils._
import org.apache.kafka.common.metrics.Metrics
import org.apache.kafka.common.requests.{AbstractRequestResponse, AbstractRequest}
import org.apache.kafka.common.utils.SystemTime
import org.apache.log4j.{Level, Logger}
import org.junit.{After, Before, Test}
import scala.collection.mutable
class ControllerFailoverTest extends KafkaServerTestHarness with Logging {
val log = Logger.getLogger(classOf[ControllerFailoverTest])
val numNodes = 2
val numParts = 1
val msgQueueSize = 1
val topic = "topic1"
val overridingProps = new Properties()
val metrics = new Metrics()
overridingProps.put(KafkaConfig.NumPartitionsProp, numParts.toString)
override def generateConfigs() = TestUtils.createBrokerConfigs(numNodes, zkConnect)
.map(KafkaConfig.fromProps(_, overridingProps))
@Before
override def setUp() {
super.setUp()
}
@After
override def tearDown() {
super.tearDown()
this.metrics.close()
}
/**
* See @link{https://issues.apache.org/jira/browse/KAFKA-2300}
* for the background of this test case
*/
@Test
def testMetadataUpdate() {
log.setLevel(Level.INFO)
var controller: KafkaServer = this.servers.head
// Find the current controller
val epochMap: mutable.Map[Int, Int] = mutable.Map.empty
for (server <- this.servers) {
epochMap += (server.config.brokerId -> server.kafkaController.epoch)
if(server.kafkaController.isActive()) {
controller = server
}
}
// Create topic with one partition
kafka.admin.AdminUtils.createTopic(controller.zkUtils, topic, 1, 1)
val topicPartition = TopicAndPartition("topic1", 0)
var partitions = controller.kafkaController.partitionStateMachine.partitionsInState(OnlinePartition)
while (!partitions.contains(topicPartition)) {
partitions = controller.kafkaController.partitionStateMachine.partitionsInState(OnlinePartition)
Thread.sleep(100)
}
// Replace channel manager with our mock manager
controller.kafkaController.controllerContext.controllerChannelManager.shutdown()
val channelManager = new MockChannelManager(controller.kafkaController.controllerContext,
controller.kafkaController.config, metrics)
channelManager.startup()
controller.kafkaController.controllerContext.controllerChannelManager = channelManager
channelManager.shrinkBlockingQueue(0)
channelManager.stopSendThread(0)
// Spawn a new thread to block on the outgoing channel
// queue
val thread = new Thread(new Runnable {
def run() {
try {
controller.kafkaController.sendUpdateMetadataRequest(Seq(0), Set(topicPartition))
log.info("Queue state %d %d".format(channelManager.queueCapacity(0), channelManager.queueSize(0)))
controller.kafkaController.sendUpdateMetadataRequest(Seq(0), Set(topicPartition))
log.info("Queue state %d %d".format(channelManager.queueCapacity(0), channelManager.queueSize(0)))
} catch {
case _: Exception => log.info("Thread interrupted")
}
}
})
thread.setName("mythread")
thread.start()
while (thread.getState() != Thread.State.WAITING) {
Thread.sleep(100)
}
// Assume that the thread is WAITING because it is
// blocked on the queue, so interrupt and move forward
thread.interrupt()
thread.join()
channelManager.resumeSendThread(0)
// Wait and find current controller
var found = false
var counter = 0
while (!found && counter < 10) {
for (server <- this.servers) {
val previousEpoch = epochMap get server.config.brokerId match {
case Some(epoch) =>
epoch
case None =>
val msg = String.format("Missing element in epoch map %s", epochMap.mkString(", "))
throw new IllegalStateException(msg)
}
if (server.kafkaController.isActive
&& previousEpoch < server.kafkaController.epoch) {
controller = server
found = true
}
}
if (!found) {
Thread.sleep(100)
counter += 1
}
}
// Give it a shot to make sure that sending isn't blocking
try {
controller.kafkaController.sendUpdateMetadataRequest(Seq(0), Set(topicPartition))
} catch {
case e : Throwable => {
fail(e)
}
}
}
}
class MockChannelManager(private val controllerContext: ControllerContext, config: KafkaConfig, metrics: Metrics)
extends ControllerChannelManager(controllerContext, config, new SystemTime, metrics) {
def stopSendThread(brokerId: Int) {
val requestThread = brokerStateInfo(brokerId).requestSendThread
requestThread.isRunning.set(false)
requestThread.interrupt
requestThread.join
}
def shrinkBlockingQueue(brokerId: Int) {
val messageQueue = new LinkedBlockingQueue[QueueItem](1)
val brokerInfo = this.brokerStateInfo(brokerId)
this.brokerStateInfo.put(brokerId, brokerInfo.copy(messageQueue = messageQueue))
}
def resumeSendThread (brokerId: Int) {
this.startRequestSendThread(0)
}
def queueCapacity(brokerId: Int): Int = {
this.brokerStateInfo(brokerId).messageQueue.remainingCapacity
}
def queueSize(brokerId: Int): Int = {
this.brokerStateInfo(brokerId).messageQueue.size
}
}
| {
"content_hash": "f2f19ee4f5e015c4a9a89cf4a8132bf0",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 113,
"avg_line_length": 34.3780487804878,
"alnum_prop": 0.7025540971975878,
"repo_name": "geeag/kafka",
"id": "6430b33ad80f9b1efb473cdc667d113a4f8c6158",
"size": "6439",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "core/src/test/scala/unit/kafka/controller/ControllerFailoverTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22196"
},
{
"name": "HTML",
"bytes": "5443"
},
{
"name": "Java",
"bytes": "5890050"
},
{
"name": "Python",
"bytes": "452869"
},
{
"name": "Scala",
"bytes": "3503598"
},
{
"name": "Shell",
"bytes": "54956"
},
{
"name": "XSLT",
"bytes": "7116"
}
],
"symlink_target": ""
} |
namespace Obscureware.Console.Commands.Internals.Converters
{
using System;
using System.Globalization;
[ArgumentConverterTargetType(typeof(Decimal))]
internal class DecimalArgumentConverter : ArgumentConverter
{
/// <inheritdoc />
public override object TryConvert(string argumentText, CultureInfo culture)
{
return Decimal.Parse(argumentText, culture);
}
}
} | {
"content_hash": "5612f54ee2b3976c704514b842a69e39",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 83,
"avg_line_length": 28.6,
"alnum_prop": 0.6899766899766899,
"repo_name": "Sebastian-Gruchacz/ObscureWare",
"id": "6df828049a35ce5a652aad5f42eb385d8986b1f6",
"size": "429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Extended.Console/Obscureware.Console.Commands/Internals/Converters/DecimalArgumentConverter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "283395"
}
],
"symlink_target": ""
} |
@interface EmployeeTableViewController : UITableViewController
@property (nonatomic) EmployeeObject *currentEmployee;
-(NSString*)convetToCurrencyString:(NSString*)string;
@end
| {
"content_hash": "2692130118e8d57bfe3960715404b435",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 62,
"avg_line_length": 25.714285714285715,
"alnum_prop": 0.8333333333333334,
"repo_name": "OliverSJ/Chicago-Employee-Salaries",
"id": "abd59ce901e0a81637e703ffffe24af2fff6ff33",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ChicagoEmployeeSalaries/EmployeeTableViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "110487"
},
{
"name": "Ruby",
"bytes": "314"
}
],
"symlink_target": ""
} |
using System;
using Telerik.Charting;
using Telerik.Core;
using Windows.Foundation;
namespace Telerik.UI.Xaml.Controls.Chart
{
internal class RangeSeriesDataSource : CategoricalSeriesDataSource
{
private DataPointBinding lowBinding;
private DataPointBinding highBinding;
public DataPointBinding LowBinding
{
get
{
return this.lowBinding;
}
set
{
if (this.lowBinding == value)
{
return;
}
this.lowBinding = value;
if (this.ItemsSource != null)
{
this.Rebind(false, null);
}
}
}
public DataPointBinding HighBinding
{
get
{
return this.highBinding;
}
set
{
if (this.highBinding == value)
{
return;
}
this.highBinding = value;
if (this.ItemsSource != null)
{
this.Rebind(false, null);
}
}
}
protected override DataPoint CreateDataPoint()
{
return new RangeDataPoint();
}
protected override void ProcessDouble(DataPoint point, double value)
{
if (!double.IsNaN(value))
{
RangeDataPoint rangeDataPoint = (RangeDataPoint)point;
rangeDataPoint.Low = Math.Min(0, value);
rangeDataPoint.High = Math.Max(0, value);
}
}
protected override void ProcessDoubleArray(DataPoint point, double[] values)
{
if (values.Length == 2)
{
RangeDataPoint rangeDataPoint = (RangeDataPoint)point;
rangeDataPoint.Low = values[0];
rangeDataPoint.High = Math.Max(values[1], rangeDataPoint.Low);
}
else
{
throw new NotSupportedException();
}
}
protected override void ProcessNullableDoubleArray(DataPoint point, double?[] values)
{
if (values.Length == 2)
{
RangeDataPoint rangeDataPoint = (RangeDataPoint)point;
if (values[0].HasValue)
{
rangeDataPoint.Low = values[0].Value;
}
if (values[1].HasValue)
{
rangeDataPoint.High = Math.Max(values[1].Value, rangeDataPoint.Low);
}
}
else
{
throw new NotSupportedException();
}
}
protected override void ProcessPoint(DataPoint dataPoint, Point point)
{
throw new NotSupportedException();
}
protected override void ProcessSize(DataPoint point, Size size)
{
throw new NotSupportedException();
}
protected override void InitializeBinding(DataPointBindingEntry binding)
{
bool highIsValidNumber = true;
bool lowIsValidNumber = true;
RangeDataPoint rangeDataPoint = (RangeDataPoint)binding.DataPoint;
if (this.highBinding != null)
{
object value = this.highBinding.GetValue(binding.DataItem);
double doubleValue;
if (NumericConverter.TryConvertToDouble(value, out doubleValue))
{
rangeDataPoint.High = doubleValue;
}
else
{
rangeDataPoint.High = 0d;
highIsValidNumber = false;
}
}
if (this.lowBinding != null)
{
object value = this.lowBinding.GetValue(binding.DataItem);
double doubleValue;
if (NumericConverter.TryConvertToDouble(value, out doubleValue))
{
rangeDataPoint.Low = doubleValue;
}
else
{
rangeDataPoint.Low = 0d;
lowIsValidNumber = false;
}
}
rangeDataPoint.isEmpty = !lowIsValidNumber && !highIsValidNumber;
base.InitializeBinding(binding);
}
}
}
| {
"content_hash": "9165adb8fd6863fcc6a8ce55c4c0ad50",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 93,
"avg_line_length": 28.40251572327044,
"alnum_prop": 0.47564216120460584,
"repo_name": "geotinc/UI-For-UWP",
"id": "a430d75a72d09304ac758e8500cac8648d04d027",
"size": "4518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Controls/Chart/Chart.UWP/Visualization/DataBinding/DataSources/RangeSeriesDataSource.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "123"
},
{
"name": "C",
"bytes": "524"
},
{
"name": "C#",
"bytes": "9312647"
},
{
"name": "C++",
"bytes": "95940"
},
{
"name": "Smalltalk",
"bytes": "24928"
}
],
"symlink_target": ""
} |
package org.bitcoins.chain.pow
import org.bitcoins.chain.blockchain.Blockchain
import org.bitcoins.chain.config.ChainAppConfig
import org.bitcoins.core.api.chain.db.BlockHeaderDb
import org.bitcoins.core.number.UInt32
import org.bitcoins.core.protocol.blockchain._
import org.bitcoins.core.util.NumberUtil
/** Implements functions found inside of bitcoin core's
* @see [[https://github.com/bitcoin/bitcoin/blob/35477e9e4e3f0f207ac6fa5764886b15bf9af8d0/src/pow.cpp pow.cpp]]
*/
sealed abstract class Pow {
/** Gets the next proof of work requirement for a block
* @see [[https://github.com/bitcoin/bitcoin/blob/35477e9e4e3f0f207ac6fa5764886b15bf9af8d0/src/pow.cpp#L13 Mimics bitcoin core implementation]]
*/
def getNetworkWorkRequired(
newPotentialTip: BlockHeader,
blockchain: Blockchain)(implicit config: ChainAppConfig): UInt32 = {
val chainParams = config.chain
val tip = blockchain.tip
val currentHeight = tip.height
val powLimit: UInt32 =
if ((currentHeight + 1) % chainParams.difficultyChangeInterval != 0) {
if (chainParams.allowMinDifficultyBlocks) {
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (
newPotentialTip.time.toLong > tip.blockHeader.time.toLong + chainParams.powTargetSpacing.toSeconds * 2
) {
chainParams.compressedPowLimit
} else {
// Return the last non-special-min-difficulty-rules-block
//while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
// pindex = pindex->pprev;
val nonMinDiffF = blockchain.find { h =>
h.nBits != chainParams.compressedPowLimit || h.height % chainParams.difficultyChangeInterval == 0
}
nonMinDiffF match {
case Some(bh) => bh.nBits
case None =>
config.chain match {
case RegTestNetChainParams =>
RegTestNetChainParams.compressedPowLimit
case TestNetChainParams | MainNetChainParams |
SigNetChainParams(_) =>
//if we can't find a non min difficulty block, let's just fail
throw new RuntimeException(
s"Could not find non mindifficulty block in chain of size=${blockchain.length}! hash=${tip.hashBE.hex} height=${currentHeight}")
}
}
}
} else {
tip.blockHeader.nBits
}
} else {
val firstHeight: Int =
currentHeight - (chainParams.difficultyChangeInterval - 1)
require(
firstHeight >= 0,
s"We must have our first height be positive, got=${firstHeight}")
val firstBlockAtIntervalOpt: Option[BlockHeaderDb] =
blockchain.findAtHeight(firstHeight)
firstBlockAtIntervalOpt match {
case Some(firstBlockAtInterval) =>
calculateNextWorkRequired(currentTip = tip,
firstBlockAtInterval,
chainParams)
case None =>
throw new RuntimeException(
s"Could not find block at height=$firstHeight out of ${blockchain.length} headers to calculate pow difficulty change")
}
}
powLimit
}
/** Calculate the next proof of work requirement for our blockchain
* @see [[https://github.com/bitcoin/bitcoin/blob/35477e9e4e3f0f207ac6fa5764886b15bf9af8d0/src/pow.cpp#L49 bitcoin core implementation]]
* @param currentTip
* @param firstBlock
* @param chainParams
* @return
*/
def calculateNextWorkRequired(
currentTip: BlockHeaderDb,
firstBlock: BlockHeaderDb,
chainParams: ChainParams): UInt32 = {
if (chainParams.noRetargeting) {
currentTip.nBits
} else {
var actualTimespan = (currentTip.time - firstBlock.time).toLong
val timespanSeconds = chainParams.powTargetTimeSpan.toSeconds
if (actualTimespan < timespanSeconds / 4) {
actualTimespan = timespanSeconds / 4
}
if (actualTimespan > timespanSeconds * 4) {
actualTimespan = timespanSeconds * 4
}
val powLimit = chainParams.powLimit
var bnNew = NumberUtil.targetExpansion(currentTip.nBits).difficulty
bnNew = bnNew * actualTimespan
bnNew = bnNew / timespanSeconds
if (bnNew > powLimit) {
bnNew = powLimit
}
val newTarget = NumberUtil.targetCompression(bnNew, isNegative = false)
newTarget
}
}
def getBlockProof(header: BlockHeader): BigInt = {
val target = NumberUtil.targetExpansion(header.nBits)
if (target.isNegative || target.isOverflow) {
BigInt(0)
} else {
(BigInt(1) << 256) / (target.difficulty + BigInt(1))
}
}
}
object Pow extends Pow
| {
"content_hash": "545ee892c17f676a7ce3cefeb1e0defa",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 150,
"avg_line_length": 36.01428571428571,
"alnum_prop": 0.6354621182070607,
"repo_name": "bitcoin-s/bitcoin-s",
"id": "1918439fedccb334c77f50a53f28a711118c51d9",
"size": "5042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chain/src/main/scala/org/bitcoins/chain/pow/Pow.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2266"
},
{
"name": "Dockerfile",
"bytes": "235"
},
{
"name": "Java",
"bytes": "58539"
},
{
"name": "JavaScript",
"bytes": "31763"
},
{
"name": "Scala",
"bytes": "8398379"
},
{
"name": "Shell",
"bytes": "7787"
}
],
"symlink_target": ""
} |
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <inttypes.h>
#include "liblwm2m.h"
#include "commandline.h"
#define HELP_COMMAND "help"
#define HELP_DESC "Type '"HELP_COMMAND" [COMMAND]' for more details on a command."
#define UNKNOWN_CMD_MSG "Unknown command. Type '"HELP_COMMAND"' for help."
static command_desc_t * prv_find_command(command_desc_t * commandArray,
char * buffer,
size_t length)
{
int i;
if (length == 0) return NULL;
i = 0;
while (commandArray[i].name != NULL
&& (strlen(commandArray[i].name) != length || strncmp(buffer, commandArray[i].name, length)))
{
i++;
}
if (commandArray[i].name == NULL)
{
return NULL;
}
else
{
return &commandArray[i];
}
}
static void prv_displayHelp(command_desc_t * commandArray,
char * buffer)
{
command_desc_t * cmdP;
int length;
// find end of first argument
length = 0;
while (buffer[length] != 0 && !isspace(buffer[length]&0xff))
length++;
cmdP = prv_find_command(commandArray, buffer, length);
if (cmdP == NULL)
{
int i;
fprintf(stdout, HELP_COMMAND"\t"HELP_DESC"\r\n");
for (i = 0 ; commandArray[i].name != NULL ; i++)
{
fprintf(stdout, "%s\t%s\r\n", commandArray[i].name, commandArray[i].shortDesc);
}
}
else
{
fprintf(stdout, "%s\r\n", cmdP->longDesc?cmdP->longDesc:cmdP->shortDesc);
}
}
void handle_command(command_desc_t * commandArray,
char * buffer)
{
command_desc_t * cmdP;
int length;
// find end of command name
length = 0;
while (buffer[length] != 0 && !isspace(buffer[length]&0xFF))
length++;
cmdP = prv_find_command(commandArray, buffer, length);
if (cmdP != NULL)
{
while (buffer[length] != 0 && isspace(buffer[length]&0xFF))
length++;
cmdP->callback(buffer + length, cmdP->userData);
}
else
{
if (!strncmp(buffer, HELP_COMMAND, length))
{
while (buffer[length] != 0 && isspace(buffer[length]&0xFF))
length++;
prv_displayHelp(commandArray, buffer + length);
}
else
{
fprintf(stdout, UNKNOWN_CMD_MSG"\r\n");
}
}
}
static char* prv_end_of_space(char* buffer)
{
while (isspace(buffer[0]&0xff))
{
buffer++;
}
return buffer;
}
char* get_end_of_arg(char* buffer)
{
while (buffer[0] != 0 && !isspace(buffer[0]&0xFF))
{
buffer++;
}
return buffer;
}
char * get_next_arg(char * buffer, char** end)
{
// skip arg
buffer = get_end_of_arg(buffer);
// skip space
buffer = prv_end_of_space(buffer);
if (NULL != end)
{
*end = get_end_of_arg(buffer);
}
return buffer;
}
int check_end_of_args(char* buffer)
{
buffer = prv_end_of_space(buffer);
return (0 == buffer[0]);
}
/**********************************************************
* Display Functions
*/
static void print_indent(FILE * stream,
int num)
{
int i;
for ( i = 0 ; i < num ; i++)
fprintf(stream, " ");
}
void output_buffer(FILE * stream,
uint8_t * buffer,
int length,
int indent)
{
int i;
if (length == 0) fprintf(stream, "\n");
if (buffer == NULL) return;
i = 0;
while (i < length)
{
uint8_t array[16];
int j;
print_indent(stream, indent);
memcpy(array, buffer+i, 16);
for (j = 0 ; j < 16 && i+j < length; j++)
{
fprintf(stream, "%02X ", array[j]);
if (j%4 == 3) fprintf(stream, " ");
}
if (length > 16)
{
while (j < 16)
{
fprintf(stream, " ");
if (j%4 == 3) fprintf(stream, " ");
j++;
}
}
fprintf(stream, " ");
for (j = 0 ; j < 16 && i+j < length; j++)
{
if (isprint(array[j]))
fprintf(stream, "%c", array[j]);
else
fprintf(stream, ".");
}
fprintf(stream, "\n");
i += 16;
}
}
void output_tlv(FILE * stream,
uint8_t * buffer,
size_t buffer_len,
int indent)
{
lwm2m_data_type_t type;
uint16_t id;
size_t dataIndex;
size_t dataLen;
int length = 0;
int result;
while (0 != (result = lwm2m_decode_TLV((uint8_t*)buffer + length, buffer_len - length, &type, &id, &dataIndex, &dataLen)))
{
print_indent(stream, indent);
fprintf(stream, "{\r\n");
print_indent(stream, indent+1);
fprintf(stream, "ID: %d", id);
fprintf(stream, " type: ");
switch (type)
{
case LWM2M_TYPE_OBJECT_INSTANCE:
fprintf(stream, "Object Instance");
break;
case LWM2M_TYPE_MULTIPLE_RESOURCE:
fprintf(stream, "Multiple Instances");
break;
case LWM2M_TYPE_OPAQUE:
fprintf(stream, "Resource Value");
break;
default:
printf("unknown (%d)", (int)type);
break;
}
fprintf(stream, "\n");
print_indent(stream, indent+1);
fprintf(stream, "{\n");
if (type == LWM2M_TYPE_OBJECT_INSTANCE || type == LWM2M_TYPE_MULTIPLE_RESOURCE)
{
output_tlv(stream, buffer + length + dataIndex, dataLen, indent+1);
}
else
{
int64_t intValue;
double floatValue;
uint8_t tmp;
print_indent(stream, indent+2);
fprintf(stream, "data (%ld bytes):\r\n", dataLen);
output_buffer(stream, (uint8_t*)buffer + length + dataIndex, dataLen, indent+2);
tmp = buffer[length + dataIndex + dataLen];
buffer[length + dataIndex + dataLen] = 0;
if (0 < sscanf((const char *)buffer + length + dataIndex, "%"PRId64, &intValue))
{
print_indent(stream, indent+2);
fprintf(stream, "data as Integer: %" PRId64 "\r\n", intValue);
}
if (0 < sscanf((const char*)buffer + length + dataIndex, "%lg", &floatValue))
{
print_indent(stream, indent+2);
fprintf(stream, "data as Float: %.16g\r\n", floatValue);
}
buffer[length + dataIndex + dataLen] = tmp;
}
print_indent(stream, indent+1);
fprintf(stream, "}\r\n");
length += result;
print_indent(stream, indent);
fprintf(stream, "}\r\n");
}
}
void output_data(FILE * stream,
lwm2m_media_type_t format,
uint8_t * data,
int dataLength,
int indent)
{
int i;
print_indent(stream, indent);
fprintf(stream, "%d bytes received of type ", dataLength);
switch (format)
{
case LWM2M_CONTENT_TEXT:
fprintf(stream, "text/plain:\r\n");
output_buffer(stream, data, dataLength, indent);
break;
case LWM2M_CONTENT_OPAQUE:
fprintf(stream, "application/octet-stream:\r\n");
output_buffer(stream, data, dataLength, indent);
break;
case LWM2M_CONTENT_TLV:
fprintf(stream, "application/vnd.oma.lwm2m+tlv:\r\n");
output_tlv(stream, data, dataLength, indent);
break;
case LWM2M_CONTENT_JSON:
fprintf(stream, "application/vnd.oma.lwm2m+json:\r\n");
print_indent(stream, indent);
for (i = 0 ; i < dataLength ; i++)
{
fprintf(stream, "%c", data[i]);
}
fprintf(stream, "\n");
break;
case LWM2M_CONTENT_LINK:
fprintf(stream, "application/link-format:\r\n");
print_indent(stream, indent);
for (i = 0 ; i < dataLength ; i++)
{
fprintf(stream, "%c", data[i]);
}
fprintf(stream, "\n");
break;
default:
fprintf(stream, "Unknown (%d):\r\n", format);
output_buffer(stream, data, dataLength, indent);
break;
}
}
void dump_tlv(FILE * stream,
int size,
lwm2m_data_t * dataP,
int indent)
{
int i;
for(i= 0 ; i < size ; i++)
{
print_indent(stream, indent);
fprintf(stream, "{\r\n");
print_indent(stream, indent+1);
fprintf(stream, "id: %d\r\n", dataP[i].id);
print_indent(stream, indent+1);
fprintf(stream, "type: ");
switch (dataP[i].type)
{
case LWM2M_TYPE_OBJECT:
fprintf(stream, "LWM2M_TYPE_OBJECT\r\n");
dump_tlv(stream, dataP[i].value.asChildren.count, dataP[i].value.asChildren.array, indent + 1);
break;
case LWM2M_TYPE_OBJECT_INSTANCE:
fprintf(stream, "LWM2M_TYPE_OBJECT_INSTANCE\r\n");
dump_tlv(stream, dataP[i].value.asChildren.count, dataP[i].value.asChildren.array, indent + 1);
break;
case LWM2M_TYPE_MULTIPLE_RESOURCE:
fprintf(stream, "LWM2M_TYPE_MULTIPLE_RESOURCE\r\n");
dump_tlv(stream, dataP[i].value.asChildren.count, dataP[i].value.asChildren.array, indent + 1);
break;
case LWM2M_TYPE_UNDEFINED:
fprintf(stream, "LWM2M_TYPE_UNDEFINED\r\n");
break;
case LWM2M_TYPE_STRING:
fprintf(stream, "LWM2M_TYPE_STRING\r\n");
print_indent(stream, indent + 1);
fprintf(stream, "\"%.*s\"\r\n", (int)dataP[i].value.asBuffer.length, dataP[i].value.asBuffer.buffer);
break;
case LWM2M_TYPE_OPAQUE:
fprintf(stream, "LWM2M_TYPE_OPAQUE\r\n");
output_buffer(stream, dataP[i].value.asBuffer.buffer, dataP[i].value.asBuffer.length, indent + 1);
break;
case LWM2M_TYPE_INTEGER:
fprintf(stream, "LWM2M_TYPE_INTEGER: ");
print_indent(stream, indent + 1);
fprintf(stream, "%" PRId64, dataP[i].value.asInteger);
fprintf(stream, "\r\n");
break;
case LWM2M_TYPE_FLOAT:
fprintf(stream, "LWM2M_TYPE_FLOAT: ");
print_indent(stream, indent + 1);
fprintf(stream, "%" PRId64, dataP[i].value.asInteger);
fprintf(stream, "\r\n");
break;
case LWM2M_TYPE_BOOLEAN:
fprintf(stream, "LWM2M_TYPE_BOOLEAN: ");
fprintf(stream, "%s", dataP[i].value.asBoolean ? "true" : "false");
fprintf(stream, "\r\n");
break;
case LWM2M_TYPE_OBJECT_LINK:
fprintf(stream, "LWM2M_TYPE_OBJECT_LINK\r\n");
break;
default:
fprintf(stream, "unknown (%d)\r\n", (int)dataP[i].type);
break;
}
print_indent(stream, indent);
fprintf(stream, "}\r\n");
}
}
#define CODE_TO_STRING(X) case X : return #X
static const char* prv_status_to_string(int status)
{
switch(status)
{
CODE_TO_STRING(COAP_NO_ERROR);
CODE_TO_STRING(COAP_IGNORE);
CODE_TO_STRING(COAP_201_CREATED);
CODE_TO_STRING(COAP_202_DELETED);
CODE_TO_STRING(COAP_204_CHANGED);
CODE_TO_STRING(COAP_205_CONTENT);
CODE_TO_STRING(COAP_400_BAD_REQUEST);
CODE_TO_STRING(COAP_401_UNAUTHORIZED);
CODE_TO_STRING(COAP_404_NOT_FOUND);
CODE_TO_STRING(COAP_405_METHOD_NOT_ALLOWED);
CODE_TO_STRING(COAP_406_NOT_ACCEPTABLE);
CODE_TO_STRING(COAP_500_INTERNAL_SERVER_ERROR);
CODE_TO_STRING(COAP_501_NOT_IMPLEMENTED);
CODE_TO_STRING(COAP_503_SERVICE_UNAVAILABLE);
default: return "";
}
}
void print_status(FILE * stream,
uint8_t status)
{
fprintf(stream, "%d.%02d (%s)", (status&0xE0)>>5, status&0x1F, prv_status_to_string(status));
}
| {
"content_hash": "f02997e63675cd0356a2c639c3aace9b",
"timestamp": "",
"source": "github",
"line_count": 434,
"max_line_length": 126,
"avg_line_length": 27.74884792626728,
"alnum_prop": 0.522212073403637,
"repo_name": "dr-venkman/TizenRT",
"id": "0fa7ff5b98eef8f91671234dd2d1f52531090a13",
"size": "12840",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "external/wakaama/examples/shared/commandline.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "206235"
},
{
"name": "Batchfile",
"bytes": "39014"
},
{
"name": "C",
"bytes": "30349475"
},
{
"name": "C++",
"bytes": "534795"
},
{
"name": "HTML",
"bytes": "2149"
},
{
"name": "Makefile",
"bytes": "521344"
},
{
"name": "Objective-C",
"bytes": "90599"
},
{
"name": "Perl",
"bytes": "2687"
},
{
"name": "Python",
"bytes": "31505"
},
{
"name": "Shell",
"bytes": "131159"
},
{
"name": "Tcl",
"bytes": "325812"
}
],
"symlink_target": ""
} |
package de.danoeh.antennapod.core.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import de.danoeh.antennapod.core.ClientConfig;
import de.danoeh.antennapod.core.service.playback.PlaybackService;
/** Receives media button events. */
public class MediaButtonReceiver extends BroadcastReceiver {
private static final String TAG = "MediaButtonReceiver";
public static final String EXTRA_KEYCODE = "de.danoeh.antennapod.core.service.extra.MediaButtonReceiver.KEYCODE";
public static final String EXTRA_SOURCE = "de.danoeh.antennapod.core.service.extra.MediaButtonReceiver.SOURCE";
public static final String NOTIFY_BUTTON_RECEIVER = "de.danoeh.antennapod.NOTIFY_BUTTON_RECEIVER";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Received intent");
KeyEvent event = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount()==0) {
ClientConfig.initialize(context);
Intent serviceIntent = new Intent(context, PlaybackService.class);
serviceIntent.putExtra(EXTRA_KEYCODE, event.getKeyCode());
serviceIntent.putExtra(EXTRA_SOURCE, event.getSource());
context.startService(serviceIntent);
}
}
}
| {
"content_hash": "64f641ecd3534de61a8f333200b2db93",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 114,
"avg_line_length": 40.088235294117645,
"alnum_prop": 0.7842993396918562,
"repo_name": "drabux/AntennaPod",
"id": "0bfeb1150fe4d5ae25b2fdb95ae1be93c57d7fff",
"size": "1363",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "core/src/main/java/de/danoeh/antennapod/core/receiver/MediaButtonReceiver.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "4157"
},
{
"name": "Java",
"bytes": "2132936"
},
{
"name": "Python",
"bytes": "14394"
},
{
"name": "Shell",
"bytes": "765"
}
],
"symlink_target": ""
} |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>Source Property</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache log4net SDK Documentation - Microsoft .NET Framework 4.0</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">LogLog.Source Property</h1>
</div>
</div>
<div id="nstext">
<p> The Type that generated the internal message. </p>
<div class="syntax">
<span class="lang">[Visual Basic]</span>
<br />Public ReadOnly Property Source As <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemTypeClassTopic.htm">Type</a></div>
<div class="syntax">
<span class="lang">[C#]</span>
<br />public <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemTypeClassTopic.htm">System.Type</a> Source {get;}</div>
<p>
</p>
<h4 class="dtH4">See Also</h4>
<p>
<a href="log4net.Util.LogLog.html">LogLog Class</a> | <a href="log4net.Util.html">log4net.Util Namespace</a></p>
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
<param name="Keyword" value="Source property">
</param>
<param name="Keyword" value="Source property, LogLog class">
</param>
<param name="Keyword" value="LogLog.Source property">
</param>
</object>
<hr />
<div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div>
</div>
</body>
</html> | {
"content_hash": "dbe5177d33b805b115a305b9a1db5267",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 222,
"avg_line_length": 44.18,
"alnum_prop": 0.5961973743775464,
"repo_name": "gersonkurz/manualisator",
"id": "aa1876b4e3824052b11c567a222d64e3aa337374",
"size": "2209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "manualisator/log4net-1.2.13/doc/release/sdk/log4net.Util.LogLog.Source.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "235121"
},
{
"name": "CSS",
"bytes": "15869"
},
{
"name": "HTML",
"bytes": "9723377"
},
{
"name": "JavaScript",
"bytes": "5685"
},
{
"name": "NSIS",
"bytes": "1916"
},
{
"name": "Shell",
"bytes": "1041"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mfc2Mvvm.Shell")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mfc2Mvvm.Shell")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | {
"content_hash": "1b2b15ba7440f1c3fad5c2f990016a8d",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 96,
"avg_line_length": 38.875,
"alnum_prop": 0.7491961414790996,
"repo_name": "taspeotis/MFC2MVVM",
"id": "edc830d369a19f2aa665c32eb3a4a322432754d5",
"size": "2180",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Mfc2Mvvm.Shell/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "11147"
}
],
"symlink_target": ""
} |
layout: pattern
title: Producer Consumer
folder: producer-consumer
permalink: /patterns/producer-consumer/
categories: Concurrency
tags:
- Java
- Difficulty-Intermediate
- I/O
- Reactive
---
## Intent
Producer Consumer Design pattern is a classic concurrency pattern which reduces
coupling between Producer and Consumer by separating Identification of work with Execution of
Work.

## Applicability
Use the Producer Consumer idiom when
* decouple system by separate work in two process produce and consume.
* addresses the issue of different timing require to produce work or consuming work
| {
"content_hash": "7741987c079e51b8b2826047e94a8d0d",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 94,
"avg_line_length": 27.541666666666668,
"alnum_prop": 0.794251134644478,
"repo_name": "StefanHeimberg/java-design-patterns",
"id": "1bb84c35fbb249decae56e671c7d6c481a751c2f",
"size": "665",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "producer-consumer/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5808"
},
{
"name": "Gherkin",
"bytes": "1078"
},
{
"name": "HTML",
"bytes": "38429"
},
{
"name": "Java",
"bytes": "2576417"
},
{
"name": "JavaScript",
"bytes": "1191"
},
{
"name": "Shell",
"bytes": "1718"
}
],
"symlink_target": ""
} |
package com.aquarius.effectivejava.practices.chapter04.item16;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
/**
* Created by aquarius on 2017/5/8.
*/
// 不恰当的继承
public class InstrumentedHashSet<E> extends HashSet<E> {
private int addCount;
public InstrumentedHashSet() {
}
public InstrumentedHashSet(int initCapacity, float loadFactor) {
super(initCapacity, loadFactor);
}
@Override
public boolean add(E e) {
addCount++;
return super.add(e);
}
// 因为HashSet中addAll方法会调用add方法,所以这里再修改addCount的值会多加c.size()次
@Override
public boolean addAll(Collection<? extends E> c) {
addCount = addCount + c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
public static void main(String[] args) {
InstrumentedHashSet<String> s = new InstrumentedHashSet<String>();
s.addAll(Arrays.asList("Snap", "Crackle", "Pop")); // 由于addAll的错误处理,导致addCount计算错误
System.out.println(s.getAddCount());
}
}
| {
"content_hash": "e23503839e7025a7a9ced20e7fff5ebb",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 90,
"avg_line_length": 24.066666666666666,
"alnum_prop": 0.6592797783933518,
"repo_name": "aquarius520/effective-java-practices",
"id": "f4abaa6cba831dff9bc9438bc816ca7bac652805",
"size": "1171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/aquarius/effectivejava/practices/chapter04/item16/InstrumentedHashSet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "38111"
}
],
"symlink_target": ""
} |
package emlab.gen.role.market;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.transaction.annotation.Transactional;
import agentspring.role.Role;
import agentspring.role.RoleComponent;
import cern.colt.Timer;
import emlab.gen.domain.agent.DecarbonizationModel;
import emlab.gen.domain.agent.Government;
import emlab.gen.domain.agent.NationalGovernment;
import emlab.gen.domain.gis.Zone;
import emlab.gen.domain.market.CO2Auction;
import emlab.gen.domain.market.ClearingPoint;
import emlab.gen.domain.market.electricity.ElectricitySpotMarket;
import emlab.gen.domain.market.electricity.PowerPlantDispatchPlan;
import emlab.gen.domain.market.electricity.Segment;
import emlab.gen.domain.technology.Interconnector;
import emlab.gen.domain.technology.PowerPlant;
import emlab.gen.domain.technology.Substance;
import emlab.gen.repository.Reps;
import emlab.gen.util.Utils;
/**
* Creates and clears the {@link ElectricitySpotMarket} for two {@link Zone}s. The market is divided into {@link Segment}s and cleared for each segment. A global CO2 emissions market is cleared. The
* process is iterative and the target is to let the total emissions match the cap.
*
* @author <a href="mailto:E.J.L.Chappin@tudelft.nl">Emile Chappin</a>
*
* @author <a href="mailto:A.Chmieliauskas@tudelft.nl">Alfredas Chmieliauskas</a>
*
*/
@RoleComponent
public class ClearIterativeCO2AndElectricitySpotMarketThreeCountryRole extends AbstractClearElectricitySpotMarketRole<DecarbonizationModel>
implements Role<DecarbonizationModel> {
@Autowired
private Reps reps;
@Autowired
Neo4jTemplate template;
@Override
@Transactional
public void act(DecarbonizationModel model) {
Timer timer = new Timer();
timer.start();
// find all operational power plants and store the ones operational to a
// list.
logger.info("Clearing the CO2 and electricity spot markets using iteration for 2 countries ");
// find all markets
List<ElectricitySpotMarket> electricitySpotMarkets = reps.marketRepository.findAllElectricitySpotMarketsAsList();
// find all fuel prices
Map<Substance, Double> fuelPriceMap = new HashMap<Substance, Double>();
for (Substance substance : template.findAll(Substance.class)) {
fuelPriceMap.put(substance, findLastKnownPriceForSubstance(substance));
}
// find all interconnectors
Interconnector interconnector = template.findAll(Interconnector.class).iterator().next();
// find all segments
List<Segment> segments = Utils.asList(reps.segmentRepository.findAll());
// find the EU government
Government government = template.findAll(Government.class).iterator().next();
// find national minimum CO2 prices
Map<ElectricitySpotMarket, Double> nationalMinCo2Prices = new HashMap<ElectricitySpotMarket, Double>();
Iterable<NationalGovernment> nationalGovernments = template.findAll(NationalGovernment.class);
for (NationalGovernment nG : nationalGovernments) {
if (model.isCo2TradingImplemented()) {
nationalMinCo2Prices.put(reps.marketRepository.findElectricitySpotMarketByNationalGovernment(nG), nG
.getMinNationalCo2PriceTrend().getValue(getCurrentTick()));
} else {
nationalMinCo2Prices.put(reps.marketRepository.findElectricitySpotMarketByNationalGovernment(nG), 0d);
}
}
CO2Auction co2Auction = template.findAll(CO2Auction.class).iterator().next();
if (model.isCo2TradingImplemented()) {
CO2PriceStability co2PriceStability = new CO2PriceStability();
co2PriceStability.stable = false;
co2PriceStability.positive = false;
co2PriceStability.iterationSpeedFactor = model.getIterationSpeedFactor();
co2PriceStability.co2Price = findLastKnownPriceOnMarket(co2Auction);
ClearingPoint lastClearingPointOfCo2Market = reps.clearingPointRepositoryOld.findClearingPointForMarketAndTime(co2Auction,
getCurrentTick() - 1);
if (lastClearingPointOfCo2Market != null) {
co2PriceStability.co2Emissions = lastClearingPointOfCo2Market.getVolume();
} else {
co2PriceStability.co2Emissions = 0d;
}
while (!co2PriceStability.stable) {
// logger.warn(" Determining fuel mix while iterating");
// for (EnergyProducer producer :
// reps.genericRepository.findAllAtRandom(EnergyProducer.class))
// {
// producer.act(determineFuelMixRole);
// }
// Clear the electricity markets with the expected co2Price
updatePowerPlanDispatchPlansWithNewCO2Prices(co2PriceStability.co2Price, nationalMinCo2Prices);
if (model.isLongTermContractsImplemented())
determineCommitmentOfPowerPlantsOnTheBasisOfLongTermContracts(segments);
for (Segment segment : segments) {
clearTwoConnectedElectricityMarketsAtAGivenCO2PriceForOneSegment(electricitySpotMarkets, interconnector.getCapacity(),
segment, government, co2PriceStability.co2Emissions);
}
co2PriceStability = determineStabilityOfCO2andElectricityPricesAndAdjustIfNecessary(co2PriceStability, model, government);
}
// Save the resulting CO2 price to the CO2 auction
reps.clearingPointRepositoryOld.createOrUpdateClearingPoint(co2Auction, co2PriceStability.co2Price,
co2PriceStability.co2Emissions, getCurrentTick());
} else {
if (model.isLongTermContractsImplemented())
determineCommitmentOfPowerPlantsOnTheBasisOfLongTermContracts(segments);
for (Segment segment : segments) {
clearTwoConnectedElectricityMarketsAtAGivenCO2PriceForOneSegment(electricitySpotMarkets, interconnector.getCapacity(),
segment, government, 0);
}
}
timer.stop();
logger.warn(" Market clearing took: " + timer.seconds() + "seconds.");
}
/**
* Clears a time segment of all electricity markets for a given CO2 price.
*
* @param powerPlants
* to be used
* @param markets
* to clear
* @return the total CO2 emissions
*/
@Transactional
void clearTwoConnectedElectricityMarketsAtAGivenCO2PriceForOneSegment(List<ElectricitySpotMarket> markets,
double interconnectorCapacity, Segment segment, Government government, double co2Price) {
GlobalSegmentClearingOutcome globalOutcome = new GlobalSegmentClearingOutcome();
globalOutcome.loads = determineActualDemandForSpotMarkets(segment);
globalOutcome.globalLoad = determineTotalLoadFromLoadMap(globalOutcome.loads);
// Keep track of supply per market. Start at 0.
for (ElectricitySpotMarket m : reps.marketRepository.findAllElectricitySpotMarkets()) {
globalOutcome.supplies.put(m, 0d);
}
// empty list of plants that are supplying.
double marginalPlantMarginalCost = clearGlobalMarketWithNoCapacityConstraints(segment, globalOutcome);
// For each plant in the cost-ordered list
// Determine the flow over the interconnector.
ElectricitySpotMarket firstMarket = markets.get(0);
double loadInFirstMarket = globalOutcome.loads.get(firstMarket);
double supplyInFirstMarket = globalOutcome.supplies.get(firstMarket);
// Interconnector flow defined as from market A --> market B = positive
double interconnectorFlow = supplyInFirstMarket - loadInFirstMarket;
logger.info("Before market coupling interconnector flow: {}, available interconnector capacity {}", interconnectorFlow,
interconnectorCapacity);
// if interconnector is not limiting, there is one price
if (Math.abs(interconnectorFlow) <= interconnectorCapacity) {
// Set the price to the bid of the marginal plant.
for (ElectricitySpotMarket market : markets) {
double supplyInThisMarket = globalOutcome.supplies.get(market);
globalOutcome.globalSupply += supplyInThisMarket;
if (globalOutcome.globalLoad <= globalOutcome.globalSupply) {
globalOutcome.globalPrice = marginalPlantMarginalCost;
} else {
globalOutcome.globalPrice = market.getValueOfLostLoad();
}
// updatePowerDispatchPlansAfterTwoCountryClearingIsComplete(segment);
reps.clearingPointRepositoryOld.createOrUpdateSegmentClearingPoint(segment, market, marginalPlantMarginalCost,
supplyInThisMarket * segment.getLengthInHours(), getCurrentTick());
logger.info("Stored a system-uniform price for market " + market + " / segment " + segment + " -- supply "
+ supplyInThisMarket + " -- price: " + marginalPlantMarginalCost);
}
} else {
MarketSegmentClearingOutcome marketOutcomes = new MarketSegmentClearingOutcome();
for (ElectricitySpotMarket m : markets) {
marketOutcomes.supplies.put(m, 0d);
marketOutcomes.prices.put(m, m.getValueOfLostLoad());
}
// else there are two prices
logger.info("There should be multiple prices, but first we should do market coupling.");
boolean firstImporting = true;
if (interconnectorFlow > 0) {
firstImporting = false;
}
boolean first = true;
for (ElectricitySpotMarket market : markets) {
// Update the load for this market. Which is market's true load
// +/- the full interconnector capacity, based on direction of
// the flow
if ((first && firstImporting) || (!first && !firstImporting)) {
marketOutcomes.loads.put(market, globalOutcome.loads.get(market) - interconnectorCapacity);
} else {
marketOutcomes.loads.put(market, globalOutcome.loads.get(market) + interconnectorCapacity);
}
first = false;
}
// For each plant in the cost-ordered list
clearTwoInterconnectedMarketsGivenAnInterconnectorAdjustedLoad(segment, markets, marketOutcomes);
// updatePowerDispatchPlansAfterTwoCountryClearingIsComplete(segment);
for (ElectricitySpotMarket market : markets) {
if (marketOutcomes.supplies.get(market) < marketOutcomes.loads.get(market)) {
marketOutcomes.prices.put(market, market.getValueOfLostLoad());
}
}
// Only for debugging purposes
// logger.warn("Outcomes: {}", marketOutcomes);
// for (ElectricitySpotMarket market : markets) {
// logger.warn(
// "Segment " + segment.getSegmentID() +
// ": PPD capacity: {} MW, PP capacity: {}, Peak-Query: "
// +
// reps.powerPlantRepository.calculatePeakCapacityOfOperationalPowerPlantsInMarket(market,
// getCurrentTick()),
// determineCapacityInMarketBasedOnTreemapAndDispatchPlans(marginalCostMap,
// segment, market, markets),
// determinePeakCapacityInMarketBasedOnTreemapAndPowerPlants(marginalCostMap,
// segment, market, markets)
// + "Normal Capacity: "
// +
// determineCapacityInMarketBasedOnTreemapAndPowerPlants(marginalCostMap,
// market, markets)
// + "Query Capacity: "
// +
// reps.powerPlantRepository.calculateCapacityOfOperationalPowerPlantsInMarket(market,
// getCurrentTick()));
// }
for (ElectricitySpotMarket market : markets) {
reps.clearingPointRepositoryOld.createOrUpdateSegmentClearingPoint(segment, market, marketOutcomes.prices.get(market),
marketOutcomes.supplies.get(market) * segment.getLengthInHours(), getCurrentTick());
// logger.warn("Stored a market specific price for market " +
// market + " / segment " + segment + " -- supply "
// + marketOutcomes.supplies.get(market) + " -- demand: " +
// marketOutcomes.loads.get(market) + " -- price: "
// + marketOutcomes.prices.get(market));
}
@SuppressWarnings("unused")
int i = 0;
}
}
void clearTwoInterconnectedMarketsGivenAnInterconnectorAdjustedLoad(Segment segment, List<ElectricitySpotMarket> markets,
MarketSegmentClearingOutcome marketOutcomes) {
for (PowerPlantDispatchPlan plan : reps.powerPlantDispatchPlanRepository.findSortedPowerPlantDispatchPlansForSegmentForTime(
segment, getCurrentTick())) {
// If it is in the right market
PowerPlant plant = plan.getPowerPlant();
ElectricitySpotMarket myMarket = (ElectricitySpotMarket) plan.getBiddingMarket();
// Make it produce as long as there is load.
double plantSupply = determineProductionOnSpotMarket(plan, marketOutcomes.supplies.get(myMarket),
marketOutcomes.loads.get(myMarket));
if (plantSupply > 0) {
// Plant is producing, store the information to
// determine price and so on.
marketOutcomes.supplies.put(myMarket, marketOutcomes.supplies.get(myMarket) + plantSupply);
marketOutcomes.prices.put(myMarket, plan.getPrice());
// logger.warn("Storing price: {} for plant {} in market " +
// myMarket, plantCost.getValue(), plant);
}
}
}
@Override
public Reps getReps() {
return reps;
}
}
| {
"content_hash": "651f4c8bf1c14eca49474763c0a3a346",
"timestamp": "",
"source": "github",
"line_count": 321,
"max_line_length": 198,
"avg_line_length": 44.89719626168224,
"alnum_prop": 0.6571606994171524,
"repo_name": "Kaveri3012/emlab-generation",
"id": "10218f304f03dda751fda1e7912afdb5bd20075e",
"size": "15182",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "emlab-generation/src/main/java/emlab/gen/role/market/ClearIterativeCO2AndElectricitySpotMarketThreeCountryRole.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "791891"
},
{
"name": "Python",
"bytes": "21242"
},
{
"name": "R",
"bytes": "53400"
},
{
"name": "Shell",
"bytes": "13390"
}
],
"symlink_target": ""
} |
"""
.. module:: utilities
:platform: Unix
:synopsis: Helpful function for ScatterBrane
.. moduleauthor:: Katherine Rosenfeld <krosenf@gmail.com>
.. moduleauthor:: Michael Johnson
"""
from __future__ import print_function
import numpy as np
from scipy.interpolate import RectBivariateSpline
from scipy.ndimage.filters import gaussian_filter
from astropy.io import fits
def smoothImage(img,dx,fwhm):
'''
Returns Image smoothed by a gaussian kernel.
:param img: ``(n, n)``
numpy array
:param dx: scalar
Pixel scale in microarcseconds
:param fwhm: scalar
Gaussian full width at half maximum in microarcseconds
'''
return gaussian_filter(img,fwhm/(2*np.sqrt(np.log(4)))/dx)
def getCoherenceLength(theta,wavelength=1.3e-3,magnification=0.448):
'''
:param theta: scalar
FWHM of scattering kernel at 1 cm in milli-arcseconds.
:param wavelength: (optional) scalar
Observing wavelength in meters
:param magnification: (optional) scalar
Magnification factor (scatterer-observer)/(source-scatterer).
:returns: scalar
Coherence length in km.
'''
#return (wavelength*1e-3)*np.sqrt(np.log(4))/(np.pi*np.sqrt(1+magnification)**2*np.radians(1e-3/3600*theta*(wavelength*1e2)**2))
return (wavelength*1e-3)*np.sqrt(np.log(4))/(np.pi*(1+magnification)*np.radians(1e-3/3600*theta*(wavelength*1e2)**2))
def ensembleSmooth(img,dx,brane,return_kernel=False):
'''
Generates ensemble averaged image given scattering kernel parameters.
:param img: ``(n, n)``
numpy array
:param dx: scalar
Pixel scale in microarcseconds
:param brane: Brane object.
:param return_kernel: (optional) bool
Return tuple with uv kernel (:func:`nump.fft.rfft2` format). See :func:`getUVKernel` for an alternate method.
'''
nx = img.shape[0]
# scattering kernel parameters in wavelengths
sigma_maj = brane.wavelength*np.sqrt(np.log(4)) / (np.pi*(1.+brane.m)*brane.r0) / (2*np.sqrt(np.log(4)))
sigma_min = sigma_maj / brane.anisotropy
v = np.dot(np.transpose([np.fft.fftfreq(nx,d=dx*np.radians(1.)/(3600*1e6))]),[np.ones(nx/2 + 1)])
u = np.dot(np.transpose([np.ones(nx)]),[np.fft.rfftfreq(nx,d=dx*np.radians(1.)/(3600*1e6))])
# rotate
if brane.pa != None:
theta = np.radians(90-brane.pa)
else:
theta = np.radians(0.)
u_ = np.cos(theta)*u - np.sin(theta)*v
v = np.sin(theta)*u + np.cos(theta)*v
# rotate
G = np.exp(-2*np.pi**2*(u_**2*sigma_maj**2 + v**2*sigma_min**2))
V = np.fft.rfft2(img)
if return_kernel:
return (np.fft.irfft2(V*G,s=img.shape),G)
else:
return np.fft.irfft2(V*G,s=img.shape)
def getUVKernel(u,v,brane):
'''
Get ensemble kernel in visibility plane for specified uv points. See func:`ensembleSmooth` for an althernate method.
:param u: ``(n, )``
Samples of u in units of wavelengths.
:param v: ``(n, )``
Samples of v in units of wavelengths.
:param brane: Brane object
:returns: ``(n, )`` Ensemble kernel complex visibility
'''
# scattering kernel parameters in wavelengths
sigma_maj = brane.wavelength*np.sqrt(np.log(4)) / (np.pi*(1.+brane.m)*brane.r0) / (2*np.sqrt(np.log(4)))
sigma_min = sigma_maj / brane.anisotropy
# rotate
if brane.pa != None:
theta = np.radians(90-brane.pa)
else:
theta = np.radians(0.)
u_ = np.cos(theta)*u - np.sin(theta)*v
v_ = np.sin(theta)*u + np.cos(theta)*v
# rotate and return
return np.exp(-2*np.pi**2*(u_**2*sigma_maj**2 + v_**2*sigma_min**2))
def loadSettings(filename):
'''
Loads simulation settings from a file generated by :func:`Brane.save_settings`.
:param filename: string
File name that contains simulation settings.
:returns: A dictionary with simulation settings.
'''
return dict(np.genfromtxt(filename,\
dtype=[('a','|S10'),('f','float')],delimiter='\t',autostrip=True))
def regrid(a,inx,idx,onx,odx):
'''
Regrids array with a new resolution and pixel number.
:param a: ``(n, n)``
Input numpy image
:param inx: int
Number of input pixels on a side
:param idx: scalar
Input resolution element
:param onx: int
Number of output pixels on a side
:param odx: scalar
Output resolution element
:returns: Array regridded to the new resolution and field of view.
'''
x = idx * (np.arange(inx) - 0.5 * (inx - 1))
f = RectBivariateSpline(x,x,a)
x_ = odx * (np.arange(onx) - 0.5 * (onx - 1))
xx_,yy_ = np.meshgrid(x_,x_,indexing='xy')
m = f.ev(yy_.flatten(),xx_.flatten()).reshape((onx,onx))
return m*(odx/idx)**2
def writefits(m,dx,dest='image.fits',obsra=266.4168370833333,obsdec=-29.00781055555555,freq=230e9):
'''
Write fits file with header. Defaults are set for Sgr A* at 1.3mm.
:param m: ``(n, n)``
numpy image array
:param dx: scalar
Pixel size in microarcseconds
:param dest: (optional) string
Output fits file name
:param obsra: (optional) scalar
Source right ascension
:param obsdec: (optional) scalar
Source declination
'''
hdu = fits.PrimaryHDU(m)
hdu.header['CDELT1'] = -1*dx*np.radians(1.)/(3600.*1e6)
hdu.header['CDELT2'] = dx*np.radians(1.)/(3600.*1e6)
hdu.header['OBSRA'] = obsra
hdu.header['OBSDEC'] = obsdec
hdu.header['FREQ'] = freq
hdu.writeto(dest,clobber=True)
def FTElementFast(img,dx,baseline):
'''
Return complex visibility.
:param img: ``(n, n)``
numpy image array
:param dx: scalar
Pixel size in microarcseconds
:param baseline: ``(2, )``
(u,v) point in wavelengths
.. note:: To shift center try multipliny by :math:`\\mathrm{exp}(\\pi i u n_x\\Delta_x)` and watch out for the axis orientation.
'''
nx = img.shape[-1]
du = 1./(nx * dx * np.radians(1.)/(3600*1e6))
ind = np.arange(nx)
return np.sum(img * np.dot(\
np.transpose([np.exp(-2j*np.pi/du/nx*baseline[1]*np.flipud(ind))]),\
[np.exp(-2j*np.pi/du/nx*baseline[0]*ind)]))
| {
"content_hash": "f2fb37230de161ebe2fb3bc20451a8ea",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 132,
"avg_line_length": 32.58201058201058,
"alnum_prop": 0.6295875284183177,
"repo_name": "krosenfeld/scatterbrane",
"id": "318109b52f59f97f58544d578401e4239d639a0e",
"size": "6159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scatterbrane/utilities.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "40405"
}
],
"symlink_target": ""
} |
using System.Web.Mvc;
using System.Web.Routing;
using MvcContrib.Routing;
namespace Commencement
{
public class RouteConfigurator
{
public virtual void RegisterRoutes()
{
RouteCollection routes = RouteTable.Routes;
routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
MvcRoute.MappUrl("{controller}/{action}/{id}")
.WithDefaults(new { controller = "Home", action = "Index", id = "" })
.AddWithName("Default", routes);
}
}
} | {
"content_hash": "8f1c036baaf78fd1c99d2ebb93b5b7b3",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 91,
"avg_line_length": 30.40909090909091,
"alnum_prop": 0.5485799701046338,
"repo_name": "ucdavis/Commencement",
"id": "b625288ed595cd67453c56d5c5e45254d07b558e",
"size": "671",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Commencement/RouteConfigurator.asax.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "306718"
},
{
"name": "C#",
"bytes": "2117514"
},
{
"name": "CSS",
"bytes": "262826"
},
{
"name": "HTML",
"bytes": "88445"
},
{
"name": "JavaScript",
"bytes": "665621"
},
{
"name": "SCSS",
"bytes": "3253"
},
{
"name": "TSQL",
"bytes": "333839"
},
{
"name": "XSLT",
"bytes": "12947"
}
],
"symlink_target": ""
} |
export * from './parseConformance';
export * from "./model/bundle";
export * from './validator';
export * from './fhir';
export * from './fhirPath';
| {
"content_hash": "fbca25e831b619bc09e82f157c1de59d",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 35,
"avg_line_length": 29.8,
"alnum_prop": 0.6577181208053692,
"repo_name": "lantanagroup/FHIR.js",
"id": "fa69bfccfc7a279987621a24fdd9906a1e93fa83",
"size": "149",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.d.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1769"
},
{
"name": "JavaScript",
"bytes": "78203"
},
{
"name": "PowerShell",
"bytes": "203"
},
{
"name": "TypeScript",
"bytes": "126804"
}
],
"symlink_target": ""
} |
package academy.learnprogramming.methods;
/**
* @author goran on 13/07/2017.
*/
public class ReturningDataFromMethods {
public static void main(String[] args) {
int number = 2;
String word = "xyz";
// number(number);
number = number(number); // 3
// word = word(word); // xyza
word(word);
System.out.println(number + word); //3xyz
}
public static int number(int number) {
number++;
return number;
}
public static String word(String word) {
word += "a"; // xyza
return word;
}
}
| {
"content_hash": "62f7bef9058440c91382018c0a582d5a",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 49,
"avg_line_length": 19.9,
"alnum_prop": 0.5527638190954773,
"repo_name": "jamalgithub/workdev",
"id": "96f11f7468b89cc54113f0150fbcfcd34ba3f87b",
"size": "597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OCA/src/academy/learnprogramming/methods/ReturningDataFromMethods.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12727"
},
{
"name": "Java",
"bytes": "2899130"
},
{
"name": "PLSQL",
"bytes": "5617"
},
{
"name": "TSQL",
"bytes": "2886"
}
],
"symlink_target": ""
} |
import { UIComponent } from "../../settings/UIFeature";
import { ComponentVisibilityCustomisations } from "../ComponentVisibility";
export function shouldShowComponent(component: UIComponent): boolean {
return ComponentVisibilityCustomisations.shouldShowComponent?.(component) ?? true;
}
| {
"content_hash": "83071e3888a22b10aaa2903e0e21c088",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 86,
"avg_line_length": 36.875,
"alnum_prop": 0.7830508474576271,
"repo_name": "matrix-org/matrix-react-sdk",
"id": "11b8a40969560524ee97d6986c90279475e2b97e",
"size": "873",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/customisations/helpers/UIComponents.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "984691"
},
{
"name": "Dockerfile",
"bytes": "1550"
},
{
"name": "HTML",
"bytes": "1043"
},
{
"name": "JavaScript",
"bytes": "33429"
},
{
"name": "Perl",
"bytes": "10945"
},
{
"name": "Python",
"bytes": "5019"
},
{
"name": "Shell",
"bytes": "5451"
},
{
"name": "TypeScript",
"bytes": "9543345"
}
],
"symlink_target": ""
} |
package com.thoughtworks.go.util;
import org.xml.sax.InputSource;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class XpathUtils {
private static XPathFactory xPathFactory = XPathFactory.newInstance();
public static String evaluate(File file, String xpath)
throws XPathExpressionException, IOException {
try(InputStream stream = new FileInputStream(file)) {
InputSource inputSource = new InputSource(stream);
return evaluate(xPathFactory, inputSource, xpath);
}
}
public static boolean nodeExists(File file, String xpath) throws XPathExpressionException, IOException {
try (FileInputStream stream = new FileInputStream(file)) {
return nodeExists(stream, xpath);
}
}
public static boolean nodeExists(InputStream stream, String xpath) throws XPathExpressionException {
return nodeExists(new InputSource(stream), xpath);
}
public static boolean nodeExists(InputSource inputSource, String xpath) throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPathExpression expression = factory.newXPath().compile(xpath);
Boolean b = (Boolean) expression.evaluate(inputSource, XPathConstants.BOOLEAN);
return b != null && b;
}
public static boolean nodeExists(String xmlPartial, String xpath) throws XPathExpressionException {
return nodeExists(new ByteArrayInputStream(xmlPartial.getBytes(StandardCharsets.UTF_8)), xpath);
}
private static String evaluate(XPathFactory factory, InputSource inputSource, String xpath)
throws XPathExpressionException {
XPathExpression expression = factory.newXPath().compile(xpath);
return expression.evaluate(inputSource).trim();
}
}
| {
"content_hash": "88086980288611534900d7520f7b288e",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 109,
"avg_line_length": 38.32692307692308,
"alnum_prop": 0.731058705469142,
"repo_name": "ketan/gocd",
"id": "c1952ce13311ecfe8007c9fee3e90892ca8140ee",
"size": "2594",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "config/config-api/src/main/java/com/thoughtworks/go/util/XpathUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "474"
},
{
"name": "CSS",
"bytes": "1578"
},
{
"name": "EJS",
"bytes": "1626"
},
{
"name": "FreeMarker",
"bytes": "48379"
},
{
"name": "Groovy",
"bytes": "2439874"
},
{
"name": "HTML",
"bytes": "275640"
},
{
"name": "Java",
"bytes": "21184582"
},
{
"name": "JavaScript",
"bytes": "837258"
},
{
"name": "NSIS",
"bytes": "24216"
},
{
"name": "Ruby",
"bytes": "426294"
},
{
"name": "SCSS",
"bytes": "661917"
},
{
"name": "Shell",
"bytes": "13847"
},
{
"name": "TypeScript",
"bytes": "4435721"
},
{
"name": "XSLT",
"bytes": "206746"
}
],
"symlink_target": ""
} |
<!doctype HTML>
<!-- The second div squashes into the first, and had a fractional position greater than 0.5. This tests that pixel snapping for squashed layers
matches that of non-squashed layers -->
<div style="position: absolute; width: 200px; height: 200px; left: 0px; top: 0px; will-change: transform; background-color: lightgreen"></div>
<div style="position: absolute; width: 1px; height: 1px; left: 0px; top:0.6px; background-color: lightgray"></div>
| {
"content_hash": "af556fb77067496b46267401e897eacf",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 143,
"avg_line_length": 66.42857142857143,
"alnum_prop": 0.7333333333333333,
"repo_name": "chromium/chromium",
"id": "037edd7e7a529a3a47b2bba520b94a8f6784b9a3",
"size": "465",
"binary": false,
"copies": "9",
"ref": "refs/heads/main",
"path": "third_party/blink/web_tests/compositing/squashing/subpixel-rounding.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package io.netty.handler.ssl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class OptionalSslHandlerTest {
private static final String SSL_HANDLER_NAME = "sslhandler";
private static final String HANDLER_NAME = "handler";
@Mock
private ChannelHandlerContext context;
@Mock
private SslContext sslContext;
@Mock
private ChannelPipeline pipeline;
@BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(context.pipeline()).thenReturn(pipeline);
}
@Test
public void handlerRemoved() throws Exception {
OptionalSslHandler handler = new OptionalSslHandler(sslContext);
final ByteBuf payload = Unpooled.copiedBuffer("plaintext".getBytes());
try {
handler.decode(context, payload, null);
verify(pipeline).remove(handler);
} finally {
payload.release();
}
}
@Test
public void handlerReplaced() throws Exception {
final ChannelHandler nonSslHandler = Mockito.mock(ChannelHandler.class);
OptionalSslHandler handler = new OptionalSslHandler(sslContext) {
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
return nonSslHandler;
}
@Override
protected String newNonSslHandlerName() {
return HANDLER_NAME;
}
};
final ByteBuf payload = Unpooled.copiedBuffer("plaintext".getBytes());
try {
handler.decode(context, payload, null);
verify(pipeline).replace(handler, HANDLER_NAME, nonSslHandler);
} finally {
payload.release();
}
}
@Test
public void sslHandlerReplaced() throws Exception {
final SslHandler sslHandler = Mockito.mock(SslHandler.class);
OptionalSslHandler handler = new OptionalSslHandler(sslContext) {
@Override
protected SslHandler newSslHandler(ChannelHandlerContext context, SslContext sslContext) {
return sslHandler;
}
@Override
protected String newSslHandlerName() {
return SSL_HANDLER_NAME;
}
};
final ByteBuf payload = Unpooled.wrappedBuffer(new byte[] { 22, 3, 1, 0, 5 });
try {
handler.decode(context, payload, null);
verify(pipeline).replace(handler, SSL_HANDLER_NAME, sslHandler);
} finally {
payload.release();
}
}
@Test
public void decodeBuffered() throws Exception {
OptionalSslHandler handler = new OptionalSslHandler(sslContext);
final ByteBuf payload = Unpooled.wrappedBuffer(new byte[] { 22, 3 });
try {
handler.decode(context, payload, null);
verifyZeroInteractions(pipeline);
} finally {
payload.release();
}
}
}
| {
"content_hash": "3a9f63a0195bca4372e8c4b7872665fe",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 102,
"avg_line_length": 31.46788990825688,
"alnum_prop": 0.643731778425656,
"repo_name": "tbrooks8/netty",
"id": "36ff3de72e3227fdb8b6d8dd9b373d229464353d",
"size": "4065",
"binary": false,
"copies": "6",
"ref": "refs/heads/4.1",
"path": "handler/src/test/java/io/netty/handler/ssl/OptionalSslHandlerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "212351"
},
{
"name": "CSS",
"bytes": "49"
},
{
"name": "Groovy",
"bytes": "1755"
},
{
"name": "HTML",
"bytes": "21064"
},
{
"name": "Java",
"bytes": "18199255"
},
{
"name": "JavaScript",
"bytes": "16232"
},
{
"name": "Makefile",
"bytes": "1814"
},
{
"name": "Shell",
"bytes": "24488"
}
],
"symlink_target": ""
} |
(function(root){
// Let's borrow a couple of things from Underscore that we'll need
// _.each
var breaker = {},
AP = Array.prototype,
OP = Object.prototype,
hasOwn = OP.hasOwnProperty,
toString = OP.toString,
forEach = AP.forEach,
indexOf = AP.indexOf,
slice = AP.slice;
var _each = function( obj, iterator, context ) {
var key, i, l;
if ( !obj ) {
return;
}
if ( forEach && obj.forEach === forEach ) {
obj.forEach( iterator, context );
} else if ( obj.length === +obj.length ) {
for ( i = 0, l = obj.length; i < l; i++ ) {
if ( i in obj && iterator.call( context, obj[i], i, obj ) === breaker ) {
return;
}
}
} else {
for ( key in obj ) {
if ( hasOwn.call( obj, key ) ) {
if ( iterator.call( context, obj[key], key, obj) === breaker ) {
return;
}
}
}
}
};
// _.isFunction
var _isFunction = function( obj ) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
// _.extend
var _extend = function( obj ) {
_each( slice.call( arguments, 1), function( source ) {
var prop;
for ( prop in source ) {
if ( source[prop] !== void 0 ) {
obj[ prop ] = source[ prop ];
}
}
});
return obj;
};
// $.inArray
var _inArray = function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
};
// And some jQuery specific helpers
var class2type = {};
// Populate the class2type map
_each("Boolean Number String Function Array Date RegExp Object".split(" "), function(name, i) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
var _type = function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
};
// Now start the jQuery-cum-Underscore implementation. Some very
// minor changes to the jQuery source to get this working.
// Internal Deferred namespace
var _d = {};
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
_each( options.split( /\s+/ ), function( flag ) {
object[ flag ] = true;
});
return object;
}
_d.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
_extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
_each( args, function( arg ) {
var type = _type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
_each( arguments, function( arg ) {
var index;
while( ( index = _inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return _inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
_d.Deferred = function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", _d.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", _d.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", _d.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return _d.Deferred(function( newDefer ) {
_each( tuples, function( tuple, i ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( _isFunction( fn ) ?
function() {
var returned;
try { returned = fn.apply( this, arguments ); } catch(e){
newDefer.reject(e);
return;
}
if ( returned && _isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action !== "notify" ? 'resolveWith' : action + 'With']( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? _extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
_each( tuples, function( tuple, i ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
};
// Deferred helper
_d.when = function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = ( _type(subordinate) === 'array' && arguments.length === 1 ) ? subordinate : slice.call( arguments ),
length = resolveValues.length;
if ( _type(subordinate) === 'array' && subordinate.length === 1 ) {
subordinate = subordinate[ 0 ];
}
// the count of uncompleted subordinates
var remaining = length !== 1 || ( subordinate && _isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : _d.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && _isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
};
// Try exporting as a Common.js Module
if ( typeof module !== "undefined" && module.exports ) {
module.exports = _d;
// Or mixin to Underscore.js
} else if ( typeof root._ !== "undefined" ) {
root._.mixin(_d);
// Or assign it to window._
} else {
root._ = _d;
}
})(this); | {
"content_hash": "0ae7b639b4cd2969098d1f9ee1ec984b",
"timestamp": "",
"source": "github",
"line_count": 449,
"max_line_length": 138,
"avg_line_length": 29.305122494432073,
"alnum_prop": 0.4940720474236206,
"repo_name": "astronaughts/simple-cw-titanium",
"id": "f0f6957a74a96f6536cd17200c618d67853a32c7",
"size": "13158",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/vendor/simple-cw-titanium/underscore.deferred.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "421"
}
],
"symlink_target": ""
} |
class NumGen
{
public:
NumGen (int start = 0) : current(start) { }
int operator() ()
{
return current++;
}
private:
int current;
};
#endif
| {
"content_hash": "ee3115ae211fe790b090eedad5a339e3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 12.923076923076923,
"alnum_prop": 0.5357142857142857,
"repo_name": "jmoles/laser-patroll",
"id": "03e494497db3d969cedb51ff7a0d7f3a239fb6d5",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/NumGen.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "41089"
},
{
"name": "TeX",
"bytes": "38192"
}
],
"symlink_target": ""
} |
<div class="row center page-header">
<h4 class="text-center">{{title}}</h4>
</div>
<div class="row row-padded">
<p>
The buttons below run sets of trivial REST-like requests using the
<a target="_blank" href="http://docs.angularjs.org/api/ng.$http">ng.$https</a>
service (via HTTP) or the
<a target="_blank" href="https://github.com/exratione/angularjs-websocket-transport">httpOverWebSocket</a>
service (via WebSocket). The requests run either in parallel or in series.
</p>
<ul>
<li>
Response times are displayed in the table as the responses arrive.
</li>
<li>
Chromium caches concurrent HTTP GET requests made to the same URL.
</li>
<li>
The Express server uses Keep Alive, and delays each response by 50ms.
</li>
</ul>
</div>
<div class="row row-spacer"></div>
<div class="row row-padded">
<div class="col-md-3">
<button type="button" class="btn btn-primary" data-ng-click="httpParallel()">HTTP Parallel</button>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-primary" data-ng-click="httpSeries()">HTTP Series</button>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-primary" data-ng-click="httpOverWebSocketParallel()">WebSocket Parallel</button>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-primary" data-ng-click="httpOverWebSocketSeries()">WebSocket Series</button>
</div>
</div>
<div class="row row-padded text-center">
<form class="form-inline">
<div class="form-group">
Issue
</div>
<div class="form-group">
<select
class="form-control"
data-ng-model="count"
data-ng-options="value for value in countOptions"
></select>
</div>
<div class="form-group">
requests
</div>
<div class="form-group">
<select
class="form-control"
data-ng-model="useCache"
data-ng-options="item.value as item.label for item in useCacheOptions"
></select>
</div>
<div class="form-group">
a client cache enabled.
</div>
</form>
</div>
<div class="row row-padded" data-ng-show="run.ended">
<div class="alert alert-success">
Test completed in {{run.elapsed}}ms.
</div>
</div>
<div class="row row-spacer"></div>
<div class="row row-padded">
<table class="table table-bordered">
<tr>
<th class="number">#</th>
<th class="status">Status</th>
<th class="elapsed">Request Duration (ms)</th>
<th class="elapsed">Cached Response?</th>
</tr>
<tr class="warning" data-ng-hide="results.length">
<td class="text-center" colspan="4">
No test results.
</td>
</tr>
<tr data-ng-repeat="result in results">
<td>{{result.index}}</td>
<td>{{resultStatus($index)}}</td>
<td>{{result.elapsed}}</td>
<td>
<span data-ng-show="result.cached">Yes</span>
<span data-ng-hide="result.cached">No</span>
</td>
</tr>
</table>
</div>
| {
"content_hash": "fcb01626a37891077d776636d2263a33",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 121,
"avg_line_length": 29.54901960784314,
"alnum_prop": 0.6167883211678832,
"repo_name": "exratione/angularjs-websocket-transport",
"id": "26b5fbf97bc300b136ba40947ddbd5c85f410a95",
"size": "3015",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src-example/client/partial/comparison.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "292"
},
{
"name": "JavaScript",
"bytes": "161312"
},
{
"name": "Ruby",
"bytes": "8200"
}
],
"symlink_target": ""
} |
body,a,table,div,span,td,th,input,select,p,li,textarea{font-size:9pt;font-family:宋体}
input.dlgBtnCommon {width:60px}
input.dlgBtnBrowse {width:63px;height:18px;margin-left:2px;padding-top:0px;}
input.dlgBtnFind {width:80px}
body {margin:0px;padding:0px;border:0px}
.Menu_Image, .Menu_Image_Disabled{overflow:hidden;width:16px;height:16px;margin:2px;background-repeat: no-repeat;}
.Menu_Image img, .Menu_Image_Disabled img{position: relative;}
.Menu_Image_Disabled img {FILTER: gray}
table.Menu_Box {border:1px solid #DE8484;background-color:#FFFCFC}
td.Menu_Box {padding:2px 4px 2px 2px;}
td.MouseOver {height:20px;border:1px solid #000080;padding:0px;background-color:#FFEEC2;cursor:default;}
td.MouseOut,td.MouseDisabled {height:20px;border:0px;padding:1px;cursor:default;}
td.Menu_Label, td.Menu_Label_Disabled {white-space: nowrap;padding-left:3px;vertical-align:middle;color:#000000;padding-right:2px}
td.Menu_Label_Disabled {color:#8D8D8D}
td.Menu_Sep {padding:1px 0px 1px 24px;}
table.Menu_Sep {width:100%;height:1px;border-width:1px 0px 0px 0px;border-style:solid;border-color:#FCE0E0;}
| {
"content_hash": "fc5fdb9e0c3dd48ca434f956c3914ee6",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 130,
"avg_line_length": 47,
"alnum_prop": 0.7641843971631206,
"repo_name": "royalwang/saivi",
"id": "9ed3da120936fdbc8054e51c20b88d1db34c7c78",
"size": "1132",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tpl/editor/skin/flat8/menuarea.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "30814"
},
{
"name": "ActionScript",
"bytes": "28251"
},
{
"name": "ApacheConf",
"bytes": "931"
},
{
"name": "CSS",
"bytes": "16883296"
},
{
"name": "HTML",
"bytes": "16526868"
},
{
"name": "Java",
"bytes": "11028"
},
{
"name": "JavaScript",
"bytes": "21292928"
},
{
"name": "Limbo",
"bytes": "6033"
},
{
"name": "PHP",
"bytes": "10997419"
},
{
"name": "Ruby",
"bytes": "2434"
},
{
"name": "Shell",
"bytes": "1414"
},
{
"name": "Smarty",
"bytes": "30131"
}
],
"symlink_target": ""
} |
package com.mongodb.jvm.json.generic;
import java.io.IOException;
import java.util.HashMap;
import org.bson.types.MaxKey;
import com.threecrickets.jvm.json.JsonContext;
import com.threecrickets.jvm.json.JsonEncoder;
import com.threecrickets.jvm.json.generic.MapEncoder;
/**
* A JSON encoder for a BSON {@link MaxKey}.
*
* @author Tal Liron
*/
public class MaxKeyEncoder implements JsonEncoder
{
//
// JsonEncoder
//
public boolean canEncode( Object object, JsonContext context )
{
return object instanceof MaxKey;
}
public void encode( Object object, JsonContext context ) throws IOException
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put( "maxKey", 1 );
new MapEncoder().encode( map, context );
}
}
| {
"content_hash": "370658174eac8924370df7976ccccbee",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 76,
"avg_line_length": 20.944444444444443,
"alnum_prop": 0.7347480106100795,
"repo_name": "tliron/mongodb-jvm",
"id": "6d7e55ff667241383766efaf77e1922fa77b34f0",
"size": "1147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/mongodb-jvm/source/com/mongodb/jvm/json/generic/MaxKeyEncoder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "14188"
},
{
"name": "Java",
"bytes": "152505"
},
{
"name": "JavaScript",
"bytes": "163921"
}
],
"symlink_target": ""
} |
package oauth
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"golang.org/x/net/context"
"golang.org/x/oauth2"
)
// Retrieve a token, saves the token, then returns the generated client.
// Function name must be uppercase to export from library and easily accessible from main code
func GetClient(config *oauth2.Config) *http.Client {
tokenFile := "token.json"
tok, err := tokenFromFile(tokenFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokenFile, tok)
}
return config.Client(context.Background(), tok)
}
// Request a token from the web, then returns the retrieved token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web %v", err)
}
return tok
}
// Retrieves a token from a local file.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
tok := &oauth2.Token{}
err = json.NewDecoder(f).Decode(tok)
return tok, err
}
// Saves a token to a file path.
func saveToken(path string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
} | {
"content_hash": "ef86ee40fe4b0139a9eb3696121863eb",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 94,
"avg_line_length": 31.73846153846154,
"alnum_prop": 0.5841008240426563,
"repo_name": "demoforwork/public",
"id": "64941c54552a530870fb4b28f3151808777905f9",
"size": "2160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "oauth/oauth.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "488"
},
{
"name": "Go",
"bytes": "32037"
},
{
"name": "HTML",
"bytes": "243482"
},
{
"name": "JavaScript",
"bytes": "365140"
},
{
"name": "Python",
"bytes": "2015100"
}
],
"symlink_target": ""
} |
/*============================================================================
This C header file is part of the SoftFloat IEC/IEEE Floating-point Arithmetic
Package, Release 2b.
Written by John R. Hauser. This work was made possible in part by the
International Computer Science Institute, located at Suite 600, 1947 Center
Street, Berkeley, California 94704. Funding was partially provided by the
National Science Foundation under grant MIP-9311980. The original version
of this code was written as part of a project to build a fixed-point vector
processor in collaboration with the University of California at Berkeley,
overseen by Profs. Nelson Morgan and John Wawrzynek. More information
is available through the Web page `http://www.cs.berkeley.edu/~jhauser/
arithmetic/SoftFloat.html'.
THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE. Although reasonable effort has
been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT TIMES
RESULT IN INCORRECT BEHAVIOR. USE OF THIS SOFTWARE IS RESTRICTED TO PERSONS
AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ALL LOSSES,
COSTS, OR OTHER PROBLEMS THEY INCUR DUE TO THE SOFTWARE, AND WHO FURTHERMORE
EFFECTIVELY INDEMNIFY JOHN HAUSER AND THE INTERNATIONAL COMPUTER SCIENCE
INSTITUTE (possibly via similar legal warning) AGAINST ALL LOSSES, COSTS, OR
OTHER PROBLEMS INCURRED BY THEIR CUSTOMERS AND CLIENTS DUE TO THE SOFTWARE.
Derivative works are acceptable, even for commercial purposes, so long as
(1) the source code for the derivative work includes prominent notice that
the work is derivative, and (2) the source code includes prominent notice with
these four paragraphs for those parts of this code that are retained.
=============================================================================*/
/*----------------------------------------------------------------------------
| Include common integer types and flags.
*----------------------------------------------------------------------------*/
#include "../../../processors/386-GCC.h"
/*----------------------------------------------------------------------------
| Symbolic Boolean literals.
*----------------------------------------------------------------------------*/
enum {
FALSE = 0,
TRUE = 1
};
| {
"content_hash": "5f3e9bcac7f0c8051ceefe4ce2999498",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 79,
"avg_line_length": 51.266666666666666,
"alnum_prop": 0.6150845253576073,
"repo_name": "DavidGriffith/tme",
"id": "2da74cd777e705ef3fd3373903f9b4847fec02a2",
"size": "2307",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "dist/softfloat/softfloat/bits32/386-Win32-GCC/milieu.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "10305"
},
{
"name": "C",
"bytes": "7327636"
},
{
"name": "C++",
"bytes": "7583"
},
{
"name": "Objective-C",
"bytes": "39968"
},
{
"name": "Perl",
"bytes": "56345"
},
{
"name": "Shell",
"bytes": "1017616"
}
],
"symlink_target": ""
} |
namespace VisualPerception.Teacher
{
partial class Form35
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.label1 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 427);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 11;
this.button1.Text = "Назад";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// richTextBox1
//
this.richTextBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.richTextBox1.Location = new System.Drawing.Point(89, 64);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedVertical;
this.richTextBox1.ShowSelectionMargin = true;
this.richTextBox1.Size = new System.Drawing.Size(561, 256);
this.richTextBox1.TabIndex = 15;
this.richTextBox1.Text = "";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(195, 35);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(389, 17);
this.label1.TabIndex = 14;
this.label1.Text = "Редактирование вводных теоретических сведений";
//
// button2
//
this.button2.Location = new System.Drawing.Point(330, 327);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 16;
this.button2.Text = "Сохранить";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label2.ForeColor = System.Drawing.Color.Green;
this.label2.Location = new System.Drawing.Point(277, 375);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(180, 17);
this.label2.TabIndex = 17;
this.label2.Text = "Изменения сохранены!";
this.label2.Visible = false;
//
// Form35
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(734, 462);
this.Controls.Add(this.label2);
this.Controls.Add(this.button2);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "Form35";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Исследование избирательности восприятия";
this.Load += new System.EventHandler(this.Form35_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label2;
}
} | {
"content_hash": "abbfd9d059bfa22dcc92d48e8c9f5a5a",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 174,
"avg_line_length": 44.411764705882355,
"alnum_prop": 0.5882686849574267,
"repo_name": "IManfis/VisualPerception",
"id": "132c8b731d6fd013853300dd25f200ce47c8309b",
"size": "5398",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VisualPerception/VisualPerception/Teacher/Form35.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "275612"
}
],
"symlink_target": ""
} |
using namespace std;
bool Exists(StringPiece f);
double GetTimestampFromStat(const struct stat& st);
double GetTimestamp(StringPiece f);
enum struct RedirectStderr {
NONE,
STDOUT,
DEV_NULL,
};
int RunCommand(const string& shell,
const string& shellflag,
const string& cmd,
RedirectStderr redirect_stderr,
string* out);
std::string GetExecutablePath();
using GlobMap = std::unordered_map<std::string, std::vector<std::string>>;
const GlobMap::mapped_type& Glob(const char* pat);
const GlobMap& GetAllGlobCache();
void ClearGlobCache();
#define HANDLE_EINTR(x) \
({ \
int r; \
do { \
r = (x); \
} while (r == -1 && errno == EINTR); \
r; \
})
#endif // FILEUTIL_H_
| {
"content_hash": "df890ad5231fa07df305232dc01e0d3c",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 74,
"avg_line_length": 24.736842105263158,
"alnum_prop": 0.5042553191489362,
"repo_name": "google/kati",
"id": "1ff4fc12db4fee06df6149131d91988ca9827959",
"size": "1718",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/fileutil.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3562"
},
{
"name": "C++",
"bytes": "383423"
},
{
"name": "Dockerfile",
"bytes": "464"
},
{
"name": "Go",
"bytes": "321818"
},
{
"name": "Makefile",
"bytes": "52845"
},
{
"name": "Python",
"bytes": "3306"
},
{
"name": "Shell",
"bytes": "52035"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/com_lenovo_lsf_register_btn_press"/>
<item android:state_focused="true" android:drawable="@drawable/com_lenovo_lsf_register_btn_focus"/>
<item android:state_enabled="false" android:drawable="@drawable/com_lenovo_lsf_startgame_btn_disable"/>
<item android:drawable="@drawable/com_lenovo_lsf_register_btn_normal"/>
</selector> | {
"content_hash": "866b86b77a9edc555a4e69dc7dd8a497",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 107,
"avg_line_length": 73.28571428571429,
"alnum_prop": 0.7407407407407407,
"repo_name": "l1fan/GameAne",
"id": "31ca4798f71bb4bf1fb14becced7bee309a19bcb",
"size": "513",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sdks/lenovo/res/drawable/com_lenovo_lsf_btn_register_selector.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "5322"
},
{
"name": "Batchfile",
"bytes": "216"
},
{
"name": "CSS",
"bytes": "17478"
},
{
"name": "HTML",
"bytes": "118872"
},
{
"name": "Java",
"bytes": "180464"
},
{
"name": "Objective-C",
"bytes": "152626"
},
{
"name": "Shell",
"bytes": "529"
}
],
"symlink_target": ""
} |
package com.netflix.conductor.core.execution.mapper;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.netflix.conductor.common.metadata.tasks.TaskType;
import com.netflix.conductor.core.utils.ParametersUtils;
import com.netflix.conductor.model.TaskModel;
import com.netflix.conductor.model.WorkflowModel;
import static com.netflix.conductor.common.metadata.tasks.TaskType.TASK_TYPE_TERMINATE;
@Component
public class TerminateTaskMapper implements TaskMapper {
public static final Logger logger = LoggerFactory.getLogger(TerminateTaskMapper.class);
private final ParametersUtils parametersUtils;
public TerminateTaskMapper(ParametersUtils parametersUtils) {
this.parametersUtils = parametersUtils;
}
@Override
public String getTaskType() {
return TaskType.TERMINATE.name();
}
@Override
public List<TaskModel> getMappedTasks(TaskMapperContext taskMapperContext) {
logger.debug("TaskMapperContext {} in TerminateTaskMapper", taskMapperContext);
WorkflowModel workflowModel = taskMapperContext.getWorkflowModel();
String taskId = taskMapperContext.getTaskId();
Map<String, Object> taskInput =
parametersUtils.getTaskInputV2(
taskMapperContext.getWorkflowTask().getInputParameters(),
workflowModel,
taskId,
null);
TaskModel task = taskMapperContext.createTaskModel();
task.setTaskType(TASK_TYPE_TERMINATE);
task.setStartTime(System.currentTimeMillis());
task.setInputData(taskInput);
task.setStatus(TaskModel.Status.IN_PROGRESS);
return List.of(task);
}
}
| {
"content_hash": "84cc3a001b4d132da175ae67159d222a",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 91,
"avg_line_length": 33.21818181818182,
"alnum_prop": 0.7170224411603722,
"repo_name": "Netflix/conductor",
"id": "0491df06d9fbdedfde81693d82272817710305df",
"size": "2422",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "core/src/main/java/com/netflix/conductor/core/execution/mapper/TerminateTaskMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1347"
},
{
"name": "Dockerfile",
"bytes": "4469"
},
{
"name": "Groovy",
"bytes": "837140"
},
{
"name": "HTML",
"bytes": "2524"
},
{
"name": "Java",
"bytes": "3347512"
},
{
"name": "JavaScript",
"bytes": "388289"
},
{
"name": "Makefile",
"bytes": "253"
},
{
"name": "SCSS",
"bytes": "4366"
},
{
"name": "Shell",
"bytes": "2383"
},
{
"name": "TypeScript",
"bytes": "8934"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Khang Quach</title>
<!-- Bootstrap Core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Theme CSS -->
<link href="css/personal.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
</head>
<body id="page-top" class="index">
<!-- Navigation -->
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top navbar-custom">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand" href="#page-top">Khang Quach</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
<a href="#page-top"></a>
</li>
<li class="page-scroll">
<a href="#portfolio">Portfolio</a>
</li>
<li class="page-scroll">
<a href="#about">About</a>
</li>
<li class="page-scroll">
<a href="#experience">Experience</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- Header -->
<header>
<div class="container">
<div class="row">
<div class="col-lg-12">
<img class="img-responsive img-circle" src="img/bio.jpg" alt="faceshot">
<div class="intro-text">
<span class="name text-center">a bit about me</span>
<hr class="star-light">
<span class="skills">Mobile Developer - Web Developer - Fitness Enthusiast</span>
</div>
</div>
</div>
</div>
</header>
<!-- Portfolio Grid Section -->
<section id="portfolio">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Portfolio</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-sm-4 portfolio-item">
<a href="#portfolioModal1" class="portfolio-link" data-toggle="modal">
<div class="caption">
<div class="caption-content">
<i class="fa fa-search-plus fa-3x"></i>
</div>
</div>
<img src="img/portfolio/Qself.jpg" class="img-responsive" alt="Qself App">
</a>
</div>
<div class="col-sm-4 portfolio-item">
<a href="#portfolioModal2" class="portfolio-link" data-toggle="modal">
<div class="caption">
<div class="caption-content">
<i class="fa fa-search-plus fa-3x"></i>
</div>
</div>
<img src="img/portfolio/Upcomer.jpg" class="img-responsive" alt="Upcomer App">
</a>
</div>
<div class="col-sm-4 portfolio-item">
<a href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
<div class="caption">
<div class="caption-content">
<i class="fa fa-search-plus fa-3x"></i>
</div>
</div>
<img src="img/portfolio/SpaceShooter.jpg" class="img-responsive" alt="SpaceShooter App">
</a>
</div>
</div>
</div>
</section>
<!-- About Section -->
<section class="success" id="about">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>About</h2>
<hr class="star-light">
</div>
</div>
<div class="row">
<div class="col-lg-4 col-lg-offset-2">
<p>I grew up in the Pacific Northwest being a sports fanatic, growing up I loved watching basketball and especially the Seattle Sonics. I was always the smallest person on the court so I decided to start weight lifting. Fast forward until now if I am not coding you can find me at the gym either working out or playing basketball.</p>
</div>
<div class="col-lg-4">
<p>Having the love for basketball I started playing fantasy basketball on my mobile phone and I discovered that the best applications are simple to use, designed elegantly and are a necessity for many people. It gave me a passion to develop applications that are easy to use and designed with simplicity in mind. </p>
</div>
</div>
</div>
</section>
<!-- Experience and Education Section -->
<section id="experience">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Experience</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-md-4">
<img class = "img-responsive img-circle" src="img/experience/cwk.png">
</div>
<div class="col-md-6">
<h4>Coding With Kids Instructor December 2016 to Present</h4>
<p>Lead classrooms of sizes up to 18 students. Teach and develop young programmer’s computer science concepts and skills through Scratch.</p>
</div>
</div>
<br/>
<br/>
<div class="row">
<div class="col-md-4">
<img class = "img-responsive img-circle " src="img/experience/NorthSeattle.png">
</div>
<div class="col-md-6">
<h4>North Seattle College Student 2015-2018</h4>
<p>Obtaining a Bachelor's of Applied Science degree in Application Development with focus on mobile, web, and cloud applications.</p>
<p>Honors include President's list, Education Fund Scholarship Recipient, Phi Theta Kappa Honor Society.</p>
</div>
</div>
</div>
</section>
<!-- Footer -->
<footer class="text-center">
<div class="footer-above">
<div class="container">
<div class="row">
<div class="footer-col col-md-4">
<h3>Location</h3>
<p>Greater Seattle Area, WA 98087</p>
</div>
<div class="footer-col col-md-4">
<h3>You can find me on</h3>
<ul class="list-inline">
<li>
<a href="https://www.linkedin.com/in/khang-quach-74b342103?trk=hp-identity-photo" class="btn-social btn-outline"><i class="fa fa-fw fa-linkedin"></i></a>
</li>
<li>
<a href="https://github.com/kennyqSoftware" class="btn-social btn-outline"><i class="fa fa-fw fa-github"></i></a>
</li>
</ul>
</div>
<div class="footer-col col-md-4">
<h3>Feel free to E-mail me</h3>
<a href="mailto:kennyqsoftware@gmail.com" class="btn-social
btn-outline"><i class="fa fa-envelope"></i></a>
</div>
</div>
</div>
</div>
<div class="footer-below">
<div class="container">
<div class="row">
<div class="col-lg-12">
Copyright © Khang Quach 2017
</div>
</div>
</div>
</div>
</footer>
<!-- Scroll to Top Button (Only visible on small and extra-small screen sizes) -->
<div class="scroll-top page-scroll hidden-sm hidden-xs hidden-lg hidden-md">
<a class="btn btn-primary" href="#page-top">
<i class="fa fa-chevron-up"></i>
</a>
</div>
<!-- Portfolio Modals -->
<div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Qself</h2>
<hr class="star-primary">
<img src="img/portfolio/Qself.jpg" class="img-responsive img-centered" alt="Qself App">
<p>Developing an easy to use scheduling application for my employer in order to organize customer’s information along with an interface for employees to see upcoming scheduled appointments. under development with a friend using Swift, Xcode.</p>
<ul class="list-inline item-details">
<li>Repo:
<strong><a href="https://github.com/kennyqSoftware/Qself-ios">Github</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="portfolio-modal modal fade" id="portfolioModal2" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Upcomer</h2>
<hr class="star-primary">
<img src="img/portfolio/Upcomer.jpg" class="img-responsive img-centered" alt="Upcomer App">
<p>An Application that allows users to research their favorite artists with randomize song selection. Artist biographies are provided along with suggestions of relevant up and coming artist based on popular search. Powered by Last.fm API and developed using Java through Android Studio. Currently in the Google Play Store.</p>
<ul class="list-inline item-details">
<li>Repo:
<strong><a href="https://github.com/kennyqSoftware/Upcomer">Github</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="portfolio-modal modal fade" id="portfolioModal3" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>SpaceShooter</h2>
<hr class="star-primary">
<img src="img/portfolio/SpaceShooter.jpg" class="img-responsive img-centered" alt="SpaceShooter App">
<p>My friends and I created a simple Galaga inspired game created in my CS141 class as a final project. Developed using Java/Eclipse</p>
<ul class="list-inline item-details">
<li>Repo:
<strong><a href="https://github.com/kennyqSoftware/SpaceShooter">Github</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- Contact Form JavaScript -->
<script src="js/jqBootstrapValidation.js"></script>
<script src="js/contact_me.js"></script>
<!-- Theme JavaScript -->
<script src="js/personal.min.js"></script>
</body>
</html>
| {
"content_hash": "f452088237cf685061a10d906707ffe9",
"timestamp": "",
"source": "github",
"line_count": 329,
"max_line_length": 354,
"avg_line_length": 45.951367781155014,
"alnum_prop": 0.47221854742690833,
"repo_name": "kennyqSoftware/WebDev",
"id": "b0ddc2abab97a5d66dca0228c25b182b636f69e4",
"size": "15122",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "personal/index.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "28265"
},
{
"name": "HTML",
"bytes": "58870"
},
{
"name": "JavaScript",
"bytes": "58135"
},
{
"name": "PHP",
"bytes": "488"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.