text
stringlengths 2
1.04M
| meta
dict |
---|---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>aac-tactics: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1 / aac-tactics - 8.13.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
aac-tactics
<small>
8.13.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-18 07:20:46 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-18 07:20:46 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.7.1 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"
maintainer: "[email protected]"
homepage: "https://github.com/coq-community/aac-tactics"
dev-repo: "git+https://github.com/coq-community/aac-tactics.git"
bug-reports: "https://github.com/coq-community/aac-tactics/issues"
license: "LGPL-3.0-or-later"
synopsis: "Coq plugin providing tactics for rewriting universally quantified equations, modulo associative (and possibly commutative) operators"
description: """
This Coq plugin provides tactics for rewriting universally quantified
equations, modulo associativity and commutativity of some operator.
The tactics can be applied for custom operators by registering the
operators and their properties as type class instances. Many common
operator instances, such as for Z binary arithmetic and booleans, are
provided with the plugin."""
build: [make "-j%{jobs}%"]
install: [make "install"]
depends: [
"ocaml" {>= "4.05.0" & < "4.12"}
"coq" {>= "8.13" & < "8.14~"}
]
tags: [
"category:Miscellaneous/Coq Extensions"
"category:Computer Science/Decision Procedures and Certified Algorithms/Decision procedures"
"keyword:reflexive tactic"
"keyword:rewriting"
"keyword:rewriting modulo associativity and commutativity"
"keyword:rewriting modulo ac"
"keyword:decision procedure"
"logpath:AAC_tactics"
"date:2020-12-16"
]
authors: [
"Thomas Braibant"
"Damien Pous"
"Fabian Kunze"
]
url {
src: "https://github.com/coq-community/aac-tactics/archive/v8.13.0.tar.gz"
checksum: "sha512=8d34c04a4d28e44a5d831bddc1907fc23b0f3ef61335b9b8206518060bb545e7983f63bdcf9808d43e4557acebb4b1031785a11772e239bb8b1193b87c086260"
}
</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-aac-tactics.8.13.0 coq.8.7.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.7.1).
The following dependencies couldn't be met:
- coq-aac-tactics -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
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-aac-tactics.8.13.0</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": "1b25135b16b2da721086aa1de3c88b67",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 42.43646408839779,
"alnum_prop": 0.5697174847025127,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "ed8cb30dfd45b04196100d77e6220a77e8f0a1fd",
"size": "7706",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.7.1/aac-tactics/8.13.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package net.java.sip.communicator.util;
import java.net.*;
import java.text.*;
import java.util.*;
import net.java.sip.communicator.service.dns.*;
import net.java.sip.communicator.util.SRVRecord;
import org.xbill.DNS.*;
/**
* Utility methods and fields to use when working with network addresses.
*
* TODO: there is a lot of duplication between this class and
* org.ice4j.ice.NetworkUtils
*
* @author Emil Ivov
* @author Damian Minkov
* @author Vincent Lucas
* @author Alan Kelly
*/
public class NetworkUtils
{
/**
* The <tt>Logger</tt> used by the <tt>NetworkUtils</tt> class for logging
* output.
*/
private static final Logger logger = Logger.getLogger(NetworkUtils.class);
/**
* A string containing the "any" local address for IPv6.
*/
public static final String IN6_ADDR_ANY = "::0";
/**
* A string containing the "any" local address for IPv4.
*/
public static final String IN4_ADDR_ANY = "0.0.0.0";
/**
* A string containing the "any" local address.
*/
public static final String IN_ADDR_ANY = determineAnyAddress();
/**
* The length of IPv6 addresses.
*/
private final static int IN6_ADDR_SIZE = 16;
/**
* The size of the tokens in a <tt>String</tt> representation of IPv6
* addresses.
*/
private final static int IN6_ADDR_TOKEN_SIZE = 2;
/**
* The length of IPv4 addresses.
*/
private final static int IN4_ADDR_SIZE = 4;
/**
* The maximum int value that could correspond to a port number.
*/
public static final int MAX_PORT_NUMBER = 65535;
/**
* The minimum int value that could correspond to a port number bindable
* by the SIP Communicator.
*/
public static final int MIN_PORT_NUMBER = 1024;
/**
* The random port number generator that we use in getRandomPortNumer()
*/
private static Random portNumberGenerator = new Random();
/**
* The name of the boolean property that defines whether all domain names
* looked up from Jitsi should be treated as absolute.
*/
public static final String PNAME_DNS_ALWAYS_ABSOLUTE
= "net.java.sip.communicator.util.dns.DNSSEC_ALWAYS_ABSOLUTE";
/**
* Default value of {@link #PNAME_DNS_ALWAYS_ABSOLUTE}.
*/
public static final boolean PDEFAULT_DNS_ALWAYS_ABSOLUTE = false;
/**
* A random number generator.
*/
private static final Random random = new Random();
static
{
String prefer6 = System.getProperty("java.net.preferIPv6Addresses");
String prefer4 = System.getProperty("java.net.preferIPv4Stack");
logger.info("java.net.preferIPv6Addresses=" + prefer6);
logger.info("java.net.preferIPv4Stack=" + prefer4);
}
/**
* Determines whether the address is the result of windows auto configuration.
* (i.e. One that is in the 169.254.0.0 network)
* @param add the address to inspect
* @return true if the address is autoconfigured by windows, false otherwise.
*/
public static boolean isWindowsAutoConfiguredIPv4Address(InetAddress add)
{
return (add.getAddress()[0] & 0xFF) == 169
&& (add.getAddress()[1] & 0xFF) == 254;
}
/**
* Returns a random local port number that user applications could bind to.
* (i.e. above 1024).
* @return a random int located between 1024 and 65 535.
*/
public static int getRandomPortNumber()
{
return getRandomPortNumber(MIN_PORT_NUMBER, MAX_PORT_NUMBER);
}
/**
* Returns a random local port number in the interval [min, max].
*
* @param min the minimum allowed value for the returned port number.
* @param max the maximum allowed value for the returned port number.
*
* @return a random int in the interval [min, max].
*/
public static int getRandomPortNumber(int min, int max)
{
return portNumberGenerator.nextInt(max - min + 1) + min;
}
/**
* Verifies whether <tt>address</tt> could be an IPv4 address string.
*
* @param address the String that we'd like to determine as an IPv4 address.
*
* @return true if the address contained by <tt>address</tt> is an IPv4
* address and false otherwise.
*/
public static boolean isIPv4Address(String address)
{
return strToIPv4(address) != null;
}
/**
* Verifies whether <tt>address</tt> could be an IPv6 address string.
*
* @param address the String that we'd like to determine as an IPv6 address.
*
* @return true if the address contained by <tt>address</tt> is an IPv6
* address and false otherwise.
*/
public static boolean isIPv6Address(String address)
{
return strToIPv6(address) != null;
}
/**
* Checks whether <tt>address</tt> is a valid IP address string.
*
* @param address the address that we'd like to check
* @return true if address is an IPv4 or IPv6 address and false otherwise.
*/
public static boolean isValidIPAddress(String address)
{
// empty string
if (address == null || address.length() == 0)
{
return false;
}
// look for IPv6 brackets and remove brackets for parsing
boolean ipv6Expected = false;
if (address.charAt(0) == '[')
{
// This is supposed to be an IPv6 literal
if (address.length() > 2
&& address.charAt(address.length() - 1) == ']')
{
// remove brackets from IPv6
address = address.substring(1, address.length() - 1);
ipv6Expected = true;
}
else
{
return false;
}
}
// look for IP addresses
if (Character.digit(address.charAt(0), 16) != -1
|| (address.charAt(0) == ':'))
{
byte[] addr = null;
// see if it is IPv4 address
addr = strToIPv4(address);
// if not, see if it is IPv6 address
if (addr == null)
{
addr = strToIPv6(address);
}
// if IPv4 is found when IPv6 is expected
else if (ipv6Expected)
{
// invalid address: IPv4 address surrounded with brackets!
return false;
}
// if an IPv4 or IPv6 address is found
if (addr != null)
{
// is an IP address
return true;
}
}
// no matches found
return false;
}
/**
* Creates a byte array containing the specified <tt>ipv4AddStr</tt>.
*
* @param ipv4AddrStr a <tt>String</tt> containing an IPv4 address.
*
* @return a byte array containing the four bytes of the address represented
* by ipv4AddrStr or <tt>null</tt> if <tt>ipv4AddrStr</tt> does not contain
* a valid IPv4 address string.
*/
public static byte[] strToIPv4(String ipv4AddrStr)
{
if (ipv4AddrStr == null || ipv4AddrStr.length() == 0)
return null;
byte[] address = new byte[IN4_ADDR_SIZE];
String[] tokens = ipv4AddrStr.split("\\.", -1);
long currentTkn;
try
{
switch(tokens.length)
{
case 1:
//If the address was specified as a single String we can
//directly copy it into the byte array.
currentTkn = Long.parseLong(tokens[0]);
if (currentTkn < 0 || currentTkn > 0xffffffffL)
return null;
address[0] = (byte) ((currentTkn >> 24) & 0xff);
address[1] = (byte) (((currentTkn & 0xffffff) >> 16) & 0xff);
address[2] = (byte) (((currentTkn & 0xffff) >> 8) & 0xff);
address[3] = (byte) (currentTkn & 0xff);
break;
case 2:
// If the address was passed in two parts (e.g. when dealing
// with a Class A address representation), we place the
// first one in the leftmost byte and the rest in the three
// remaining bytes of the address array.
currentTkn = Integer.parseInt(tokens[0]);
if (currentTkn < 0 || currentTkn > 0xff)
return null;
address[0] = (byte) (currentTkn & 0xff);
currentTkn = Integer.parseInt(tokens[1]);
if (currentTkn < 0 || currentTkn > 0xffffff)
return null;
address[1] = (byte) ((currentTkn >> 16) & 0xff);
address[2] = (byte) (((currentTkn & 0xffff) >> 8) &0xff);
address[3] = (byte) (currentTkn & 0xff);
break;
case 3:
// If the address was passed in three parts (e.g. when
// dealing with a Class B address representation), we place
// the first two parts in the two leftmost bytes and the
// rest in the two remaining bytes of the address array.
for (int i = 0; i < 2; i++)
{
currentTkn = Integer.parseInt(tokens[i]);
if (currentTkn < 0 || currentTkn > 0xff)
return null;
address[i] = (byte) (currentTkn & 0xff);
}
currentTkn = Integer.parseInt(tokens[2]);
if (currentTkn < 0 || currentTkn > 0xffff)
return null;
address[2] = (byte) ((currentTkn >> 8) & 0xff);
address[3] = (byte) (currentTkn & 0xff);
break;
case 4:
// And now for the most common - four part case. This time
// there's a byte for every part :). Yuppiee! :)
for (int i = 0; i < 4; i++)
{
currentTkn = Integer.parseInt(tokens[i]);
if (currentTkn < 0 || currentTkn > 0xff)
return null;
address[i] = (byte) (currentTkn & 0xff);
}
break;
default:
return null;
}
}
catch(NumberFormatException e)
{
return null;
}
return address;
}
/**
* Creates a byte array containing the specified <tt>ipv6AddStr</tt>.
*
* @param ipv6AddrStr a <tt>String</tt> containing an IPv6 address.
*
* @return a byte array containing the four bytes of the address represented
* by <tt>ipv6AddrStr</tt> or <tt>null</tt> if <tt>ipv6AddrStr</tt> does
* not contain a valid IPv6 address string.
*/
public static byte[] strToIPv6(String ipv6AddrStr)
{
// Bail out if the string is shorter than "::"
if (ipv6AddrStr == null || ipv6AddrStr.length() < 2)
return null;
int colonIndex;
char currentChar;
boolean sawtDigit;
int currentTkn;
char[] addrBuff = ipv6AddrStr.toCharArray();
byte[] dst = new byte[IN6_ADDR_SIZE];
int srcb_length = addrBuff.length;
int scopeID = ipv6AddrStr.indexOf ("%");
if (scopeID == srcb_length -1)
return null;
if (scopeID != -1)
srcb_length = scopeID;
colonIndex = -1;
int i = 0, j = 0;
// Can be wrapped in []
if (addrBuff[i] == '[')
{
++i;
if (scopeID == -1)
--srcb_length;
}
// Starting : mean we need to have at least one more.
if (addrBuff[i] == ':')
if (addrBuff[++i] != ':')
return null;
int curtok = i;
sawtDigit = false;
currentTkn = 0;
while (i < srcb_length)
{
currentChar = addrBuff[i++];
int chval = Character.digit(currentChar, 16);
if (chval != -1)
{
currentTkn <<= 4;
currentTkn |= chval;
if (currentTkn > 0xffff)
return null;
sawtDigit = true;
continue;
}
if (currentChar == ':')
{
curtok = i;
if (!sawtDigit)
{
if (colonIndex != -1)
return null;
colonIndex = j;
continue;
}
else if (i == srcb_length)
{
return null;
}
if (j + IN6_ADDR_TOKEN_SIZE > IN6_ADDR_SIZE)
return null;
dst[j++] = (byte) ((currentTkn >> 8) & 0xff);
dst[j++] = (byte) (currentTkn & 0xff);
sawtDigit = false;
currentTkn = 0;
continue;
}
if (currentChar == '.' && ((j + IN4_ADDR_SIZE) <= IN6_ADDR_SIZE))
{
String ia4 = ipv6AddrStr.substring(curtok, srcb_length);
// check this IPv4 address has 3 dots, ie. A.B.C.D
int dot_count = 0, index=0;
while ((index = ia4.indexOf ('.', index)) != -1)
{
dot_count ++;
index ++;
}
if (dot_count != 3)
return null;
byte[] v4addr = strToIPv4(ia4);
if (v4addr == null)
return null;
for (int k = 0; k < IN4_ADDR_SIZE; k++)
{
dst[j++] = v4addr[k];
}
sawtDigit = false;
break; /* '\0' was seen by inet_pton4(). */
}
return null;
}
if (sawtDigit)
{
if (j + IN6_ADDR_TOKEN_SIZE > IN6_ADDR_SIZE)
return null;
dst[j++] = (byte) ((currentTkn >> 8) & 0xff);
dst[j++] = (byte) (currentTkn & 0xff);
}
if (colonIndex != -1)
{
int n = j - colonIndex;
if (j == IN6_ADDR_SIZE)
return null;
for (i = 1; i <= n; i++)
{
dst[IN6_ADDR_SIZE - i] = dst[colonIndex + n - i];
dst[colonIndex + n - i] = 0;
}
j = IN6_ADDR_SIZE;
}
if (j != IN6_ADDR_SIZE)
return null;
byte[] newdst = mappedIPv4ToRealIPv4(dst);
if (newdst != null)
{
return newdst;
}
else
{
return dst;
}
}
/**
* Returns array of hosts from the SRV record of the specified domain.
* The records are ordered against the SRV record priority
*
* @param domain the name of the domain we'd like to resolve (_proto._tcp
* included).
*
* @return an array of SRVRecord containing records returned by the DNS
* server - address and port .
*
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static SRVRecord[] getSRVRecords(String domain)
throws ParseException, DnssecException
{
return getSRVRecords(domain, true);
}
/**
* Returns array of hosts from the SRV record of the specified domain.
* The records are ordered against the SRV record priority
*
* @param domain the name of the domain we'd like to resolve (_proto._tcp
* included).
* @param useDNSCache Tells the lookup to use (or not) the DNS cache to
* resolve the domain requested. i.e. it is useful to disable the DNS cache
* when doing requests for testing DNS connectivity.
*
* @return an array of SRVRecord containing records returned by the DNS
* server - address and port .
*
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static SRVRecord[] getSRVRecords(
String domain,
boolean useDNSCache)
throws ParseException, DnssecException
{
Record[] records = null;
try
{
Lookup lookup = createLookup(domain, Type.SRV);
// Disables the DNS cache: i.e. useful when testing DNS
// connectivity.
if(!useDNSCache)
{
lookup.setCache(new Cache());
}
records = lookup.run();
}
catch (TextParseException tpe)
{
logger.error("Failed to parse domain=" + domain, tpe);
throw new ParseException(tpe.getMessage(), 0);
}
catch(DnssecRuntimeException e)
{
throw new DnssecException(e);
}
if (records == null)
{
return null;
}
//String[][] pvhn = new String[records.length][4];
SRVRecord srvRecords[] = new SRVRecord[records.length];
for (int i = 0; i < records.length; i++)
{
org.xbill.DNS.SRVRecord srvRecord =
(org.xbill.DNS.SRVRecord) records[i];
srvRecords[i] = new SRVRecord(srvRecord);
}
// Sort the SRV RRs by priority (lower is preferred) and weight.
sortSrvRecord(srvRecords);
if (logger.isTraceEnabled())
{
logger.trace("DNS SRV query for domain " + domain + " returned:");
for (int i = 0; i < srvRecords.length; i++)
{
if (logger.isTraceEnabled())
logger.trace(srvRecords[i]);
}
}
return srvRecords;
}
/**
* Returns an <tt>InetSocketAddress</tt> representing the first SRV
* record available for the specified domain or <tt>null</tt> if there are
* not SRV records for <tt>domain</tt>.
*
* @param domain the name of the domain we'd like to resolve.
* @param service the service that we are trying to get a record for.
* @param proto the protocol that we'd like <tt>service</tt> on.
*
* @return the first InetSocketAddress containing records returned by the
* DNS server - address and port .
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static SRVRecord getSRVRecord(String service,
String proto,
String domain)
throws ParseException, DnssecException
{
SRVRecord[] records = getSRVRecords("_" + service
+ "._" + proto
+ "." + domain,
true);
if(records == null || records.length == 0)
return null;
return records[0];
}
/**
* Returns an <tt>InetSocketAddress</tt> representing the first SRV
* record available for the specified domain or <tt>null</tt> if there are
* not SRV records for <tt>domain</tt>.
*
* @param domain the name of the domain we'd like to resolve.
* @param service the service that we are trying to get a record for.
* @param proto the protocol that we'd like <tt>service</tt> on.
*
* @return the InetSocketAddress[] containing records returned by the
* DNS server - address and port .
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static SRVRecord[] getSRVRecords(String service,
String proto,
String domain)
throws ParseException, DnssecException
{
return getSRVRecords(service, proto, domain, true);
}
/**
* Returns an <tt>InetSocketAddress</tt> representing the first SRV
* record available for the specified domain or <tt>null</tt> if there are
* not SRV records for <tt>domain</tt>.
*
* @param domain the name of the domain we'd like to resolve.
* @param service the service that we are trying to get a record for.
* @param proto the protocol that we'd like <tt>service</tt> on.
* @param useDNSCache Tells the lookup to use (or not) the DNS cache to
* resolve the domain requested. i.e. it is useful to disable the DNS cache
* when doing requests for testing DNS connectivity.
*
* @return the InetSocketAddress[] containing records returned by the
* DNS server - address and port .
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static SRVRecord[] getSRVRecords(String service,
String proto,
String domain,
boolean useDNSCache)
throws ParseException, DnssecException
{
SRVRecord[] records = getSRVRecords("_" + service
+ "._" + proto
+ "." + domain,
useDNSCache);
if(records == null || records.length == 0)
return null;
return records;
}
/**
* Makes a NAPTR query and returns the result. The returned records are an
* array of [Order, Service(Transport) and Replacement
* (the srv to query for servers and ports)] this all for supplied
* <tt>domain</tt>.
*
* @param domain the name of the domain we'd like to resolve.
* @return an array with the values or null if no records found.
*
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static String[][] getNAPTRRecords(String domain)
throws ParseException, DnssecException
{
Record[] records = null;
try
{
Lookup lookup = createLookup(domain, Type.NAPTR);
records = lookup.run();
}
catch (TextParseException tpe)
{
logger.error("Failed to parse domain="+domain, tpe);
throw new ParseException(tpe.getMessage(), 0);
}
catch(DnssecRuntimeException e)
{
throw new DnssecException(e);
}
if (records == null)
{
if(logger.isTraceEnabled())
logger.trace("No NAPTRs found for " + domain);
return null;
}
List<String[]> recVals = new ArrayList<>(records.length);
for (int i = 0; i < records.length; i++)
{
String[] recVal = new String[4];
NAPTRRecord r = (NAPTRRecord)records[i];
// todo - check here for broken records as missing transport
recVal[0] = "" + r.getOrder();
recVal[1] = getProtocolFromNAPTRRecords(r.getService());
if (recVal[1] == null)
{
// we don't understand this NAPTR, maybe it's not for SIP?
continue;
}
String replacement = r.getReplacement().toString();
if (replacement.endsWith("."))
{
recVal[2] =
replacement.substring(0, replacement.length() - 1);
}
else
{
recVal[2] = replacement;
}
recVal[3] = "" + r.getPreference();
recVals.add(recVal);
}
// sort the SRV RRs by RR value (lower is preferred)
Collections.sort(recVals, new Comparator<String[]>()
{
// Sorts NAPTR records by ORDER (low number first), PREFERENCE (low
// number first) and PROTOCOL (0-TLS, 1-TCP, 2-UDP).
public int compare(String array1[], String array2[])
{
// First tries to define the priority with the NAPTR order.
int order
= Integer.parseInt(array1[0]) - Integer.parseInt(array2[0]);
if(order != 0)
{
return order;
}
// Second tries to define the priority with the NAPTR
// preference.
int preference
= Integer.parseInt(array1[3]) - Integer.parseInt(array2[3]);
if(preference != 0)
{
return preference;
}
// Finally defines the priority with the NAPTR protocol.
int protocol
= getProtocolPriority(array1[1])
- getProtocolPriority(array2[1]);
return protocol;
}
});
String[][] arrayResult = new String[recVals.size()][4];
arrayResult = recVals.toArray(arrayResult);
if(logger.isTraceEnabled())
logger.trace("NAPTRs for " + domain + "="
+ Arrays.toString(arrayResult));
return arrayResult;
}
/**
* Returns the mapping from rfc3263 between service and the protocols.
*
* @param service the service from NAPTR record.
* @return the protocol TCP, UDP or TLS.
*/
private static String getProtocolFromNAPTRRecords(String service)
{
if(service.equalsIgnoreCase("SIP+D2U"))
return "UDP";
else if(service.equalsIgnoreCase("SIP+D2T"))
return "TCP";
else if(service.equalsIgnoreCase("SIPS+D2T"))
return "TLS";
else
return null;
}
/**
* Returns the priority of a protocol. The lowest priority is the highest:
* 0-TLS, 1-TCP, 2-UDP.
*
* @param protocol The protocol name: "TLS", "TCP" or "UDP".
*
* @return The priority of a protocol. The lowest priority is the highest:
* 0-TLS, 1-TCP, 2-UDP.
*/
private static int getProtocolPriority(String protocol)
{
if(protocol.equals("TLS"))
return 0;
else if(protocol.equals("TCP"))
return 1;
return 2; // "UDP".
}
/**
* Creates an InetAddress from the specified <tt>hostAddress</tt>. The point
* of using the method rather than creating the address by yourself is that
* it would first check whether the specified <tt>hostAddress</tt> is indeed
* a valid ip address. It this is the case, the method would create the
* <tt>InetAddress</tt> using the <tt>InetAddress.getByAddress()</tt>
* method so that no DNS resolution is attempted by the JRE. Otherwise
* it would simply use <tt>InetAddress.getByName()</tt> so that we would an
* <tt>InetAddress</tt> instance even at the cost of a potential DNS
* resolution.
*
* @param hostAddress the <tt>String</tt> representation of the address
* that we would like to create an <tt>InetAddress</tt> instance for.
*
* @return an <tt>InetAddress</tt> instance corresponding to the specified
* <tt>hostAddress</tt>.
*
* @throws UnknownHostException if any of the <tt>InetAddress</tt> methods
* we are using throw an exception.
*/
public static InetAddress getInetAddress(String hostAddress)
throws UnknownHostException
{
//is null
if (hostAddress == null || hostAddress.length() == 0)
{
throw new UnknownHostException(
hostAddress + " is not a valid host address");
}
//transform IPv6 literals into normal addresses
if (hostAddress.charAt(0) == '[')
{
// This is supposed to be an IPv6 literal
if (hostAddress.length() > 2
&& hostAddress.charAt(hostAddress.length()-1) == ']')
{
hostAddress = hostAddress.substring(1, hostAddress.length() -1);
}
else
{
// This was supposed to be a IPv6 address, but it's not!
throw new UnknownHostException(hostAddress);
}
}
if (NetworkUtils.isValidIPAddress(hostAddress))
{
byte[] addr = null;
// attempt parse as IPv4 address
addr = strToIPv4(hostAddress);
// if not IPv4, parse as IPv6 address
if (addr == null)
{
addr = strToIPv6(hostAddress);
}
return InetAddress.getByAddress(hostAddress, addr);
}
else
{
return InetAddress.getByName(hostAddress);
}
}
/**
* Returns array of hosts from the A and AAAA records of the specified
* domain. The records are ordered against the IPv4/IPv6 protocol priority
*
* @param domain the name of the domain we'd like to resolve.
* @param port the port number of the returned <tt>InetSocketAddress</tt>
* @return an array of InetSocketAddress containing records returned by the
* DNS server - address and port .
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static InetSocketAddress[] getAandAAAARecords(String domain, int port)
throws ParseException, DnssecException
{
byte[] address = null;
if((address = strToIPv4(domain)) != null
|| (address = strToIPv6(domain)) != null)
{
try
{
return new InetSocketAddress[]
{
new InetSocketAddress(
InetAddress.getByAddress(domain, address), port)
};
}
catch (UnknownHostException e)
{
//should not happen
logger.error(
"Unable to create InetAddress for <" + domain + ">", e);
return null;
}
}
List<InetSocketAddress> addresses = new LinkedList<InetSocketAddress>();
boolean v6lookup = Boolean.getBoolean("java.net.preferIPv6Addresses");
for(int i = 0; i < 2; i++)
{
Lookup lookup;
try
{
lookup = createLookup(domain, v6lookup ? Type.AAAA : Type.A);
}
catch (TextParseException tpe)
{
logger.error("Failed to parse domain <" + domain + ">", tpe);
throw new ParseException(tpe.getMessage(), 0);
}
Record[] records = null;
try
{
records = lookup.run();
}
catch(DnssecRuntimeException e)
{
throw new DnssecException(e);
}
if(records != null)
{
for(Record r : records)
{
try
{
addresses.add(
new InetSocketAddress(
// create a new InetAddress filled with the
// domain name to avoid PTR queries
InetAddress.getByAddress(
domain,
v6lookup
? ((AAAARecord)r).getAddress().getAddress()
: ((ARecord)r).getAddress().getAddress()
),
port
)
);
}
catch (UnknownHostException e)
{
logger.error("Invalid record returned from DNS", e);
}
}
}
v6lookup = !v6lookup;
}
if(logger.isTraceEnabled())
logger.trace("A or AAAA addresses: " + addresses);
return addresses.toArray(new InetSocketAddress[0]);
}
/**
* Returns array of hosts from the A record of the specified domain.
* The records are ordered against the A record priority
* @param domain the name of the domain we'd like to resolve.
* @param port the port number of the returned <tt>InetSocketAddress</tt>
* @return an array of InetSocketAddress containing records returned by the
* DNS server - address and port .
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException when a DNSSEC validation failure occurred.
*/
public static InetSocketAddress getARecord(String domain, int port)
throws ParseException, DnssecException
{
byte[] address;
if((address = strToIPv4(domain)) != null)
{
try
{
return new InetSocketAddress(
InetAddress.getByAddress(domain, address), port);
}
catch (UnknownHostException e)
{
//should not happen
logger.error(
"Unable to create InetAddress for <" + domain + ">", e);
return null;
}
}
Record[] records;
try
{
//note that we intentionally do not use our parallel resolver here.
//for starters we'd like to make sure that it works well enough
//with SRV and NAPTR queries. We may then also adopt it for As
//and AAAAs once it proves to be reliable (posted on: 2010-11-24)
Lookup lookup = createLookup(domain, Type.A);
records = lookup.run();
}
catch (TextParseException tpe)
{
logger.error("Failed to parse domain="+domain, tpe);
throw new ParseException(tpe.getMessage(), 0);
}
catch(DnssecRuntimeException e)
{
throw new DnssecException(e);
}
if (records != null && records.length > 0)
{
if(logger.isTraceEnabled())
logger.trace("A record for " + domain + "="
+ ((ARecord)records[0]).getAddress());
try
{
return new InetSocketAddress(
InetAddress.getByAddress(domain,
((ARecord)records[0]).getAddress().getAddress()),
port);
}
catch (UnknownHostException e)
{
return null;
}
}
else
{
if(logger.isTraceEnabled())
logger.trace("No A record found for " + domain);
return null;
}
}
/**
* Returns array of hosts from the AAAA record of the specified domain.
* The records are ordered against the AAAA record priority
* @param domain the name of the domain we'd like to resolve.
* @param port the port number of the returned <tt>InetSocketAddress</tt>
* @return an array of InetSocketAddress containing records returned by the
* DNS server - address and port .
* @throws ParseException if <tt>domain</tt> is not a valid domain name.
* @throws DnssecException
*/
public static InetSocketAddress getAAAARecord(String domain, int port)
throws ParseException, DnssecException
{
byte[] address;
if((address = strToIPv6(domain)) != null)
{
try
{
return new InetSocketAddress(
InetAddress.getByAddress(domain, address), port);
}
catch (UnknownHostException e)
{
//should not happen
logger.error(
"Unable to create InetAddress for <" + domain + ">", e);
return null;
}
}
Record[] records;
try
{
//note that we intentionally do not use our parallel resolver here.
//for starters we'd like to make sure that it works well enough
//with SRV and NAPTR queries. We may then also adopt it for As
//and AAAAs once it proves to be reliable (posted on: 2010-11-24)
Lookup lookup = createLookup(domain, Type.AAAA);
records = lookup.run();
}
catch (TextParseException tpe)
{
logger.error("Failed to parse domain="+domain, tpe);
throw new ParseException(tpe.getMessage(), 0);
}
catch(DnssecRuntimeException e)
{
throw new DnssecException(e);
}
if (records != null && records.length > 0)
{
if(logger.isTraceEnabled())
logger.trace("AAAA record for " + domain + "="
+ ((AAAARecord)records[0]).getAddress());
try
{
return new InetSocketAddress(
InetAddress.getByAddress(domain,
((AAAARecord)records[0]).getAddress().getAddress()),
port);
}
catch (UnknownHostException e)
{
return null;
}
}
else
{
if(logger.isTraceEnabled())
logger.trace("No AAAA record found for " + domain);
return null;
}
}
/**
* Tries to determine if this host supports IPv6 addresses (i.e. has at
* least one IPv6 address) and returns IN6_ADDR_ANY or IN4_ADDR_ANY
* accordingly. This method is only used to initialize IN_ADDR_ANY so that
* it could be used when binding sockets. The reason we need it is because
* on mac (contrary to lin or win) binding a socket on 0.0.0.0 would make
* it deaf to IPv6 traffic. Binding on ::0 does the trick but that would
* fail on hosts that have no IPv6 support. Using the result of this method
* provides an easy way to bind sockets in cases where we simply want any
* IP packets coming on the port we are listening on (regardless of IP
* version).
*
* @return IN6_ADDR_ANY or IN4_ADDR_ANY if this host supports or not IPv6.
*/
private static String determineAnyAddress()
{
Enumeration<NetworkInterface> ifaces;
try
{
ifaces = NetworkInterface.getNetworkInterfaces();
}
catch (SocketException e)
{
if (logger.isDebugEnabled())
logger.debug("Couldn't retrieve local interfaces.", e);
return IN4_ADDR_ANY;
}
while(ifaces.hasMoreElements())
{
Enumeration<InetAddress> addrs
= ifaces.nextElement().getInetAddresses();
while (addrs.hasMoreElements())
{
if(addrs.nextElement() instanceof Inet6Address)
return IN6_ADDR_ANY;
}
}
return IN4_ADDR_ANY;
}
/**
* Determines whether <tt>port</tt> is a valid port number bindable by an
* application (i.e. an integer between 1024 and 65535).
*
* @param port the port number that we'd like verified.
*
* @return <tt>true</tt> if port is a valid and bindable port number and
* <tt>false</tt> otherwise.
*/
public static boolean isValidPortNumber(int port)
{
return MIN_PORT_NUMBER <= port && port <= MAX_PORT_NUMBER;
}
/**
* Returns an IPv4 address matching the one mapped in the IPv6
* <tt>addr</tt>. Both input and returned value are in network order.
*
* @param addr a String representing an IPv4-Mapped address in textual
* format
*
* @return a byte array numerically representing the IPv4 address
*/
public static byte[] mappedIPv4ToRealIPv4(byte[] addr)
{
if (isMappedIPv4Addr(addr))
{
byte[] newAddr = new byte[IN4_ADDR_SIZE];
System.arraycopy(addr, 12, newAddr, 0, IN6_ADDR_SIZE);
return newAddr;
}
return null;
}
/**
* Utility method to check if the specified <tt>address</tt> is an IPv4
* mapped IPv6 address.
*
* @param address the address that we'd like to determine as an IPv4 mapped
* one or not.
*
* @return <tt>true</tt> if address is an IPv4 mapped IPv6 address and
* <tt>false</tt> otherwise.
*/
private static boolean isMappedIPv4Addr(byte[] address)
{
if (address.length < IN6_ADDR_SIZE)
{
return false;
}
if ((address[0] == 0x00) && (address[1] == 0x00)
&& (address[2] == 0x00) && (address[3] == 0x00)
&& (address[4] == 0x00) && (address[5] == 0x00)
&& (address[6] == 0x00) && (address[7] == 0x00)
&& (address[8] == 0x00) && (address[9] == 0x00)
&& (address[10] == (byte)0xff)
&& (address[11] == (byte)0xff))
{
return true;
}
return false;
}
/**
* Creates a new {@link Lookup} instance.
*
* @param domain the domain we will be resolving
* @param type the type of the record we will be trying to obtain.
*
* @return the newly created {@link Lookup} instance.
*
* @throws TextParseException if <tt>domain</tt> is not a valid domain name.
*/
private static Lookup createLookup(String domain, int type)
throws TextParseException
{
// make domain name absolute if requested
if(UtilActivator.getConfigurationService().getBoolean(
PNAME_DNS_ALWAYS_ABSOLUTE,
PDEFAULT_DNS_ALWAYS_ABSOLUTE))
{
if(!Name.fromString(domain).isAbsolute())
domain = domain + ".";
}
Lookup lookup = new Lookup(domain, type);
if(logger.isTraceEnabled())
{
StringBuilder sb = new StringBuilder();
sb.append("Active DNS servers in default resolver: ");
for(String s : ResolverConfig.getCurrentConfig().servers())
{
sb.append(s);
sb.append(", ");
}
logger.trace(sb.toString());
}
return lookup;
}
/**
* Compares two DNS names against each other. Helper method to avoid the
* export of DNSJava.
* @param dns1 The first DNS name
* @param dns2 The DNS name that is compared against dns1
* @return The value 0 if dns2 is a name equivalent to dns1;
* a value less than 0 if dns2 is less than dns1 in the canonical ordering,
* and a value greater than 0 if dns2 is greater than dns1 in the canonical
* ordering.
* @throws ParseException if the dns1 or dns2 is not a DNS Name
*/
public static int compareDnsNames(String dns1, String dns2)
throws ParseException
{
try
{
return Name.fromString(dns1).compareTo(Name.fromString(dns2));
}
catch(TextParseException e)
{
throw new ParseException(e.getMessage(), 0);
}
}
/**
* Sorts the SRV record list by priority and weight.
*
* @param srvRecords The list of SRV records.
*/
private static void sortSrvRecord(SRVRecord[] srvRecords)
{
// Sort the SRV RRs by priority (lower is preferred).
Arrays.sort(srvRecords, new Comparator<SRVRecord>()
{
public int compare(SRVRecord obj1, SRVRecord obj2)
{
return (obj1.getPriority() - obj2.getPriority());
}
});
// Sort the SRV RRs by weight (larger weight has a proportionately
// higher probability of being selected).
sortSrvRecordByWeight(srvRecords);
}
/**
* Sorts each priority of the SRV record list. Each priority is sorted with
* the probabilty given by the weight attribute.
*
* @param srvRecords The list of SRV records already sorted by priority.
*/
private static void sortSrvRecordByWeight(SRVRecord[] srvRecords)
{
int currentPriority = srvRecords[0].getPriority();
int startIndex = 0;
for(int i = 0; i < srvRecords.length; ++i)
{
if(currentPriority != srvRecords[i].getPriority())
{
// Sort the current priority.
sortSrvRecordPriorityByWeight(srvRecords, startIndex, i);
// Reinit variables for the next priority.
startIndex = i;
currentPriority = srvRecords[i].getPriority();
}
}
}
/**
* Sorts SRV record list for a given priority: this priority is sorted with
* the probabilty given by the weight attribute.
*
* @param srvRecords The list of SRV records already sorted by priority.
* @param startIndex The first index (included) for the current priority.
* @param endIndex The last index (excluded) for the current priority.
*/
private static void sortSrvRecordPriorityByWeight(
SRVRecord[] srvRecords,
int startIndex,
int endIndex)
{
int randomWeight;
// Loops over the items of the current priority.
while(startIndex < endIndex)
{
// Compute a random number in [0...totalPriorityWeight].
randomWeight = getRandomWeight(srvRecords, startIndex, endIndex);
// Move the selected item on top of the unsorted items for this
// priority.
moveSelectedSRVRecord(
srvRecords,
startIndex,
endIndex,
randomWeight);
// Move to next index.
++startIndex;
}
}
/**
* Compute a random number in [0...totalPriorityWeight] with
* totalPriorityWeight the sum of all weight for the current priority.
*
* @param srvRecords The list of SRV records already sorted by priority.
* @param startIndex The first index (included) for the current priority.
* @param endIndex The last index (excluded) for the current priority.
*
* @return A random number in [0...totalPriorityWeight] with
* totalPriorityWeight the sum of all weight for the current priority.
*/
private static int getRandomWeight(
SRVRecord[] srvRecords,
int startIndex,
int endIndex)
{
int totalPriorityWeight = 0;
// Compute the max born.
for(int i = startIndex; i < endIndex; ++i)
{
totalPriorityWeight += srvRecords[i].getWeight();
}
// Compute a random number in [0...totalPriorityWeight].
return random.nextInt(totalPriorityWeight + 1);
}
/**
* Moves the selected SRV record in top of the unsorted items for this
* priority.
*
* @param srvRecords The list of SRV records already sorted by priority.
* @param startIndex The first unsorted index (included) for the current
* priority.
* @param endIndex The last unsorted index (excluded) for the current
* priority.
* @param selectedWeight The selected weight used to design the selected
* item to move.
*/
private static void moveSelectedSRVRecord(
SRVRecord[] srvRecords,
int startIndex,
int endIndex,
int selectedWeight)
{
SRVRecord tmpSrvRecord;
int totalPriorityWeight = 0;
for(int i = startIndex; i < endIndex; ++i)
{
totalPriorityWeight += srvRecords[i].getWeight();
// If we found the selecting record.
if(totalPriorityWeight >= selectedWeight)
{
// Switch between startIndex and j.
tmpSrvRecord = srvRecords[startIndex];
srvRecords[startIndex] = srvRecords[i];
srvRecords[i] = tmpSrvRecord;
// Break the loop;
return;
}
}
}
/**
* Clears the default DNS cache.
*/
public static void clearDefaultDNSCache()
{
Cache defaultCache = Lookup.getDefaultCache(DClass.IN);
defaultCache.clearCache();
}
}
| {
"content_hash": "5f9f720f45fbd346606ed034d97e793a",
"timestamp": "",
"source": "github",
"line_count": 1438,
"max_line_length": 82,
"avg_line_length": 34.15507649513213,
"alnum_prop": 0.5324035427058943,
"repo_name": "cobratbq/jitsi",
"id": "f7abb94d6ab3ee1c9a25ac9917496b1099026c0c",
"size": "49785",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/net/java/sip/communicator/util/NetworkUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "451993"
},
{
"name": "C++",
"bytes": "453194"
},
{
"name": "CMake",
"bytes": "442"
},
{
"name": "CSS",
"bytes": "7555"
},
{
"name": "HTML",
"bytes": "1807"
},
{
"name": "Java",
"bytes": "19251756"
},
{
"name": "Makefile",
"bytes": "13895"
},
{
"name": "Objective-C",
"bytes": "157171"
},
{
"name": "Roff",
"bytes": "2357"
},
{
"name": "Shell",
"bytes": "6281"
},
{
"name": "Visual Basic",
"bytes": "11032"
},
{
"name": "XSLT",
"bytes": "1814"
}
],
"symlink_target": ""
} |
package org.apache.jackrabbit.oak.spi.security.privilege;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.tree.TreeUtil;
/**
* Privilege management related utility methods.
*/
public final class PrivilegeUtil implements PrivilegeConstants {
private PrivilegeUtil() {}
/**
* Returns the root tree for all privilege definitions stored in the content
* repository.
*
* @return The privileges root.
*/
@Nonnull
public static Tree getPrivilegesTree(Root root) {
return root.getTree(PRIVILEGES_PATH);
}
/**
* Reads the privilege definition stored in the specified definition tree.
* Note, that this utility does not check the existence nor the node type
* of the specified tree.
*
* @param definitionTree An existing tree storing a privilege definition.
* @return A new instance of {@code PrivilegeDefinition}.
*/
@Nonnull
public static PrivilegeDefinition readDefinition(@Nonnull Tree definitionTree) {
String name = definitionTree.getName();
boolean isAbstract = TreeUtil.getBoolean(definitionTree, REP_IS_ABSTRACT);
Iterable<String> declAggrNames = null;
PropertyState property = definitionTree.getProperty(REP_AGGREGATES);
if (property != null) {
declAggrNames = property.getValue(Type.NAMES);
}
return new ImmutablePrivilegeDefinition(name, isAbstract, declAggrNames);
}
} | {
"content_hash": "1eb9842277df73334f9b747252b2f74b",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 84,
"avg_line_length": 33.857142857142854,
"alnum_prop": 0.7106690777576854,
"repo_name": "davidegiannella/jackrabbit-oak",
"id": "427af32ee723c54df1ecd8a236108060b1b352b0",
"size": "2461",
"binary": false,
"copies": "5",
"ref": "refs/heads/trunk",
"path": "oak-security-spi/src/main/java/org/apache/jackrabbit/oak/spi/security/privilege/PrivilegeUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "24043"
},
{
"name": "Groovy",
"bytes": "145173"
},
{
"name": "HTML",
"bytes": "1406"
},
{
"name": "Java",
"bytes": "24655836"
},
{
"name": "JavaScript",
"bytes": "42991"
},
{
"name": "Perl",
"bytes": "7585"
},
{
"name": "Shell",
"bytes": "17433"
}
],
"symlink_target": ""
} |
#import "TiToJS.h"
#import "KrollBridge.h"
#import "KrollCallback.h"
#import "KrollObject.h"
#import "TiHost.h"
#import "TopTiModule.h"
#import "TiUtils.h"
#import "TiApp.h"
#import "ApplicationMods.h"
#import <libkern/OSAtomic.h>
#import "KrollContext.h"
#import "TiConsole.h"
#import "TiExceptionHandler.h"
#import "APSAnalytics.h"
#ifdef KROLL_COVERAGE
# include "KrollCoverage.h"
#endif
#ifndef USE_JSCORE_FRAMEWORK
#import "TiDebugger.h"
#endif
extern BOOL const TI_APPLICATION_ANALYTICS;
extern NSString * const TI_APPLICATION_DEPLOYTYPE;
extern NSString * const TI_APPLICATION_GUID;
extern NSString * const TI_APPLICATION_BUILD_TYPE;
NSString * TitaniumModuleRequireFormat = @"(function(exports){"
"var __OXP=exports;var module={'exports':exports};var __dirname=\"%@\";var __filename=\"/%@\";%@;\n"
"if(module.exports !== __OXP){return module.exports;}"
"return exports;})({})";
//Defined private method inside TiBindingRunLoop.m (Perhaps to move to .c?)
void TiBindingRunLoopAnnounceStart(TiBindingRunLoop runLoop);
@implementation TitaniumObject
-(NSDictionary*)modules
{
return modules;
}
-(id)initWithContext:(KrollContext*)context_ host:(TiHost*)host_ context:(id<TiEvaluator>)pageContext_ baseURL:(NSURL*)baseURL_
{
TopTiModule *module = [[[TopTiModule alloc] _initWithPageContext:pageContext_] autorelease];
[module setHost:host_];
[module _setBaseURL:baseURL_];
if (self = [super initWithTarget:module context:context_])
{
pageContext = pageContext_;
modules = [[NSMutableDictionary alloc] init];
host = [host_ retain];
[(KrollBridge *)pageContext_ registerProxy:module krollObject:self];
// pre-cache a few modules we always use
TiModule *ui = [host moduleNamed:@"UI" context:pageContext_];
[self addModule:@"UI" module:ui];
TiModule *api = [host moduleNamed:@"API" context:pageContext_];
[self addModule:@"API" module:api];
if (TI_APPLICATION_ANALYTICS)
{
APSAnalytics *sharedAnalytics = [APSAnalytics sharedInstance];
if (TI_APPLICATION_BUILD_TYPE != nil || (TI_APPLICATION_BUILD_TYPE.length > 0)) {
[sharedAnalytics performSelector:@selector(setBuildType:) withObject:TI_APPLICATION_BUILD_TYPE];
}
[sharedAnalytics performSelector:@selector(setSDKVersion:) withObject:[NSString stringWithFormat:@"ti.%@",[module performSelector:@selector(version)]]];
[sharedAnalytics enableWithAppKey:TI_APPLICATION_GUID andDeployType:TI_APPLICATION_DEPLOYTYPE];
}
}
return self;
}
#if KROLLBRIDGE_MEMORY_DEBUG==1
-(id)retain
{
NSLog(@"[MEMORY DEBUG] RETAIN: %@ (%d)",self,[self retainCount]+1);
return [super retain];
}
-(oneway void)release
{
NSLog(@"[MEMORY DEBUG] RELEASE: %@ (%d)",self,[self retainCount]-1);
[super release];
}
#endif
-(void)dealloc
{
RELEASE_TO_NIL(host);
RELEASE_TO_NIL(modules);
RELEASE_TO_NIL(dynprops);
[super dealloc];
}
-(void)gc
{
}
-(id)valueForKey:(NSString *)key
{
// allow dynprops to override built-in modules
// in case you want to re-define them
if (dynprops!=nil)
{
id result = [dynprops objectForKey:key];
if (result!=nil)
{
if (result == [NSNull null])
{
return nil;
}
return result;
}
}
id module = [modules objectForKey:key];
if (module!=nil)
{
return module;
}
module = [host moduleNamed:key context:pageContext];
if (module!=nil)
{
return [self addModule:key module:module];
}
//go against module
return [super valueForKey:key];
}
-(void)setValue:(id)value forKey:(NSString *)key
{
if (dynprops==nil)
{
dynprops = [[NSMutableDictionary dictionary] retain];
}
if (value == nil)
{
value = [NSNull null];
}
[dynprops setValue:value forKey:key];
}
- (id) valueForUndefinedKey: (NSString *) key
{
if ([key isEqualToString:@"toString"] || [key isEqualToString:@"valueOf"])
{
return [self description];
}
if (dynprops != nil)
{
return [dynprops objectForKey:key];
}
//NOTE: we need to return nil here since in JS you can ask for properties
//that don't exist and it should return undefined, not an exception
return nil;
}
-(id)addModule:(NSString*)name module:(TiModule*)module
{
// Have we received a JS Module?
if (![module respondsToSelector:@selector(unboundBridge:)])
{
[modules setObject:module forKey:name];
return module;
}
KrollObject *ko = [pageContext registerProxy:module];
if (ko == nil)
{
return nil;
}
[self noteKrollObject:ko forKey:name];
[modules setObject:ko forKey:name];
return ko;
}
-(TiModule*)moduleNamed:(NSString*)name context:(id<TiEvaluator>)context
{
return [modules objectForKey:name];
}
@end
OSSpinLock krollBridgeRegistryLock = OS_SPINLOCK_INIT;
CFMutableSetRef krollBridgeRegistry = nil;
@implementation KrollBridge
+(void)initialize
{
if (krollBridgeRegistry == nil)
{
CFSetCallBacks doNotRetain = kCFTypeSetCallBacks;
doNotRetain.retain = NULL;
doNotRetain.release = NULL;
krollBridgeRegistry = CFSetCreateMutable(NULL, 3, &doNotRetain);
}
}
@synthesize currentURL;
-(void)registerForMemoryWarning
{
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didReceiveMemoryWarning:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
-(void)unregisterForMemoryWarning
{
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
-(id)init
{
if (self = [super init])
{
#if KROLLBRIDGE_MEMORY_DEBUG==1
NSLog(@"[DEBUG] INIT: %@",self);
#endif
modules = [[NSMutableDictionary alloc] init];
proxyLock = OS_SPINLOCK_INIT;
OSSpinLockLock(&krollBridgeRegistryLock);
CFSetAddValue(krollBridgeRegistry, self);
OSSpinLockUnlock(&krollBridgeRegistryLock);
TiThreadPerformOnMainThread(^{[self registerForMemoryWarning];}, NO);
}
return self;
}
-(void)didReceiveMemoryWarning:(NSNotification*)notification
{
OSSpinLockLock(&proxyLock);
if (registeredProxies == NULL) {
OSSpinLockUnlock(&proxyLock);
[self gc];
return;
}
BOOL keepWarning = YES;
signed long proxiesCount = CFDictionaryGetCount(registeredProxies);
OSSpinLockUnlock(&proxyLock);
//During a memory panic, we may not get the chance to copy proxies.
while (keepWarning)
{
keepWarning = NO;
for (id proxy in (NSDictionary *)registeredProxies)
{
[proxy didReceiveMemoryWarning:notification];
OSSpinLockLock(&proxyLock);
if (registeredProxies == NULL) {
OSSpinLockUnlock(&proxyLock);
break;
}
signed long newCount = CFDictionaryGetCount(registeredProxies);
OSSpinLockUnlock(&proxyLock);
if (newCount != proxiesCount)
{
proxiesCount = newCount;
keepWarning = YES;
break;
}
}
}
[self gc];
}
#if KROLLBRIDGE_MEMORY_DEBUG==1
-(id)retain
{
NSLog(@"[MEMORY DEBUG] RETAIN: %@ (%d)",self,[self retainCount]+1);
return [super retain];
}
-(oneway void)release
{
NSLog(@"[MEMORY DEBUG] RELEASE: %@ (%d)",self,[self retainCount]-1);
[super release];
}
#endif
-(void)removeProxies
{
OSSpinLockLock(&proxyLock);
CFDictionaryRef oldProxies = registeredProxies;
registeredProxies = NULL;
OSSpinLockUnlock(&proxyLock);
for (id thisProxy in (NSDictionary *)oldProxies)
{
KrollObject * thisKrollObject = (id)CFDictionaryGetValue(oldProxies, thisProxy);
[thisProxy contextShutdown:self];
[thisKrollObject unprotectJsobject];
}
if (oldProxies != NULL)
{
CFRelease(oldProxies);
}
for (NSString * thisModuleKey in modules) {
id thisModule = [modules objectForKey:thisModuleKey];
if ([thisModule respondsToSelector:@selector(unprotectJsobject)]) {
[thisModule unprotectJsobject];
}
}
RELEASE_TO_NIL(modules);
}
-(void)dealloc
{
#if KROLLBRIDGE_MEMORY_DEBUG==1
NSLog(@"[MEMORY DEBUG] DEALLOC: %@",self);
#endif
[self removeProxies];
RELEASE_TO_NIL(preload);
RELEASE_TO_NIL(context);
RELEASE_TO_NIL(titanium);
OSSpinLockLock(&krollBridgeRegistryLock);
CFSetRemoveValue(krollBridgeRegistry, self);
OSSpinLockUnlock(&krollBridgeRegistryLock);
[super dealloc];
}
- (TiHost*)host
{
return host;
}
- (KrollContext*) krollContext
{
return context;
}
- (id)preloadForKey:(id)key name:(id)name
{
if (preload!=nil)
{
NSDictionary* dict = [preload objectForKey:name];
if (dict!=nil)
{
return [dict objectForKey:key];
}
}
return nil;
}
- (void)boot:(id)callback url:(NSURL*)url_ preload:(NSDictionary*)preload_
{
preload = [preload_ retain];
[super boot:callback url:url_ preload:preload_];
context = [[KrollContext alloc] init];
context.delegate = self;
[context start];
}
- (void)evalJSWithoutResult:(NSString*)code
{
[context evalJS:code];
}
// NOTE: this must only be called on the JS thread or an exception will be raised
- (id)evalJSAndWait:(NSString*)code
{
return [context evalJSAndWait:code];
}
-(BOOL)evaluationError
{
return evaluationError;
}
- (void)evalFileOnThread:(NSString*)path context:(KrollContext*)context_
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSError *error = nil;
TiValueRef exception = NULL;
TiContextRef jsContext = [context_ context];
NSURL *url_ = [path hasPrefix:@"file:"] ? [NSURL URLWithString:path] : [NSURL fileURLWithPath:path];
if (![path hasPrefix:@"/"] && ![path hasPrefix:@"file:"])
{
url_ = [NSURL URLWithString:path relativeToURL:url];
}
NSString *jcode = nil;
if ([url_ isFileURL])
{
NSData *data = [TiUtils loadAppResource:url_];
if (data==nil)
{
jcode = [NSString stringWithContentsOfFile:[url_ path] encoding:NSUTF8StringEncoding error:&error];
}
else
{
jcode = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
}
else
{
jcode = [NSString stringWithContentsOfURL:url_ encoding:NSUTF8StringEncoding error:&error];
}
if (error!=nil)
{
NSLog(@"[ERROR] Error loading path: %@, %@",path,error);
evaluationError = YES;
TiScriptError *scriptError = nil;
// check for file not found a give a friendlier message
if ([error code]==260 && [error domain]==NSCocoaErrorDomain) {
scriptError = [[TiScriptError alloc] initWithMessage:[NSString stringWithFormat:@"Could not find the file %@",[path lastPathComponent]] sourceURL:nil lineNo:0];
} else {
scriptError = [[TiScriptError alloc] initWithMessage:[NSString stringWithFormat:@"Error loading script %@. %@",[path lastPathComponent],[error description]] sourceURL:nil lineNo:0];
}
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:scriptError];
[scriptError release];
return;
}
const char *urlCString = [[url_ absoluteString] UTF8String];
TiStringRef jsCode = TiStringCreateWithCFString((CFStringRef) jcode);
TiStringRef jsURL = TiStringCreateWithUTF8CString(urlCString);
if (exception == NULL) {
#ifndef USE_JSCORE_FRAMEWORK
if ([[self host] debugMode]) {
TiDebuggerBeginScript(context_,urlCString);
}
TiEvalScript(jsContext, jsCode, NULL, jsURL, 1, &exception);
if ([[self host] debugMode]) {
TiDebuggerEndScript(context_);
}
#else
TiEvalScript(jsContext, jsCode, NULL, jsURL, 1, &exception);
#endif
if (exception == NULL) {
evaluationError = NO;
} else {
evaluationError = YES;
}
}
if (exception != NULL) {
id excm = [KrollObject toID:context value:exception];
evaluationError = YES;
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:[TiUtils scriptErrorValue:excm]];
}
TiStringRelease(jsCode);
TiStringRelease(jsURL);
[pool release];
}
- (void)evalFile:(NSString*)path callback:(id)callback selector:(SEL)selector
{
[context invokeOnThread:self method:@selector(evalFileOnThread:context:) withObject:path callback:callback selector:selector];
}
- (void)evalFile:(NSString *)file
{
[context invokeOnThread:self method:@selector(evalFileOnThread:context:) withObject:file condition:nil];
}
- (void)fireEvent:(id)listener withObject:(id)obj remove:(BOOL)yn thisObject:(TiProxy*)thisObject_
{
if (![listener isKindOfClass:[KrollCallback class]])
{
DebugLog(@"[ERROR] Listener callback is of a non-supported type: %@",[listener class]);
return;
}
KrollEvent *event = [[KrollEvent alloc] initWithCallback:listener eventObject:obj thisObject:thisObject_];
[context enqueue:event];
[event release];
}
-(void)enqueueEvent:(NSString*)type forProxy:(TiProxy *)proxy withObject:(id)obj
{
KrollObject* eventKrollObject = [self krollObjectForProxy:proxy];
KrollEvent * newEvent = [[KrollEvent alloc]
initWithType:type
ForKrollObject:eventKrollObject
eventObject:obj
thisObject:eventKrollObject];
[context enqueue:newEvent];
[newEvent release];
}
-(void)shutdown:(NSCondition*)condition
{
#if KROLLBRIDGE_MEMORY_DEBUG==1
NSLog(@"[MEMORY DEBUG] DESTROY: %@",self);
#endif
if (shutdown==NO)
{
shutdownCondition = [condition retain];
shutdown = YES;
// fire a notification event to our listeners
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
NSNotification *notification = [NSNotification notificationWithName:kTiContextShutdownNotification object:self];
[[NSNotificationCenter defaultCenter] postNotification:notification];
[context stop];
}
else
{
[condition lock];
[condition signal];
[condition unlock];
}
}
-(void)gc
{
[context gc];
[titanium gc];
}
#pragma mark Delegate
-(void)willStartNewContext:(KrollContext*)kroll
{
#ifdef HYPERLOOP
// Start Hyperloop engine if present
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(willStartNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
[self retain]; // Hold onto ourselves as long as the context needs us
}
-(void)didStartNewContext:(KrollContext*)kroll
{
// create Titanium global object
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// Load the "Titanium" object into the global scope
NSString *basePath = (url==nil) ? [TiHost resourcePath] : [[[url path] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"."];
titanium = [[TitaniumObject alloc] initWithContext:kroll host:host context:self baseURL:[NSURL fileURLWithPath:basePath]];
TiContextRef jsContext = [kroll context];
TiValueRef tiRef = [KrollObject toValue:kroll value:titanium];
NSString *titaniumNS = [NSString stringWithFormat:@"T%sanium","it"];
TiStringRef prop = TiStringCreateWithCFString((CFStringRef) titaniumNS);
TiStringRef prop2 = TiStringCreateWithCFString((CFStringRef) [NSString stringWithFormat:@"%si","T"]);
TiObjectRef globalRef = TiContextGetGlobalObject(jsContext);
TiObjectSetProperty(jsContext, globalRef, prop, tiRef,
kTiPropertyAttributeDontDelete | kTiPropertyAttributeDontEnum,
NULL);
TiObjectSetProperty(jsContext, globalRef, prop2, tiRef,
kTiPropertyAttributeDontDelete | kTiPropertyAttributeDontEnum,
NULL);
TiStringRelease(prop);
TiStringRelease(prop2);
// Load the "console" object into the global scope
console = [[KrollObject alloc] initWithTarget:[[[TiConsole alloc] _initWithPageContext:self] autorelease] context:kroll];
prop = TiStringCreateWithCFString((CFStringRef)@"console");
TiObjectSetProperty(jsContext, globalRef, prop, [KrollObject toValue:kroll value:console], kTiPropertyAttributeNone, NULL);
//if we have a preload dictionary, register those static key/values into our namespace
if (preload!=nil)
{
for (NSString *name in preload)
{
KrollObject *ti = (KrollObject*)[titanium valueForKey:name];
NSDictionary *values = [preload valueForKey:name];
for (id key in values)
{
id target = [values objectForKey:key];
KrollObject *ko = [self krollObjectForProxy:target];
if (ko==nil)
{
ko = [self registerProxy:target];
}
[ti noteKrollObject:ko forKey:key];
[ti setStaticValue:ko forKey:key purgable:NO];
}
}
//We need to run this before the app.js, which means it has to be here.
TiBindingRunLoopAnnounceStart(kroll);
[self evalFile:[url path] callback:self selector:@selector(booted)];
}
else
{
// now load the app.js file and get started
NSURL *startURL = [host startURL];
//We need to run this before the app.js, which means it has to be here.
TiBindingRunLoopAnnounceStart(kroll);
[self evalFile:[startURL absoluteString] callback:self selector:@selector(booted)];
}
#ifdef HYPERLOOP
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(didStartNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
[pool release];
}
-(void)willStopNewContext:(KrollContext*)kroll
{
#ifdef HYPERLOOP
// Stop Hyperloop engine if present
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(willStopNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
if (shutdown==NO)
{
shutdown = YES;
// fire a notification event to our listeners
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
NSNotification *notification = [NSNotification notificationWithName:kTiContextShutdownNotification object:self];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}
[titanium gc];
if (shutdownCondition)
{
[shutdownCondition lock];
[shutdownCondition signal];
[shutdownCondition unlock];
RELEASE_TO_NIL(shutdownCondition);
}
}
-(void)didStopNewContext:(KrollContext*)kroll
{
TiThreadPerformOnMainThread(^{[self unregisterForMemoryWarning];}, NO);
[self removeProxies];
RELEASE_TO_NIL(titanium);
RELEASE_TO_NIL(console);
RELEASE_TO_NIL(context);
RELEASE_TO_NIL(preload);
#ifdef HYPERLOOP
Class cls = NSClassFromString(@"Hyperloop");
if (cls) {
[cls performSelector:@selector(didStopNewContext:bridge:) withObject:kroll withObject:self];
}
#endif
[self autorelease]; // Safe to release now that the context is done
}
-(void)registerProxy:(id)proxy krollObject:(KrollObject *)ourKrollObject
{
OSSpinLockLock(&proxyLock);
if (registeredProxies==NULL)
{
registeredProxies = CFDictionaryCreateMutable(NULL, 10, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
//NOTE: Do NOT treat registeredProxies like a mutableDictionary; mutable dictionaries copy keys,
//CFMutableDictionaryRefs only retain keys, which lets them work with proxies properly.
CFDictionaryAddValue(registeredProxies, proxy, ourKrollObject);
OSSpinLockUnlock(&proxyLock);
[proxy boundBridge:self withKrollObject:ourKrollObject];
}
- (id)registerProxy:(id)proxy
{
KrollObject * ourKrollObject = [self krollObjectForProxy:proxy];
if (ourKrollObject != nil)
{
return ourKrollObject;
}
if (![context isKJSThread])
{
return nil;
}
#ifdef KROLL_COVERAGE
ourKrollObject = [[KrollCoverageObject alloc] initWithTarget:proxy context:context];
#else
ourKrollObject = [[KrollObject alloc] initWithTarget:proxy context:context];
#endif
[self registerProxy:proxy krollObject:ourKrollObject];
return [ourKrollObject autorelease];
}
- (void)unregisterProxy:(id)proxy
{
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL)
{
CFDictionaryRemoveValue(registeredProxies, proxy);
//Don't bother with removing the empty registry. It's small and leaves on dealloc anyways.
}
OSSpinLockUnlock(&proxyLock);
[proxy unboundBridge:self];
}
- (BOOL)usesProxy:(id)proxy
{
if (proxy == nil)
{
return NO;
}
BOOL result=NO;
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL)
{
result = (CFDictionaryGetCountOfKey(registeredProxies, proxy) != 0);
}
OSSpinLockUnlock(&proxyLock);
return result;
}
- (id)krollObjectForProxy:(id)proxy
{
id result=nil;
OSSpinLockLock(&proxyLock);
if (registeredProxies != NULL)
{
result = (id)CFDictionaryGetValue(registeredProxies, proxy);
}
OSSpinLockUnlock(&proxyLock);
return result;
}
-(id)loadCommonJSModule:(NSString*)code withSourceURL:(NSURL *)sourceURL
{
// This takes care of resolving paths like `../../foo.js`
sourceURL = [NSURL fileURLWithPath:[[sourceURL path] stringByStandardizingPath]];
// Get the relative path to the Resources directory
NSString *relativePath = [sourceURL path];
relativePath = [relativePath stringByReplacingOccurrencesOfString:[[[NSBundle mainBundle] resourceURL] path] withString:@""];
relativePath = [[relativePath substringFromIndex:1] stringByDeletingLastPathComponent];
NSString *dirname = [relativePath length] == 0 ? @"." : relativePath;
/*
* This is for parity with android, if the file is located in the Resources, then __dirname returns "."
* otherwise the __dirname returns the folder names separated by "/"
* for example:
* "/Resources/constants.js" __dirname = "."
* "/Resources/views/login/window.js" __dirname = "views/login"
*/
NSString *filename = [NSString stringWithFormat:@"%@/%@", dirname, [sourceURL lastPathComponent]];
NSString *js = [[NSString alloc] initWithFormat:TitaniumModuleRequireFormat, dirname, filename,code];
/* This most likely should be integrated with normal code flow, but to
* minimize impact until a in-depth reconsideration of KrollContext can be
* done, we should have as little footprint
*/
KrollEval *eval = [[KrollEval alloc] initWithCode:js sourceURL:sourceURL startingLineNo:1];
TiValueRef exception = NULL;
TiValueRef resultRef = [eval jsInvokeInContext:context exception:&exception];
[js release];
[eval release];
if (exception != NULL) {
id excm = [KrollObject toID:context value:exception];
[[TiExceptionHandler defaultExceptionHandler] reportScriptError:[TiUtils scriptErrorValue:excm]];
return nil;
}
/*
* In order to work around the underlying issue of TIMOB-2392, we must
* use KrollWrapper as a JS wrapper instead of converting it to a proxy
*/
KrollWrapper * result = [[KrollWrapper alloc] init];
[result setBridge:self];
[result setJsobject:(TiObjectRef)resultRef];
[result protectJsobject];
return [result autorelease];
}
-(NSString*)pathToModuleClassName:(NSString*)path
{
//TODO: switch to use ApplicationMods
NSArray *tokens = [path componentsSeparatedByString:@"."];
NSMutableString *modulename = [NSMutableString string];
for (NSString *token in tokens)
{
[modulename appendFormat:@"%@%@",[[token substringToIndex:1] uppercaseString],[token substringFromIndex:1]];
}
[modulename appendString:@"Module"];
return modulename;
}
- (TiModule *)loadCoreModule:(NSString *)path withContext:(KrollContext *)kroll
{
// make sure path doesn't begin with ., .., or /
// Can't be a "core" module then
if ([path hasPrefix:@"/"] || [path hasPrefix:@"."]) {
return nil;
}
// moduleId then is the first path component
NSString *moduleID = [[path pathComponents] objectAtIndex:0];
NSString *moduleClassName = [self pathToModuleClassName:moduleID];
Class moduleClass = NSClassFromString(moduleClassName);
if (moduleClass == nil) {
return nil;
}
// We have a module to load resources from! Now we need to determine if
// it's a base module (which should be cached) or a pure JS resource
// stored on the module.
TiModule *module = [modules objectForKey:moduleID];
if (module == nil) {
module = [[moduleClass alloc] _initWithPageContext:self];
[module setHost:host];
[module _setName:moduleClassName];
[modules setObject:module forKey:moduleID];
[module autorelease];
}
// TODO Handle the oddball case of mixing in JS to the native module...
/*
// TODO: Support package.json 'main' file identifier which will load instead
// of module JS. Currently neither iOS nor Android support package information.
NSRange separatorLocation = [fullPath rangeOfString:@"/"];
if (separatorLocation.location == NSNotFound) { // Indicates toplevel module
loadNativeJS:
if ([module isJSModule]) {
data = [module moduleJS];
}
[self setCurrentURL:[NSURL URLWithString:fullPath relativeToURL:[[self host] baseURL]]];
}
else {
NSString* assetPath = [fullPath substringFromIndex:separatorLocation.location+1];
// Handle the degenerate case (supported by MW) where we're loading
// module.id/module.id, which should resolve to module.id and mixin.
// Rather than create a utility method for this (or C&P if native loading changes)
// we use a goto to jump into the if block above.
if ([assetPath isEqualToString:moduleID]) {
goto loadNativeJS;
}
NSString* filepath = [assetPath stringByAppendingString:@".js"];
data = [module loadModuleAsset:filepath];
// Have to reset module so that this code doesn't get mixed in and is loaded as pure JS
module = nil;
}
if (data == nil && isAbsolute) {
// We may have an absolute URL which tried to load from a module instead of a directory. Fix
// the fullpath back to the right value, so we can try again.
fullPath = [path hasPrefix:@"/"]?[path substringFromIndex:1]:path;
}
else if (data != nil) {
// Set the current URL; it should be the fullPath relative to the host's base URL.
[self setCurrentURL:[NSURL URLWithString:[fullPath stringByDeletingLastPathComponent] relativeToURL:[[self host] baseURL]]];
}
// For right now, we need to mix any compiled JS on top of a compiled module, so that both components
// are accessible. We store the exports object and then put references to its properties on the toplevel
// object.
TiContextRef jsContext = [[self krollContext] context];
TiObjectRef jsObject = [wrapper jsobject];
KrollObject* moduleObject = [module krollObjectForContext:[self krollContext]];
[moduleObject noteObject:jsObject forTiString:kTiStringExportsKey context:jsContext];
TiPropertyNameArrayRef properties = TiObjectCopyPropertyNames(jsContext, jsObject);
size_t count = TiPropertyNameArrayGetCount(properties);
for (size_t i=0; i < count; i++) {
// Mixin the property onto the module JS object if it's not already there
TiStringRef propertyName = TiPropertyNameArrayGetNameAtIndex(properties, i);
if (!TiObjectHasProperty(jsContext, [moduleObject jsobject], propertyName)) {
TiValueRef property = TiObjectGetProperty(jsContext, jsObject, propertyName, NULL);
TiObjectSetProperty([[self krollContext] context], [moduleObject jsobject], propertyName, property, kTiPropertyAttributeReadOnly, NULL);
}
}
TiPropertyNameArrayRelease(properties);
*/
return module;
}
- (NSString *)loadFile:(NSString *)path
{
NSURL *url_ = [NSURL URLWithString:path relativeToURL:[[self host] baseURL]];
NSData *data = [TiUtils loadAppResource:url_];
if (data == nil) {
data = [NSData dataWithContentsOfURL:url_];
}
if (data != nil) {
[self setCurrentURL:[NSURL URLWithString:[path stringByDeletingLastPathComponent] relativeToURL:[[self host] baseURL]]];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
return nil;
}
- (TiModule *)loadJavascriptObject:(NSString *)data fromFile:(NSString *)filename withContext:(KrollContext *)kroll
{
// FIXME Move this up the stack to where we check for file existence?
// Now that we have the full path, we can check and see if the module was loaded,
// and return it if available.
if (modules != nil) {
TiModule *module = [modules objectForKey:filename];
if (module != nil) {
return module;
}
}
// We could cheat and just do "module.exports = %data%", but that wouldn't validate that the passed in content was JSON
// and may open a security hole.
// TODO It'd be good to try and handle things more gracefully if the JSON is "bad"/malformed
// Take JSON and turn into JS program that assigns module.exports to the parsed JSON
// 1. trim leading and trailing newlines and whitespace from JSON file
data = [data stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
// 2. Escape single quotes
data = [data stringByReplacingOccurrencesOfString:@"'" withString:@"\'"];
// 3. assign module.exports as JSON.parse call on the JSON
data = [@"module.exports = JSON.parse('" stringByAppendingString:data];
// 4. Replace newlines with "' +\n'"
data = [data stringByReplacingOccurrencesOfString:@"\n" withString:@"' +\n'"];
// 5. close the JSON string and end the JSON.parse call
data = [data stringByAppendingString:@"');"];
return [self loadJavascriptText:data fromFile:filename withContext:kroll];
}
- (TiModule *)loadJavascriptText:(NSString *)data fromFile:(NSString *)filename withContext:(KrollContext *)kroll
{
// FIXME Move this up the stack to where we check for file existence?
// Now that we have the full path, we can check and see if the module was loaded,
// and return it if available.
if (modules != nil) {
TiModule *module = [modules objectForKey:filename];
if (module != nil) {
return module;
}
}
NSURL *url_ = [TiHost resourceBasedURL:filename baseURL:NULL];
KrollWrapper *wrapper = [self loadCommonJSModule:data withSourceURL:url_];
if (![wrapper respondsToSelector:@selector(replaceValue:forKey:notification:)]) {
@throw [NSException exceptionWithName:@"org.appcelerator.kroll"
reason:[NSString stringWithFormat:@"Module \"%@\" failed to leave a valid exports object", filename]
userInfo:nil];
}
// register the module if it's pure JS
TiModule *module = (id)wrapper;
// cache the module by filename
[modules setObject:module forKey:filename];
if (filename != nil && module != nil) {
// uri is optional but we point it to where we loaded it
[module replaceValue:[NSString stringWithFormat:@"app://%@", filename] forKey:@"uri" notification:NO];
[module replaceValue:filename forKey:@"id" notification:NO]; // set id to full path, originally this was the path from require call
}
return module;
}
- (TiModule *)loadAsFile:(NSString *)path withContext:(KrollContext *)kroll
{
// 1. If X is a file, load X as JavaScript text. STOP
NSString *filename = path;
NSString *data = [self loadFile:filename];
if (data != nil) {
// If the file extension is .json, load as JavascriptObject!
NSString *ext = [filename pathExtension];
if (ext != nil && [ext isEqual:@"json"]) {
return [self loadJavascriptObject:data fromFile:filename withContext:context];
}
return [self loadJavascriptText:data fromFile:filename withContext:context];
}
// 2. If X.js is a file, load X.js as JavaScript text. STOP
filename = [path stringByAppendingString:@".js"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptText:data fromFile:filename withContext:context];
}
// 3. If X.json is a file, parse X.json to a JavaScript Object. STOP
filename = [path stringByAppendingString:@".json"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptObject:data fromFile:filename withContext:context];
}
// failed to load anything!
return nil;
}
- (TiModule *)loadAsDirectory:(NSString *)path withContext:(KrollContext *)kroll
{
// 1. If X/package.json is a file,
NSString *filename = [path stringByAppendingPathComponent:@"package.json"];
NSString *data = [self loadFile:filename];
if (data != nil) {
// a. Parse X/package.json, and look for "main" field.
// Just cheat and use TiUtils.jsonParse here, rather than loading the package.json as a JS object...
NSDictionary *json = [TiUtils jsonParse:data];
if (json != nil) {
id main = [json objectForKey:@"main"];
NSString *mainString = nil;
if ([main isKindOfClass:[NSString class]]) {
mainString = (NSString *)main;
// b. let M = X + (json main field)
NSString *m = [[path stringByAppendingPathComponent:mainString] stringByStandardizingPath];
// c. LOAD_AS_FILE(M)
return [self loadAsFile:m withContext:context];
}
}
}
// 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
filename = [path stringByAppendingPathComponent:@"index.js"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptText:data fromFile:filename withContext:context];
}
// 3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
filename = [path stringByAppendingPathComponent:@"index.json"];
data = [self loadFile:filename];
if (data != nil) {
return [self loadJavascriptObject:data fromFile:filename withContext:context];
}
return nil;
}
- (TiModule *)loadAsFileOrDirectory:(NSString *)path withContext:(KrollContext *)kroll
{
TiModule *module = nil;
// a. LOAD_AS_FILE(Y + X)
module = [self loadAsFile:path withContext:context];
if (module) {
return module;
}
// b. LOAD_AS_DIRECTORY(Y + X)
module = [self loadAsDirectory:path withContext:context];
if (module) {
return module;
}
return nil;
}
- (id)require:(KrollContext *)kroll path:(NSString *)path
{
NSURL *oldURL = [self currentURL];
@try {
// 1. If X is a core module,
TiModule *module = [self loadCoreModule:path withContext:kroll];
if (module) {
// a. return the core module
// b. STOP
return module;
}
// 2. If X begins with './' or '/' or '../'
if ([path hasPrefix:@"./"] || [path hasPrefix:@"../"]) {
// Need base path to work from for relative modules...
NSString *workingPath = [oldURL relativePath];
NSString *relativePath = (workingPath == nil) ? path : [workingPath stringByAppendingPathComponent:path];
module = [self loadAsFileOrDirectory:[relativePath stringByStandardizingPath] withContext:context];
if (module) {
return module;
}
// Treat '/' special as absolute, drop the leading '/'
}
else if ([path hasPrefix:@"/"]) {
module = [self loadAsFileOrDirectory:[[path substringFromIndex:1] stringByStandardizingPath] withContext:context];
if (module) {
return module;
}
} else {
// TODO Allow looking through node_modules
// 3. LOAD_NODE_MODULES(X, dirname(Y))
// Look for CommonJS module
if (![path containsString:@"/"]) {
// For CommonJS we need to look for module.id/module.id.js first...
// TODO Only look for this _exact file_. DO NOT APPEND .js or .json to it!
module = [self loadAsFile:[[path stringByAppendingPathComponent:path] stringByAppendingPathExtension:@"js"] withContext:context];
if (module) {
return module;
}
// Then try module.id as directory
module = [self loadAsDirectory:path withContext:context];
if (module) {
return module;
}
}
// TODO Find a way to determine if the first path segment refers to a CommonJS module, and if so don't log
// TODO How can we make this spit this out to Ti.API.log?
NSLog(@"require called with un-prefixed module id, should be a core or CommonJS module. Falling back to old Ti behavior and assuming it's an absolute file");
module = [self loadAsFileOrDirectory:[path stringByStandardizingPath] withContext:context];
if (module) {
return module;
}
}
}
@finally {
[self setCurrentURL:oldURL];
}
// 4. THROW "not found"
NSString *arch = [TiUtils currentArchitecture];
@throw [NSException exceptionWithName:@"org.test.kroll" reason:[NSString stringWithFormat:@"Couldn't find module: %@ for architecture: %@", path, arch] userInfo:nil]; // TODO Set 'code' property to 'MODULE_NOT_FOUND' to match Node?
}
+ (NSArray *)krollBridgesUsingProxy:(id)proxy
{
NSMutableArray * results = nil;
OSSpinLockLock(&krollBridgeRegistryLock);
signed long bridgeCount = CFSetGetCount(krollBridgeRegistry);
KrollBridge * registryObjects[bridgeCount];
CFSetGetValues(krollBridgeRegistry, (const void **)registryObjects);
for (int currentBridgeIndex = 0; currentBridgeIndex < bridgeCount; currentBridgeIndex++)
{
KrollBridge * currentBridge = registryObjects[currentBridgeIndex];
if (![currentBridge usesProxy:proxy])
{
continue;
}
if (results == nil)
{
results = [NSMutableArray arrayWithObject:currentBridge];
continue;
}
[results addObject:currentBridge];
}
//Why do we wait so long? In case someone tries to dealloc the krollBridge while we're looking at it.
//registryObjects nor the registry does a retain here!
OSSpinLockUnlock(&krollBridgeRegistryLock);
return results;
}
+ (NSArray *)krollContexts
{
OSSpinLockLock(&krollBridgeRegistryLock);
signed long bridgeCount = CFSetGetCount(krollBridgeRegistry);
KrollBridge * registryObjects[bridgeCount];
CFSetGetValues(krollBridgeRegistry, (const void **)registryObjects);
NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:0];
for (NSUInteger currentBridgeIndex = 0; currentBridgeIndex < bridgeCount; ++currentBridgeIndex) {
KrollBridge *bridge = registryObjects[currentBridgeIndex];
[results addObject:bridge.krollContext];
}
OSSpinLockUnlock(&krollBridgeRegistryLock);
return [results autorelease];
}
+ (BOOL)krollBridgeExists:(KrollBridge *)bridge
{
if(bridge == nil)
{
return NO;
}
bool result=NO;
OSSpinLockLock(&krollBridgeRegistryLock);
signed long bridgeCount = CFSetGetCount(krollBridgeRegistry);
KrollBridge * registryObjects[bridgeCount];
CFSetGetValues(krollBridgeRegistry, (const void **)registryObjects);
for (int currentBridgeIndex = 0; currentBridgeIndex < bridgeCount; currentBridgeIndex++)
{
KrollBridge * currentBridge = registryObjects[currentBridgeIndex];
if (currentBridge == bridge)
{
result = YES;
break;
}
}
//Why not CFSetContainsValue? Because bridge may not be a valid pointer, and SetContainsValue
//will ask it for a hash!
OSSpinLockUnlock(&krollBridgeRegistryLock);
return result;
}
+ (KrollBridge *)krollBridgeForThreadName:(NSString *)threadName;
{
if(threadName == nil)
{
return nil;
}
KrollBridge * result=nil;
OSSpinLockLock(&krollBridgeRegistryLock);
signed long bridgeCount = CFSetGetCount(krollBridgeRegistry);
KrollBridge * registryObjects[bridgeCount];
CFSetGetValues(krollBridgeRegistry, (const void **)registryObjects);
for (int currentBridgeIndex = 0; currentBridgeIndex < bridgeCount; currentBridgeIndex++)
{
KrollBridge * currentBridge = registryObjects[currentBridgeIndex];
#ifdef TI_USE_KROLL_THREAD
if ([[[currentBridge krollContext] threadName] isEqualToString:threadName])
{
result = [[currentBridge retain] autorelease];
break;
}
#endif
}
OSSpinLockUnlock(&krollBridgeRegistryLock);
return result;
}
-(int)forceGarbageCollectNow;
{
[context gc];
//Actually forcing garbage collect now will cause a deadlock.
return 0;
}
-(BOOL)shouldDebugContext
{
return [[self host] debugMode];
}
- (BOOL)shouldProfileContext
{
return [[self host] profileMode];
}
@end
| {
"content_hash": "7857e2b9137638267b99dddcfd862643",
"timestamp": "",
"source": "github",
"line_count": 1261,
"max_line_length": 233,
"avg_line_length": 30.869151467089612,
"alnum_prop": 0.7146380311360017,
"repo_name": "cheekiatng/titanium_mobile",
"id": "6a1d0ce891c43f648c2f15eea0dcbac40f3f2264",
"size": "39163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iphone/Classes/KrollBridge.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2552"
},
{
"name": "C",
"bytes": "203449"
},
{
"name": "C#",
"bytes": "80533"
},
{
"name": "C++",
"bytes": "207588"
},
{
"name": "CSS",
"bytes": "16297"
},
{
"name": "HTML",
"bytes": "186269"
},
{
"name": "Java",
"bytes": "2761605"
},
{
"name": "JavaScript",
"bytes": "4605244"
},
{
"name": "Makefile",
"bytes": "9707"
},
{
"name": "Mako",
"bytes": "1855"
},
{
"name": "Objective-C",
"bytes": "3989088"
},
{
"name": "Objective-C++",
"bytes": "8560"
},
{
"name": "Python",
"bytes": "1414514"
},
{
"name": "Shell",
"bytes": "28122"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types = 1);
namespace Innmind\Neo4j\ONM\Translation\Specification;
use Innmind\Neo4j\ONM\{
Translation\SpecificationTranslator,
Translation\Specification\Visitor\PropertyMatch\RelationshipVisitor as RelationshipPropertyMatchVisitor,
Translation\Specification\Visitor\Cypher\RelationshipVisitor as RelationshipCypherVisitor,
Metadata\Entity,
Metadata\Relationship,
IdentityMatch,
Query\PropertiesMatch,
Exception\SpecificationNotApplicableAsPropertyMatch,
};
use Innmind\Neo4j\DBAL\Query\Query;
use Innmind\Immutable\Map;
use Innmind\Specification\Specification;
final class RelationshipTranslator implements SpecificationTranslator
{
public function __invoke(
Entity $meta,
Specification $specification
): IdentityMatch {
if (!$meta instanceof Relationship) {
throw new \TypeError('Argument 1 must be of type '.Relationship::class);
}
try {
$mapping = (new RelationshipPropertyMatchVisitor($meta))($specification);
$query = $this->addProperties(
$this
->addProperties(
$this
->addProperties(
(new Query)->match('start'),
'start',
$mapping,
)
->linkedTo('end'),
'end',
$mapping,
)
->through(
$meta->type()->toString(),
'entity',
'right',
),
'entity',
$mapping,
);
} catch (SpecificationNotApplicableAsPropertyMatch $e) {
$condition = (new RelationshipCypherVisitor($meta))($specification);
$query = (new Query)
->match('start')
->linkedTo('end')
->through(
$meta->type()->toString(),
'entity',
'right',
)
->where($condition->cypher());
$query = $condition->parameters()->reduce(
$query,
static function(Query $query, string $key, $value): Query {
return $query->withParameter($key, $value);
},
);
}
/** @psalm-suppress InvalidArgument */
return new IdentityMatch(
$query->return('start', 'end', 'entity'),
Map::of('string', Entity::class)
('entity', $meta),
);
}
/**
* @param Map<string, PropertiesMatch> $mapping
*/
private function addProperties(
Query $query,
string $name,
Map $mapping
): Query {
if ($mapping->contains($name)) {
$match = $mapping->get($name);
$query = $match->properties()->reduce(
$query,
static function(Query $query, string $property, string $cypher): Query {
return $query->withProperty($property, $cypher);
},
);
$query = $match->parameters()->reduce(
$query,
static function(Query $query, string $key, $value): Query {
return $query->withParameter($key, $value);
},
);
}
return $query;
}
}
| {
"content_hash": "5d538cd67cced2dfcde3c869108cf1a9",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 108,
"avg_line_length": 33.046728971962615,
"alnum_prop": 0.48755656108597284,
"repo_name": "Innmind/neo4j-onm",
"id": "d162f2483dab6179b772fa11e75d3daa9ba8b6fa",
"size": "3536",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/Translation/Specification/RelationshipTranslator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "427222"
}
],
"symlink_target": ""
} |
"use strict";
module.exports = function(game) { // eslint-disable-line no-unused-vars
game.scaleCanvasToFitRectangle(1080,1920);
var player = 1;
var position = game.entities.get(player, "position");
var size = game.entities.get(player, "size");
position.x = (game.canvas.width / 2) - (size.width / 2);
position.y = (game.canvas.height / 2) + (size.height / 2);
};
| {
"content_hash": "2eb1ca9b8cefa3c27b6e93cf9279da98",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 71,
"avg_line_length": 34.36363636363637,
"alnum_prop": 0.671957671957672,
"repo_name": "AlexBezuska/Glazing-Lazers-ECS",
"id": "fe1e81aa20b2212324c982a81fdd433f452eb36f",
"size": "378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/scripts/main-enter.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "823"
},
{
"name": "JavaScript",
"bytes": "15620"
}
],
"symlink_target": ""
} |
package sds.classfile.attributes.annotation;
import java.io.IOException;
import sds.classfile.ClassFileStream;
import sds.classfile.ConstantPool;
import sds.classfile.attributes.AttributeInfo;
import sds.classfile.attributes.AttributeType;
import static sds.util.AnnotationParser.parseAnnotation;
/**
* This adapter class is for
* {@link RuntimeVisibleAnnotations <code>RuntimeVisibleAnnotations</code>} and
* {@link RuntimeInvisibleAnnotations <code>RuntimeInvisibleAnnotations</code>}.
* @author inagaki
*/
abstract class RuntimeAnnotations extends AttributeInfo {
private String[] annotations;
RuntimeAnnotations(AttributeType type) {
super(type);
}
@Override
public void read(ClassFileStream data, ConstantPool pool) throws IOException, ElementValueException {
this.annotations = new String[data.readShort()];
for(int i = 0; i < annotations.length; i++) {
annotations[i] = parseAnnotation(new Annotation(data), new StringBuilder(), pool);
}
}
/**
* returns runtime annotations.
* @return runtime annotations
*/
public String[] getAnnotations() {
return annotations;
}
} | {
"content_hash": "6e3c8b887b0c7216d0b3a5d507b327dd",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 102,
"avg_line_length": 28.53846153846154,
"alnum_prop": 0.7690925426774483,
"repo_name": "g1144146/SDS",
"id": "0226656810bc6867177a49302b814153cb4b8452",
"size": "1113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/sds/classfile/attributes/annotation/RuntimeAnnotations.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "359493"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed May 02 00:35:13 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.microprofile.jwtauth.deployment.auth.KeyUtils (BOM: * : All 2018.5.0 API)</title>
<meta name="date" content="2018-05-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.microprofile.jwtauth.deployment.auth.KeyUtils (BOM: * : All 2018.5.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/microprofile/jwtauth/deployment/auth/KeyUtils.html" title="class in org.wildfly.swarm.microprofile.jwtauth.deployment.auth">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.5.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/microprofile/jwtauth/deployment/auth/class-use/KeyUtils.html" target="_top">Frames</a></li>
<li><a href="KeyUtils.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.microprofile.jwtauth.deployment.auth.KeyUtils" class="title">Uses of Class<br>org.wildfly.swarm.microprofile.jwtauth.deployment.auth.KeyUtils</h2>
</div>
<div class="classUseContainer">No usage of org.wildfly.swarm.microprofile.jwtauth.deployment.auth.KeyUtils</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/microprofile/jwtauth/deployment/auth/KeyUtils.html" title="class in org.wildfly.swarm.microprofile.jwtauth.deployment.auth">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.5.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/microprofile/jwtauth/deployment/auth/class-use/KeyUtils.html" target="_top">Frames</a></li>
<li><a href="KeyUtils.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "0865bef4285be03348f1324094e18376",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 193,
"avg_line_length": 40.828125,
"alnum_prop": 0.6088786835055492,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "6735871c7a13bb8ea4d2271f9c8efc1e9283df89",
"size": "5226",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2018.5.0/apidocs/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/class-use/KeyUtils.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace llvm {
class vSSA : public FunctionPass {
public:
static char ID; // Pass identification, replacement for typeid.
vSSA() : FunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const;
bool runOnFunction(Function&);
private:
// Variables always liive
DominatorTreeWrapperPass *DTw_;
DominatorTree *DT_;
DominanceFrontier *DF_;
void createSigmasIfNeeded(BasicBlock *BB);
void insertSigmas(TerminatorInst *TI, Value *V);
void renameUsesToSigma(Value *V, PHINode *sigma);
SmallVector<PHINode*, 25> insertPhisForSigma(Value *V, PHINode *sigma);
void insertPhisForPhi(Value *V, PHINode *phi);
void renameUsesToPhi(Value *V, PHINode *phi);
void insertSigmaAsOperandOfPhis(SmallVector<PHINode*, 25> &vssaphi_created, PHINode *sigma);
void populatePhis(SmallVector<PHINode*, 25> &vssaphi_created, Value *V);
bool dominateAny(BasicBlock *BB, Value *value);
bool dominateOrHasInFrontier(BasicBlock *BB, BasicBlock *BB_next, Value *value);
bool verifySigmaExistance(Value *V, BasicBlock *BB, BasicBlock *from);
};
}
| {
"content_hash": "25ddf0deb8c18be31366bd370aefac67",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 93,
"avg_line_length": 37.25,
"alnum_prop": 0.7641418983700863,
"repo_name": "vmpaisante/sraa",
"id": "b2505881665937ca049d3b9a192f772b5551c8f0",
"size": "1738",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ComplementaryPasses/vSSA/vSSA.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4624"
},
{
"name": "C++",
"bytes": "246574"
},
{
"name": "Makefile",
"bytes": "4886"
},
{
"name": "Perl",
"bytes": "3041"
},
{
"name": "Shell",
"bytes": "5044"
}
],
"symlink_target": ""
} |
using BuildDoc.Entities.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildDoc.Logic
{
public interface IFormLogic
{
FormViewModel GetFormDataByObjectId(int ObjectId, int FormType);
string GetValFormList(List<FormLabelDTO> lst, string Field);
}
}
| {
"content_hash": "9d837ed6886cfda2387e80b690b7ee3b",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 72,
"avg_line_length": 21.529411764705884,
"alnum_prop": 0.7486338797814208,
"repo_name": "idoku/BuildDoc",
"id": "58433aa568c4b3155cb8c2615183753fafeee15c",
"size": "368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BuildDoc.Logic/IFormLogic.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "C#",
"bytes": "958134"
},
{
"name": "CSS",
"bytes": "148730"
},
{
"name": "HTML",
"bytes": "38566"
},
{
"name": "JavaScript",
"bytes": "188019"
}
],
"symlink_target": ""
} |
/*
var style = document.createElement('style')
style.type = 'text/css'
style.innerHTML = 'content'
document.getElementsByTagName('head')[0].appendChild(style)
#FACETFILTER_1_control_loadingState {visibility: hidden !important;}
#FACETFILTER_1_control_loadingStateBox {visibility: hidden !important;}
#FACETFILTER_1_control_loadingState_message {visibility: hidden !important;}
*/
div[class~=scn-pack-FacetFilter-MarkPositiveValue] ul>li[data-valueSign="+"] {background-color: #8ff78c!important;}
div[class~=scn-pack-FacetFilter-MarkNegativeValue] ul>li[data-valueSign="-"] {background-color: #f89b8b!important;}
div[class~=scn-pack-FacetFilter-MarkAnyValue] ul>li[data-valueSign="+"] {background-color: #b9efff!important;}
div[class~=scn-pack-FacetFilter-MarkAnyValue] ul>li[data-valueSign="-"] {background-color: #b9efff!important;}
div[class~=scn-pack-FacetFilter-MarkAnyEmptyValue] ul>li[data-valueSign="-"] {background-color: #ffffb9!important;}
div[class~=scn-pack-FullSizeChildren] div[class=sapUiLayoutAbsPos] {width: 100% !important;height: 100% !important;} | {
"content_hash": "e2e0e213f38749ed36fd4b3472153158",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 116,
"avg_line_length": 53.55,
"alnum_prop": 0.7740429505135388,
"repo_name": "Dibyendu21/Project",
"id": "991cdf361f9e8d29ca8c9c285d2470ec5f0e5ef8",
"size": "1071",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org.scn.community.databound/res/FacetFilter/FacetFilter.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "586360"
},
{
"name": "HTML",
"bytes": "457030"
},
{
"name": "JavaScript",
"bytes": "8729013"
},
{
"name": "Shell",
"bytes": "14120"
}
],
"symlink_target": ""
} |
namespace gfx {
struct PresentationFeedback;
}
namespace ash {
namespace hud_display {
class ReferenceLines;
// Draws several graphs per UI compositor frame. Every time
// OnDidPresentCompositorFrame() is called a new value is appended to the end
// of the graph. Every time UpdateData() is called, legend values are updated.
class FPSGraphPageView : public GraphPageViewBase,
public ui::CompositorObserver,
public views::WidgetObserver,
public aura::WindowObserver {
public:
METADATA_HEADER(FPSGraphPageView);
explicit FPSGraphPageView(const base::TimeDelta refresh_interval);
FPSGraphPageView(const FPSGraphPageView&) = delete;
FPSGraphPageView& operator=(const FPSGraphPageView&) = delete;
~FPSGraphPageView() override;
// GraphPageViewBase:
void AddedToWidget() override;
void RemovedFromWidget() override;
void OnPaint(gfx::Canvas* canvas) override;
void UpdateData(const DataSource::Snapshot& snapshot) override;
// ui::CompositorObserver:
void OnDidPresentCompositorFrame(
uint32_t frame_token,
const gfx::PresentationFeedback& feedback) override;
// views::WidgetObserver:
void OnWidgetDestroying(views::Widget* widget) override;
// aura::WindowObserver:
void OnWindowAddedToRootWindow(aura::Window* window) override;
void OnWindowRemovingFromRootWindow(aura::Window* window,
aura::Window* new_root) override;
private:
float frame_rate_for_last_second() const { return presented_times_.size(); }
float frame_rate_for_last_half_second() const {
return frame_rate_for_last_half_second_;
}
// Sets top reference line label to the maximum of the observed refresh rate.
void UpdateTopLabel(float f_refresh_rate);
// Updates the stats with |feedback|.
void UpdateStats(const gfx::PresentationFeedback& feedback);
// Number of frames per second presented.
Graph frame_rate_1s_;
Graph frame_rate_500ms_;
// Active display refresh rate.
Graph refresh_rate_;
ReferenceLines* reference_lines_; // not owned
float frame_rate_for_last_half_second_;
// |timestamp| from PresentationFeedback for one second.
base::circular_deque<base::TimeTicks> presented_times_;
};
} // namespace hud_display
} // namespace ash
#endif // ASH_HUD_DISPLAY_FPS_GRAPH_PAGE_VIEW_H_
| {
"content_hash": "a5ebfcf568a07e1fd5b6d671918e3290",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 79,
"avg_line_length": 31.68,
"alnum_prop": 0.7163299663299664,
"repo_name": "scheib/chromium",
"id": "2050977161644bc1afcb19cec00829fd3b6798c9",
"size": "2915",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "ash/hud_display/fps_graph_page_view.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
vagrant-docker
==============
Sample Vagrant Docker Provisioning
| {
"content_hash": "8c7166217f4fd977ec7f25c8d94066a0",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 34,
"avg_line_length": 16.5,
"alnum_prop": 0.6666666666666666,
"repo_name": "afritzler/vagrant-docker",
"id": "763ff61c96e01c61fa894a1f6797a286639fb11c",
"size": "66",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from __future__ import unicode_literals
"""
Boot session from cache or build
Session bootstraps info needed by common client side activities including
permission, homepage, default variables, system defaults etc
"""
import frappe, json
from frappe import _
import frappe.utils
from frappe.utils import cint, cstr
import frappe.model.meta
import frappe.defaults
import frappe.translate
from frappe.utils.change_log import get_change_log
import redis
from urllib import unquote
from frappe.desk.notifications import clear_notifications
@frappe.whitelist()
def clear(user=None):
frappe.local.session_obj.update(force=True)
frappe.local.db.commit()
clear_cache(frappe.session.user)
clear_global_cache()
frappe.response['message'] = _("Cache Cleared")
def clear_cache(user=None):
cache = frappe.cache()
groups = ("bootinfo", "user_recent", "user_roles", "user_doc", "lang",
"defaults", "user_permissions", "roles", "home_page", "linked_with",
"desktop_icons", 'portal_menu_items')
if user:
for name in groups:
cache.hdel(name, user)
cache.delete_keys("user:" + user)
frappe.defaults.clear_cache(user)
else:
for name in groups:
cache.delete_key(name, user)
clear_global_cache()
frappe.defaults.clear_cache()
clear_notifications(user)
def clear_global_cache():
frappe.model.meta.clear_cache()
frappe.cache().delete_value(["app_hooks", "installed_apps",
"app_modules", "module_app", "notification_config", 'system_settings'
'scheduler_events', 'time_zone'])
frappe.setup_module_map()
def clear_sessions(user=None, keep_current=False, device=None):
if not user:
user = frappe.session.user
if not device:
device = frappe.session.data.device or "desktop"
limit = 0
if user == frappe.session.user:
simultaneous_sessions = frappe.db.get_value('User', user, 'simultaneous_sessions') or 1
limit = simultaneous_sessions - 1
condition = ''
if keep_current:
condition = ' and sid != "{0}"'.format(frappe.db.escape(frappe.session.sid))
for i, sid in enumerate(frappe.db.sql_list("""select sid from tabSessions
where user=%s and device=%s {condition}
order by lastupdate desc limit {limit}, 100""".format(condition=condition, limit=limit),
(user, device))):
delete_session(sid, reason="Logged In From Another Session")
def delete_session(sid=None, user=None, reason="Session Expired"):
from frappe.core.doctype.communication.feed import logout_feed
frappe.cache().hdel("session", sid)
frappe.cache().hdel("last_db_session_update", sid)
if sid and not user:
user_details = frappe.db.sql("""select user from tabSessions where sid=%s""", sid, as_dict=True)
if user_details: user = user_details[0].get("user")
logout_feed(user, reason)
frappe.db.sql("""delete from tabSessions where sid=%s""", sid)
frappe.db.commit()
def clear_all_sessions(reason=None):
"""This effectively logs out all users"""
frappe.only_for("Administrator")
if not reason: reason = "Deleted All Active Session"
for sid in frappe.db.sql_list("select sid from `tabSessions`"):
delete_session(sid, reason=reason)
def clear_expired_sessions():
"""This function is meant to be called from scheduler"""
for device in ("desktop", "mobile"):
for sid in frappe.db.sql_list("""select sid from tabSessions
where TIMEDIFF(NOW(), lastupdate) > TIME(%s)
and device = %s""", (get_expiry_period(device), device)):
delete_session(sid, reason="Session Expired")
def get():
"""get session boot info"""
from frappe.desk.notifications import \
get_notification_info_for_boot, get_notifications
from frappe.boot import get_bootinfo, get_unseen_notes
from frappe.limits import get_limits, get_expiry_message
bootinfo = None
if not getattr(frappe.conf,'disable_session_cache', None):
# check if cache exists
bootinfo = frappe.cache().hget("bootinfo", frappe.session.user)
if bootinfo:
bootinfo['from_cache'] = 1
bootinfo["notification_info"].update(get_notifications())
bootinfo["user"]["recent"] = json.dumps(\
frappe.cache().hget("user_recent", frappe.session.user))
if not bootinfo:
# if not create it
bootinfo = get_bootinfo()
bootinfo["notification_info"] = get_notification_info_for_boot()
frappe.cache().hset("bootinfo", frappe.session.user, bootinfo)
try:
frappe.cache().ping()
except redis.exceptions.ConnectionError:
message = _("Redis cache server not running. Please contact Administrator / Tech support")
if 'messages' in bootinfo:
bootinfo['messages'].append(message)
else:
bootinfo['messages'] = [message]
# check only when clear cache is done, and don't cache this
if frappe.local.request:
bootinfo["change_log"] = get_change_log()
bootinfo["metadata_version"] = frappe.cache().get_value("metadata_version")
if not bootinfo["metadata_version"]:
bootinfo["metadata_version"] = frappe.reset_metadata_version()
bootinfo.notes = get_unseen_notes()
for hook in frappe.get_hooks("extend_bootinfo"):
frappe.get_attr(hook)(bootinfo=bootinfo)
bootinfo["lang"] = frappe.translate.get_user_lang()
bootinfo["disable_async"] = frappe.conf.disable_async
# limits
bootinfo.limits = get_limits()
bootinfo.expiry_message = get_expiry_message()
return bootinfo
def get_csrf_token():
if not frappe.local.session.data.csrf_token:
generate_csrf_token()
return frappe.local.session.data.csrf_token
def generate_csrf_token():
frappe.local.session.data.csrf_token = frappe.generate_hash()
frappe.local.session_obj.update(force=True)
# send sid and csrf token to the user
# handles the case when a user logs in again from another tab
# and it leads to invalid request in the current tab
frappe.publish_realtime(event="csrf_generated",
message={"sid": frappe.local.session.sid, "csrf_token": frappe.local.session.data.csrf_token},
user=frappe.session.user, after_commit=True)
class Session:
def __init__(self, user, resume=False, full_name=None, user_type=None):
self.sid = cstr(frappe.form_dict.get('sid') or
unquote(frappe.request.cookies.get('sid', 'Guest')))
self.user = user
self.device = frappe.form_dict.get("device") or "desktop"
self.user_type = user_type
self.full_name = full_name
self.data = frappe._dict({'data': frappe._dict({})})
self.time_diff = None
# set local session
frappe.local.session = self.data
if resume:
self.resume()
else:
if self.user:
self.start()
def start(self):
"""start a new session"""
# generate sid
if self.user=='Guest':
sid = 'Guest'
else:
sid = frappe.generate_hash()
self.data.user = self.user
self.data.sid = sid
self.data.data.user = self.user
self.data.data.session_ip = frappe.local.request_ip
if self.user != "Guest":
self.data.data.update({
"last_updated": frappe.utils.now(),
"session_expiry": get_expiry_period(self.device),
"full_name": self.full_name,
"user_type": self.user_type,
"device": self.device,
"session_country": get_geo_ip_country(frappe.local.request_ip) if frappe.local.request_ip else None,
})
# insert session
if self.user!="Guest":
self.insert_session_record()
# update user
frappe.db.sql("""UPDATE tabUser SET last_login = %(now)s, last_ip = %(ip)s, last_active = %(now)s
where name=%(name)s""", {
"now": frappe.utils.now(),
"ip": frappe.local.request_ip,
"name": self.data['user']
})
frappe.db.commit()
def insert_session_record(self):
frappe.db.sql("""insert into tabSessions
(sessiondata, user, lastupdate, sid, status, device)
values (%s , %s, NOW(), %s, 'Active', %s)""",
(str(self.data['data']), self.data['user'], self.data['sid'], self.device))
# also add to memcache
frappe.cache().hset("session", self.data.sid, self.data)
def resume(self):
"""non-login request: load a session"""
import frappe
data = self.get_session_record()
if data:
# set language
self.data.update({'data': data, 'user':data.user, 'sid': self.sid})
self.user = data.user
self.device = data.device
else:
self.start_as_guest()
if self.sid != "Guest":
frappe.local.user_lang = frappe.translate.get_user_lang(self.data.user)
frappe.local.lang = frappe.local.user_lang
def get_session_record(self):
"""get session record, or return the standard Guest Record"""
from frappe.auth import clear_cookies
r = self.get_session_data()
if not r:
frappe.response["session_expired"] = 1
clear_cookies()
self.sid = "Guest"
r = self.get_session_data()
return r
def get_session_data(self):
if self.sid=="Guest":
return frappe._dict({"user":"Guest"})
data = self.get_session_data_from_cache()
if not data:
data = self.get_session_data_from_db()
return data
def get_session_data_from_cache(self):
data = frappe.cache().hget("session", self.sid)
if data:
data = frappe._dict(data)
session_data = data.get("data", {})
# set user for correct timezone
self.time_diff = frappe.utils.time_diff_in_seconds(frappe.utils.now(),
session_data.get("last_updated"))
expiry = self.get_expiry_in_seconds(session_data.get("session_expiry"))
if self.time_diff > expiry:
self.delete_session()
data = None
return data and data.data
def get_session_data_from_db(self):
self.device = frappe.db.get_value("Sessions", {"sid": self.sid}, "device") or 'desktop'
rec = frappe.db.sql("""select user, sessiondata
from tabSessions where sid=%s and
TIMEDIFF(NOW(), lastupdate) < TIME(%s)""", (self.sid,
get_expiry_period(self.device)))
if rec:
data = frappe._dict(eval(rec and rec[0][1] or '{}'))
data.user = rec[0][0]
else:
self.delete_session()
data = None
return data
def get_expiry_in_seconds(self, expiry):
if not expiry:
return 3600
parts = expiry.split(":")
return (cint(parts[0]) * 3600) + (cint(parts[1]) * 60) + cint(parts[2])
def delete_session(self):
delete_session(self.sid, reason="Session Expired")
def start_as_guest(self):
"""all guests share the same 'Guest' session"""
self.user = "Guest"
self.start()
def update(self, force=False):
"""extend session expiry"""
if (frappe.session['user'] == "Guest" or frappe.form_dict.cmd=="logout"):
return
now = frappe.utils.now()
self.data['data']['last_updated'] = now
self.data['data']['lang'] = unicode(frappe.lang)
# update session in db
last_updated = frappe.cache().hget("last_db_session_update", self.sid)
time_diff = frappe.utils.time_diff_in_seconds(now, last_updated) if last_updated else None
# database persistence is secondary, don't update it too often
updated_in_db = False
if force or (time_diff==None) or (time_diff > 600):
# update sessions table
frappe.db.sql("""update tabSessions set sessiondata=%s,
lastupdate=NOW() where sid=%s""" , (str(self.data['data']),
self.data['sid']))
# update last active in user table
frappe.db.sql("""update `tabUser` set last_active=%(now)s where name=%(name)s""", {
"now": frappe.utils.now(),
"name": frappe.session.user
})
frappe.db.commit()
frappe.cache().hset("last_db_session_update", self.sid, now)
updated_in_db = True
# set in memcache
frappe.cache().hset("session", self.sid, self.data)
return updated_in_db
def get_expiry_period(device="desktop"):
if device=="mobile":
key = "session_expiry_mobile"
default = "720:00:00"
else:
key = "session_expiry"
default = "06:00:00"
exp_sec = frappe.defaults.get_global_default(key) or default
# incase seconds is missing
if len(exp_sec.split(':')) == 2:
exp_sec = exp_sec + ':00'
return exp_sec
def get_geo_from_ip(ip_addr):
try:
from geoip import geolite2
return geolite2.lookup(ip_addr)
except ImportError:
return
except ValueError:
return
def get_geo_ip_country(ip_addr):
match = get_geo_from_ip(ip_addr)
if match:
return match.country
| {
"content_hash": "5f0f0cfe294dc8e6283708b7a62e553e",
"timestamp": "",
"source": "github",
"line_count": 393,
"max_line_length": 104,
"avg_line_length": 29.99236641221374,
"alnum_prop": 0.6911003648086875,
"repo_name": "elba7r/frameworking",
"id": "5fa2ba27dc2a9626ba92e83015311504d249eafa",
"size": "11888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frappe/sessions.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "336604"
},
{
"name": "HTML",
"bytes": "198854"
},
{
"name": "JavaScript",
"bytes": "1262443"
},
{
"name": "Python",
"bytes": "1614773"
},
{
"name": "Shell",
"bytes": "517"
}
],
"symlink_target": ""
} |
title: Design Time
page_title: Design Time - WinForms DateTimePicker Control
description: Learn what are the design time options of the WinForms DateTimePicker.
slug: winforms/editors/datetimepicker/designtime
tags: datetimepicker
published: True
position: 2
---
# Smart Tag
The __Smart Tag__ of __RadAutoCompleteBox__ lets you quickly access common tasks involved with and customizing the layout or setting the theme.
>caption Figure 1: The Smart Tag of RadAutoCompleteBox

* __Common Tasks__
- __New Theme Manager:__ Adds a new __RadThemeManager__ component to the form.
- __Edit UI elements:__ Opens a dialog that displays the __Element Hierarchy Editor.__ This editor lets you browse all the elements in the control.
- __Theme Name:__ Select a theme name from the drop down list of themes available for that control. Selecting a theme allows you to change all aspects of the controls visual style at one time.
* __Learning Center:__ Navigate to the Telerik help, code library projects or support forum.
* __Search:__ Search the Telerik site for a given string.
# See Also
* [Add Themes]({%slug winforms/themes/using-default-themes%})
* [Free Form Date Time Parsing]({%slug winforms/editors/datetimepicker/free-form-date-time-parsing%})
* [MaskDateTimeProvider]({%slug winforms/editors/maskeddatetimeprovider%})
* [Properties]({%slug winforms/editors/datetimepicker/raddatetimepicker-properties%})
* [Structure]({%slug winforms/editors/datetimepicker%}) | {
"content_hash": "da91f68c9341678a505fa0b0713c3019",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 196,
"avg_line_length": 48.5,
"alnum_prop": 0.7667525773195877,
"repo_name": "telerik/winforms-docs",
"id": "08d518eec1112c731468eaa0344e019b7e58fc98",
"size": "1556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controls/editors/datetimepicker/design-time.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "96"
},
{
"name": "CSS",
"bytes": "2296"
},
{
"name": "HTML",
"bytes": "1629"
},
{
"name": "JavaScript",
"bytes": "42129"
},
{
"name": "Ruby",
"bytes": "882"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace TwitchLib.Models.API.Video
{
/// <summary>
/// Class representing returned Video object.
/// </summary>
public class Video
{
/// <summary>Object representing all channel data returned by this request.</summary>
public Channel Channel { get; protected set; }
/// <summary>Object representing the available FPSs of versions of the video (-1 representings property doesnt exist)</summary>
public FPS Fps { get; protected set; }
/// <summary>Language code associated with video.</summary>
public string Language { get; protected set; }
/// <summary>Length of video in seconds.</summary>
public TimeSpan Length { get; protected set; }
/// <summary>Number of recorded views.</summary>
public int Views { get; protected set; }
/// <summary>All available resolutions of video.</summary>
public Resolutions Resolutions { get; protected set; }
/// <summary>Unique identifier assigned to broadcast video originated from.</summary>
public string BroadcastId { get; protected set; }
/// <summary>Represents teh type of broadcast (could be custom upload)</summary>
public string BroadcastType { get; protected set; }
/// <summary>Creator's description of video.</summary>
public string Description { get; protected set; }
/// <summary>Similar to Description property, but with HTML elements.</summary>
public string DescriptionHtml { get; protected set; }
/// <summary>Game being played in the video.</summary>
public string Game { get; protected set; }
/// <summary>Id of the particular video.</summary>
public string Id { get; protected set; }
/// <summary>Video preview image link.</summary>
public Preview Preview { get; protected set; }
/// <summary>Date and time string representing recorded date.</summary>
public DateTime CreatedAt { get; protected set; }
/// <summary>TimeSpan object representing the time since the video was recorded.</summary>
public TimeSpan TimeSinceCreated { get; protected set; }
/// <summary>DateTime object representing the period at which the video was published.</summary>
public DateTime PublishedAt { get; protected set; }
/// <summary>Current status of the recorded video.</summary>
public string Status { get; protected set; }
/// <summary>Tags assigned to video either automatically or by content creator.</summary>
public string TagList { get; protected set; }
/// <summary>Title of video.</summary>
public string Title { get; protected set; }
/// <summary>Twitch URL to video.</summary>
public string Url { get; protected set; }
/// <summary>Current view status.</summary>
public string Viewable { get; protected set; }
/// <summary>View location.</summary>
public string ViewableAt { get; protected set; }
/// <summary>
/// Video constructor
/// </summary>
/// <param name="apiResponse">API response string from Twitch call.</param>
public Video(JToken apiResponse)
{
int length = -1;
int views = -1;
int audioFps = -1;
double mediumFps = -1;
double mobileFps = -1;
double highFps = -1;
double lowFps = -1;
double chunkedFps = -1;
if (int.TryParse(apiResponse.SelectToken("length").ToString(), out length)) Length = TimeSpan.FromSeconds(length);
if (int.TryParse(apiResponse.SelectToken("views").ToString(), out views)) Views = views;
if(apiResponse.SelectToken("fps").SelectToken("audio_only") != null)
int.TryParse(apiResponse.SelectToken("fps").SelectToken("audio_only").ToString(), out audioFps);
if(apiResponse.SelectToken("fps").SelectToken("medium") != null)
double.TryParse(apiResponse.SelectToken("fps").SelectToken("medium").ToString(), out mediumFps);
if(apiResponse.SelectToken("fps").SelectToken("mobile") != null)
double.TryParse(apiResponse.SelectToken("fps").SelectToken("mobile").ToString(), out mobileFps);
if(apiResponse.SelectToken("fps").SelectToken("high") != null)
double.TryParse(apiResponse.SelectToken("fps").SelectToken("high").ToString(), out highFps);
if(apiResponse.SelectToken("fps").SelectToken("low") != null)
double.TryParse(apiResponse.SelectToken("fps").SelectToken("low").ToString(), out lowFps);
if(apiResponse.SelectToken("fps").SelectToken("chunked") != null)
double.TryParse(apiResponse.SelectToken("fps").SelectToken("chunked").ToString(), out chunkedFps);
BroadcastId = apiResponse.SelectToken("broadcast_id")?.ToString();
BroadcastType = apiResponse.SelectToken("broadcast_type")?.ToString();
Description = apiResponse.SelectToken("description")?.ToString();
DescriptionHtml = apiResponse.SelectToken("description_html")?.ToString();
if(apiResponse.SelectToken("fps") != null)
Fps = new FPS(apiResponse.SelectToken("fps"));
Game = apiResponse.SelectToken("game")?.ToString();
Id = apiResponse.SelectToken("_id")?.ToString();
if (apiResponse.SelectToken("preview") != null)
Preview = new Preview(apiResponse.SelectToken("preview"));
CreatedAt = Common.Helpers.DateTimeStringToObject(apiResponse.SelectToken("created_at").ToString());
TimeSinceCreated = DateTime.UtcNow - CreatedAt;
Status = apiResponse.SelectToken("status")?.ToString();
TagList = apiResponse.SelectToken("tag_list")?.ToString();
Title = apiResponse.SelectToken("title")?.ToString();
Url = apiResponse.SelectToken("url")?.ToString();
if (apiResponse.SelectToken("published_at") != null)
PublishedAt = Common.Helpers.DateTimeStringToObject(apiResponse.SelectToken("published_at").ToString());
if(apiResponse.SelectToken("resolutions") != null)
Resolutions = new Resolutions(apiResponse.SelectToken("resolutions"));
Channel = new Channel(apiResponse.SelectToken("channel"));
Viewable = apiResponse.SelectToken("viewable")?.ToString();
ViewableAt = apiResponse.SelectToken("viewable_at")?.ToString();
}
}
} | {
"content_hash": "85e2cb08207f8ae93176e21c46ace137",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 135,
"avg_line_length": 57.88793103448276,
"alnum_prop": 0.6391660461653016,
"repo_name": "StylishKitsune/TwitchLib",
"id": "1793fc5ef39a3450c677e68abc33009a847840a9",
"size": "6717",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TwitchLib/Models/API/Video/Video.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "628033"
}
],
"symlink_target": ""
} |
import multiprocessing
import threading
from pybind11_tests import gil_scoped as m
def _run_in_process(target, *args, **kwargs):
"""Runs target in process and returns its exitcode after 10s (None if still alive)."""
process = multiprocessing.Process(target=target, args=args, kwargs=kwargs)
process.daemon = True
try:
process.start()
# Do not need to wait much, 10s should be more than enough.
process.join(timeout=10)
return process.exitcode
finally:
if process.is_alive():
process.terminate()
def _python_to_cpp_to_python():
"""Calls different C++ functions that come back to Python."""
class ExtendedVirtClass(m.VirtClass):
def virtual_func(self):
pass
def pure_virtual_func(self):
pass
extended = ExtendedVirtClass()
m.test_callback_py_obj(lambda: None)
m.test_callback_std_func(lambda: None)
m.test_callback_virtual_func(extended)
m.test_callback_pure_virtual_func(extended)
def _python_to_cpp_to_python_from_threads(num_threads, parallel=False):
"""Calls different C++ functions that come back to Python, from Python threads."""
threads = []
for _ in range(num_threads):
thread = threading.Thread(target=_python_to_cpp_to_python)
thread.daemon = True
thread.start()
if parallel:
threads.append(thread)
else:
thread.join()
for thread in threads:
thread.join()
# TODO: FIXME, sometimes returns -11 (segfault) instead of 0 on macOS Python 3.9
def test_python_to_cpp_to_python_from_thread():
"""Makes sure there is no GIL deadlock when running in a thread.
It runs in a separate process to be able to stop and assert if it deadlocks.
"""
assert _run_in_process(_python_to_cpp_to_python_from_threads, 1) == 0
# TODO: FIXME on macOS Python 3.9
def test_python_to_cpp_to_python_from_thread_multiple_parallel():
"""Makes sure there is no GIL deadlock when running in a thread multiple times in parallel.
It runs in a separate process to be able to stop and assert if it deadlocks.
"""
assert _run_in_process(_python_to_cpp_to_python_from_threads, 8, parallel=True) == 0
# TODO: FIXME on macOS Python 3.9
def test_python_to_cpp_to_python_from_thread_multiple_sequential():
"""Makes sure there is no GIL deadlock when running in a thread multiple times sequentially.
It runs in a separate process to be able to stop and assert if it deadlocks.
"""
assert (
_run_in_process(_python_to_cpp_to_python_from_threads, 8, parallel=False) == 0
)
# TODO: FIXME on macOS Python 3.9
def test_python_to_cpp_to_python_from_process():
"""Makes sure there is no GIL deadlock when using processes.
This test is for completion, but it was never an issue.
"""
assert _run_in_process(_python_to_cpp_to_python) == 0
def test_cross_module_gil():
"""Makes sure that the GIL can be acquired by another module from a GIL-released state."""
m.test_cross_module_gil() # Should not raise a SIGSEGV
| {
"content_hash": "1d617e5ee4105637a0996e62b28532f8",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 96,
"avg_line_length": 33.376344086021504,
"alnum_prop": 0.6723582474226805,
"repo_name": "gem5/gem5",
"id": "0a1d62747dbedb012c5e05eb66c15b7bef7f90c2",
"size": "3128",
"binary": false,
"copies": "6",
"ref": "refs/heads/stable",
"path": "ext/pybind11/tests/test_gil_scoped.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "145626"
},
{
"name": "Awk",
"bytes": "3386"
},
{
"name": "BASIC",
"bytes": "2884"
},
{
"name": "C",
"bytes": "3927153"
},
{
"name": "C++",
"bytes": "42960484"
},
{
"name": "CMake",
"bytes": "133888"
},
{
"name": "Dockerfile",
"bytes": "34102"
},
{
"name": "Emacs Lisp",
"bytes": "1914"
},
{
"name": "Forth",
"bytes": "354"
},
{
"name": "Fortran",
"bytes": "15436"
},
{
"name": "HTML",
"bytes": "146414"
},
{
"name": "Hack",
"bytes": "139769"
},
{
"name": "Java",
"bytes": "6966"
},
{
"name": "M4",
"bytes": "42624"
},
{
"name": "Makefile",
"bytes": "39573"
},
{
"name": "Perl",
"bytes": "23784"
},
{
"name": "Python",
"bytes": "8079781"
},
{
"name": "Roff",
"bytes": "8754"
},
{
"name": "SCSS",
"bytes": "2971"
},
{
"name": "SWIG",
"bytes": "173"
},
{
"name": "Scala",
"bytes": "5328"
},
{
"name": "Shell",
"bytes": "95638"
},
{
"name": "Starlark",
"bytes": "25668"
},
{
"name": "SuperCollider",
"bytes": "8869"
},
{
"name": "Vim Script",
"bytes": "4343"
},
{
"name": "sed",
"bytes": "3897"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0.001" tests="13" errors="0" skipped="0" failures="0">
<properties>
<property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
<property name="sun.boot.library.path" value="/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib"/>
<property name="java.vm.version" value="23.5-b02"/>
<property name="user.country.format" value="IN"/>
<property name="gopherProxySet" value="false"/>
<property name="java.vm.vendor" value="Oracle Corporation"/>
<property name="java.vendor.url" value="http://java.oracle.com/"/>
<property name="path.separator" value=":"/>
<property name="guice.disable.misplaced.annotation.check" value="true"/>
<property name="java.vm.name" value="Java HotSpot(TM) 64-Bit Server VM"/>
<property name="file.encoding.pkg" value="sun.io"/>
<property name="user.country" value="US"/>
<property name="sun.java.launcher" value="SUN_STANDARD"/>
<property name="sun.os.patch.level" value="unknown"/>
<property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
<property name="user.dir" value="/Users/nandu/Downloads/math (trunk)"/>
<property name="java.runtime.version" value="1.7.0_09-b05"/>
<property name="java.awt.graphicsenv" value="sun.awt.CGraphicsEnvironment"/>
<property name="java.endorsed.dirs" value="/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/endorsed"/>
<property name="os.arch" value="x86_64"/>
<property name="java.io.tmpdir" value="/var/folders/v3/9l6_62855xl2r1qshsbdv1l80000gn/T/"/>
<property name="line.separator" value=" "/>
<property name="java.vm.specification.vendor" value="Oracle Corporation"/>
<property name="os.name" value="Mac OS X"/>
<property name="classworlds.conf" value="/usr/share/maven/bin/m2.conf"/>
<property name="sun.jnu.encoding" value="UTF-8"/>
<property name="java.library.path" value="/Users/nandu/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:."/>
<property name="java.specification.name" value="Java Platform API Specification"/>
<property name="java.class.version" value="51.0"/>
<property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/>
<property name="os.version" value="10.7.5"/>
<property name="http.nonProxyHosts" value="local|*.local|169.254/16|*.169.254/16"/>
<property name="user.home" value="/Users/nandu"/>
<property name="user.timezone" value="Asia/Kolkata"/>
<property name="java.awt.printerjob" value="sun.lwawt.macosx.CPrinterJob"/>
<property name="java.specification.version" value="1.7"/>
<property name="file.encoding" value="UTF-8"/>
<property name="user.name" value="nandu"/>
<property name="java.class.path" value="/usr/share/maven/boot/plexus-classworlds-2.4.jar"/>
<property name="java.vm.specification.version" value="1.7"/>
<property name="sun.arch.data.model" value="64"/>
<property name="java.home" value="/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre"/>
<property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher clean install"/>
<property name="java.specification.vendor" value="Oracle Corporation"/>
<property name="user.language" value="en"/>
<property name="awt.toolkit" value="sun.lwawt.macosx.LWCToolkit"/>
<property name="java.vm.info" value="mixed mode"/>
<property name="java.version" value="1.7.0_09"/>
<property name="java.ext.dirs" value="/Users/nandu/Library/Java/Extensions:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java"/>
<property name="sun.boot.class.path" value="/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/sunrsasign.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/JObjC.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/classes"/>
<property name="java.vendor" value="Oracle Corporation"/>
<property name="maven.home" value="/usr/share/maven"/>
<property name="file.separator" value="/"/>
<property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/>
<property name="sun.cpu.endian" value="little"/>
<property name="sun.io.unicode.encoding" value="UnicodeBig"/>
<property name="socksNonProxyHosts" value="local|*.local|169.254/16|*.169.254/16"/>
<property name="ftp.nonProxyHosts" value="local|*.local|169.254/16|*.169.254/16"/>
<property name="sun.cpu.isalist" value=""/>
</properties>
<testcase name="testSpecialValues" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testMomentSmallSamples" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testSerialization" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0.001"/>
<testcase name="testIncrementation" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testConsistency" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testEqualsAndHashCode" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testCopyConsistency" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testSerial" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testCopy" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testEvaluation" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testEvaluateArraySegment" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testWeightedConsistency" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
<testcase name="testEvaluateArraySegmentWeighted" classname="org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest" time="0"/>
</testsuite> | {
"content_hash": "5951d0b20af8462e0577d38ddcefffe9",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 786,
"avg_line_length": 90.88311688311688,
"alnum_prop": 0.7403543869677051,
"repo_name": "tknandu/CommonsMath_Modifed",
"id": "e3fb303111e407b3136f04ef12c01f0a75fdf4b3",
"size": "6998",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "math (trunk)/target/surefire-reports/TEST-org.apache.commons.math3.stat.descriptive.moment.FirstMomentTest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3412"
},
{
"name": "HTML",
"bytes": "5012"
},
{
"name": "Java",
"bytes": "13514253"
},
{
"name": "R",
"bytes": "39299"
},
{
"name": "Shell",
"bytes": "12243"
},
{
"name": "XSLT",
"bytes": "2509"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="zh">
<head>
<!-- Generated by javadoc (version 1.7.0_40) on Mon Nov 04 09:26:00 CST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>类 org.apache.giraph.io.hcatalog.HCatalogVertexInputFormat.MultiRowHCatalogVertexReader的使用 (Apache Giraph HCatalog I/O 1.0.0 API)</title>
<meta name="date" content="2013-11-04">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="类 org.apache.giraph.io.hcatalog.HCatalogVertexInputFormat.MultiRowHCatalogVertexReader的使用 (Apache Giraph HCatalog I/O 1.0.0 API)";
}
//-->
</script>
<noscript>
<div>您的浏览器已禁用 JavaScript。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="跳过导航链接"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../../../overview-summary.html">概览</a></li>
<li><a href="../package-summary.html">程序包</a></li>
<li><a href="../../../../../../org/apache/giraph/io/hcatalog/HCatalogVertexInputFormat.MultiRowHCatalogVertexReader.html" title="org.apache.giraph.io.hcatalog中的类">类</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">树</a></li>
<li><a href="../../../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/giraph/io/hcatalog/class-use/HCatalogVertexInputFormat.MultiRowHCatalogVertexReader.html" target="_top">框架</a></li>
<li><a href="HCatalogVertexInputFormat.MultiRowHCatalogVertexReader.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="类 org.apache.giraph.io.hcatalog.HCatalogVertexInputFormat.MultiRowHCatalogVertexReader 的使用" class="title">类 org.apache.giraph.io.hcatalog.HCatalogVertexInputFormat.MultiRowHCatalogVertexReader<br>的使用</h2>
</div>
<div class="classUseContainer">没有org.apache.giraph.io.hcatalog.HCatalogVertexInputFormat.MultiRowHCatalogVertexReader的用法</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="跳过导航链接"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../../../overview-summary.html">概览</a></li>
<li><a href="../package-summary.html">程序包</a></li>
<li><a href="../../../../../../org/apache/giraph/io/hcatalog/HCatalogVertexInputFormat.MultiRowHCatalogVertexReader.html" title="org.apache.giraph.io.hcatalog中的类">类</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">树</a></li>
<li><a href="../../../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/giraph/io/hcatalog/class-use/HCatalogVertexInputFormat.MultiRowHCatalogVertexReader.html" target="_top">框架</a></li>
<li><a href="HCatalogVertexInputFormat.MultiRowHCatalogVertexReader.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2011-2013 <a href="http://www.apache.org">The Apache Software Foundation</a>. All Rights Reserved.</small></p>
</body>
</html>
| {
"content_hash": "81cd69f2c025b931f7001e49584ebd6f",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 215,
"avg_line_length": 40.84615384615385,
"alnum_prop": 0.6377903327055869,
"repo_name": "zfighter/giraph-research",
"id": "f3564b4ff819e2c397c773ee75bad141eb4ae422",
"size": "5003",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "giraph-hcatalog/target/apidocs/org/apache/giraph/io/hcatalog/class-use/HCatalogVertexInputFormat.MultiRowHCatalogVertexReader.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "78939"
},
{
"name": "Java",
"bytes": "7580660"
},
{
"name": "Shell",
"bytes": "35741"
}
],
"symlink_target": ""
} |
from unittest import TestCase
import numpy as np
from scattertext.Scalers import percentile_alphabetical
class TestPercentile_lexicographic(TestCase):
def test_percentile_lexicographic(self):
scores = [1, 1, 5, 18, 1, 3]
text = ['c', 'a', 'five', 'eighteen', 'b', 'three']
ranking = percentile_alphabetical(scores, text)
np.testing.assert_array_almost_equal(ranking, np.array([0.4, 0, 0.8, 1., 0.2, 0.6]))
| {
"content_hash": "53880650d6293b8c516e7c21314e56ea",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 86,
"avg_line_length": 30,
"alnum_prop": 0.7047619047619048,
"repo_name": "JasonKessler/scattertext",
"id": "ce191e1934a9b50bc70f69b40bc8fb56e8b0dc01",
"size": "420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scattertext/test/test_percentile_lexicographic.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1035"
},
{
"name": "HTML",
"bytes": "52028"
},
{
"name": "JavaScript",
"bytes": "497904"
},
{
"name": "Python",
"bytes": "1183530"
},
{
"name": "Shell",
"bytes": "306"
}
],
"symlink_target": ""
} |
import { connect } from 'react-redux';
import { App } from 'doca-bootstrap-theme';
import config from '../../config';
// this dynamically imports css, less and sass from the "THEME/styles"
try {
const reqCSS = require.context('doca-bootstrap-theme/styles', true, /\.css$/ig);
reqCSS.keys().forEach(reqCSS);
const reqLESS = require.context('doca-bootstrap-theme/styles', true, /\.less$/ig);
reqLESS.keys().forEach(reqLESS);
const reqSASS = require.context('doca-bootstrap-theme/styles', true, /\.scss$/ig);
reqSASS.keys().forEach(reqSASS);
} catch (e) {
// no theme styles were found
}
const mapStateToProps = state => ({
schemas: state.schemas,
config,
});
const Main = connect(
mapStateToProps
)(App);
export default Main;
| {
"content_hash": "9e688d658cf99070f87cc7ca45ca1b02",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 84,
"avg_line_length": 28.76923076923077,
"alnum_prop": 0.6911764705882353,
"repo_name": "davidbanham/notify",
"id": "c9fb02be216b6aa31b9b21b75067ab68edfd9c0f",
"size": "748",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api_documentation/src/client/main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "14442"
},
{
"name": "JavaScript",
"bytes": "11168"
},
{
"name": "Makefile",
"bytes": "993"
}
],
"symlink_target": ""
} |
package com.service.client;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.modele.Event;
import com.modele.Person;
import serilogj.Log;
import serilogj.LoggerConfiguration;
import serilogj.core.LoggingLevelSwitch;
import serilogj.events.LogEventLevel;
import serilogj.sinks.seq.SeqSink;
/**
* Rest Controller to use Comment Event
* @author Dorian Coqueron & Pierre Gaultier
* @version 1.0
*/
@RestController
@Component
@CrossOrigin
public class WebEventController {
private static final String ENCODE = "UTF-8";
private static final String EXCHANGE = "exc.event";
@Value("${spring.application.name}")
private String appName;
private static final JacksonFactory jacksonFactory = new JacksonFactory();
private static final String CLIENT_ID1 = "1059176547192-jq81i94a7dccnpklm5ph4gauim29t0dg.apps.googleusercontent.com"; //ms
private static final String CLIENT_ID2 = "784894623300-gmkq3hut99f16n220kjimotv0os7vt2e.apps.googleusercontent.com"; //java
private HttpTransport transport = new ApacheHttpTransport();
public WebEventController(){
LoggingLevelSwitch levelswitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
Log.setLogger(new LoggerConfiguration()
.writeTo(new SeqSink(Constants.getINSTANCE().getLogserverAddr(), Constants.getINSTANCE().getLogserverApikey(), null, Duration.ofSeconds(2), null, levelswitch))
.createLogger());
}
/**
* Method to find an Event by Owner with RabbitMq
* @param id
* @return
*/
@RequestMapping(value="/findByOwner", method = RequestMethod.POST)
public String getEvent(@RequestBody Person pers){
String response = new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(SerializationUtils.serialize(pers),"findByOwner");
Log
.forContext("MemberName", "findByOwner")
.forContext("Service", appName)
.information("Request : findByOwner");
return response;
}
/**
* Method to find an Event by Place with RabbitMq
* @param id
* @return
*/
@RequestMapping("/getEventByPlace")
public String getAllEvent(@RequestParam(value="id", defaultValue="1") String id){
String response = "";
try {
response = new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(id.getBytes(ENCODE),"getEventByPlace");
} catch (UnsupportedEncodingException e) {
Log
.forContext("MemberName", "getEventByPlace")
.forContext("Service", appName)
.error(e,"{date} UnsupportedEncodingException");
}
Log
.forContext("MemberName", "getEventByPlace")
.forContext("Service", appName)
.forContext("id", id)
.information("Request : getEventByPlace");
return response;
}
/**
* Method to save an event with RabbitMq
* @param id
* @return
* @throws ParseException
*/
@RequestMapping(value = "/saveEvent",method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String updateEvent(@RequestParam Map<String, String> body){
ObjectMapper mapper = new ObjectMapper();
Event event = null;
try {
event = mapper.readValue((String) body.get("event"),Event.class);
} catch (IOException e1) {
Log
.forContext("MemberName", "saveEvent")
.forContext("Service", appName)
.error(e1," IOException");
}
Log
.forContext("MemberName", "saveEvent")
.forContext("Service", appName)
.forContext("event", body.get("event"))
.information("Request : saveEvent");
String idTokenString = body.get("tokenid");
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jacksonFactory)
.setAudience(Arrays.asList(CLIENT_ID1, CLIENT_ID2))
.build();
GoogleIdToken idToken = null;
try {
idToken = verifier.verify(idTokenString);
} catch (GeneralSecurityException | IOException e) {
Log
.forContext("MemberName", "getAllPerson")
.forContext("Service", appName)
.error(e,"Exception");
}
if (idToken != null) {
Payload payload = idToken.getPayload();
String userId = payload.getSubject();
String email = payload.getEmail();
String name = (String) payload.get("name");
Log
.forContext("id", idTokenString)
.forContext("email", email)
.forContext("userId", userId)
.forContext("name", name)
.forContext("Service", appName)
.information("User Connection");
new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(SerializationUtils.serialize(event),"saveEvent");
return "{\"response\":\"success\"}";
} else {
Log
.forContext("Service", appName)
.information("Invalid Token");
return "{\"response\":\"error\"}";
}
}
/**
* Method to find all Events with RabbitMq
* @param id
* @return
*/
@RequestMapping("/getAllEvent")
public String findAllEvent(@RequestParam(value="id", defaultValue="1") String id){
String response ="";
try {
response = new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(id.getBytes(ENCODE), "getAllEvent");
} catch (UnsupportedEncodingException e) {
Log
.forContext("MemberName", "getAllEvent")
.forContext("Service", appName)
.error(e," UnsupportedEncodingException");
}
Log
.forContext("MemberName", "getAllEvent")
.forContext("Service", appName)
.information("Request : getAllEvent");
return response;
}
}
| {
"content_hash": "9730481c71e54fdf1c89ccc4db63a46b",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 163,
"avg_line_length": 34.93617021276596,
"alnum_prop": 0.7270097442143727,
"repo_name": "Miosoky/PepSIIrup-2017",
"id": "61d1d36da62a3117d3b29559439c08c087c8763b",
"size": "6568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com.SII.ClientService/src/main/java/com/service/client/WebEventController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "99203"
},
{
"name": "Shell",
"bytes": "270"
}
],
"symlink_target": ""
} |
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Marker } from '../models/marker';
import { Coordinates } from '../models/coordinates';
import * as L from 'leaflet';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
@Input() set markers(markers: Marker[]){
this._markers = markers;
this.setMarkersOnMap();
};
get markers(){
return this._markers;
}
@Input() width: string;
@Output() markerDragged = new EventEmitter<Marker>();
options: L.MapOptions;
map: L.Map;
markerLayerGroup: L.LayerGroup;
private _markers: Marker[];
constructor() {
}
ngOnInit() {
const wmsUrlZh = 'https://www.gis.stadt-zuerich.ch/maps/services/wms/WMS-ZH-STZH-OGD/MapServer/WMSServer?';
const attribution = 'Maps: <a href="https://www.stadt-zuerich.ch/portal/de/index/ogd.html" target="_blank">Open Data Zürich</a>';
this.markerLayerGroup = L.layerGroup([]);
this.options = {
layers: [
L.tileLayer.wms(wmsUrlZh, {
layers: 'Luftbild_2013',
format: 'image/png',
maxZoom: 28,
tileSize: 128,
attribution: attribution}),
this.markerLayerGroup
],
zoom: 14,
center: L.latLng({ lat: 47.377744, lng: 8.535698 })
};
(this.options.layers[0] as L.TileLayer.WMS).setParams(<any>{width: 256, height: 256 });
}
onMapReady(map: L.Map) {
this.map = map;
this.setMarkersOnMap();
}
setMarkersOnMap() {
if (!this.markers || !this.map) {
return;
}
this.markerLayerGroup.clearLayers();
this.updateMapPosition();
for (const ourMarker of this.markers){
const leafletMarker = L.marker([ourMarker.coordinates.latitude, ourMarker.coordinates.longitude], {
icon: L.icon(
{ iconSize: [25, 41], // size of the icon
iconAnchor: [12, 41], // point of the icon which will correspond to marker's location
popupAnchor: [0, -45],
iconUrl: 'assets/marker-icon.png',
shadowUrl: 'assets/marker-shadow.png' }),
draggable: ourMarker.draggable
});
this.markerLayerGroup.addLayer(leafletMarker);
if (ourMarker.title && ourMarker.url) {
if(ourMarker.imagesrc) leafletMarker.bindPopup(`<a href="${ourMarker.url}">${ourMarker.title} <br/> <img src="${ourMarker.imagesrc}" width="100px"/></a>`);
else leafletMarker.bindPopup(`<a href="${ourMarker.url}">${ourMarker.title}</a>`);
}
if (ourMarker.draggable) {
leafletMarker.on('drag', (e) => {
const position = leafletMarker.getLatLng();
ourMarker.coordinates = { latitude: position.lat, longitude: position.lng};
this.markerDragged.emit(ourMarker);
});
}
}
}
updateMapPosition() {
if (this.markers.length > 1) {
let bounds = new L.LatLng(this.markers[0].coordinates.latitude, this.markers[0].coordinates.longitude).toBounds(0);
for (const marker of this.markers){
bounds = bounds.extend(new L.LatLng(marker.coordinates.latitude, marker.coordinates.longitude));
}
this.map.flyToBounds(bounds);
} else if (this.markers.length === 1) {
const coords = new L.LatLng(this.markers[0].coordinates.latitude, this.markers[0].coordinates.longitude);
this.map.flyTo(coords, 15);
}
}
}
| {
"content_hash": "a6623097d71d75b61bf6c088b60dd399",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 163,
"avg_line_length": 34.74,
"alnum_prop": 0.6243523316062176,
"repo_name": "rsalzer/bankenstadt",
"id": "303b968f85b30bc791f54e796717469367d7ae40",
"size": "3475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/app/map/map.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "172"
},
{
"name": "HTML",
"bytes": "8427"
},
{
"name": "JavaScript",
"bytes": "57620"
},
{
"name": "TypeScript",
"bytes": "41884"
}
],
"symlink_target": ""
} |
.. _ml2_ovn_devstack:
=========================
Testing OVN with DevStack
=========================
This document describes how to test OpenStack with OVN using DevStack. We will
start by describing how to test on a single host.
Single Node Test Environment
----------------------------
1. Create a test system.
It's best to use a throwaway dev system for running DevStack. Your best bet is
to use either CentOS 8 or the latest Ubuntu LTS (18.04, Bionic).
2. Create the ``stack`` user.
::
$ git clone https://opendev.org/openstack/devstack.git
$ sudo ./devstack/tools/create-stack-user.sh
3. Switch to the ``stack`` user and clone DevStack and Neutron.
::
$ sudo su - stack
$ git clone https://opendev.org/openstack/devstack.git
$ git clone https://opendev.org/openstack/neutron.git
4. Configure DevStack to use the OVN driver.
OVN driver comes with a sample DevStack configuration file you can start
with. For example, you may want to set some values for the various PASSWORD
variables in that file so DevStack doesn't have to prompt you for them. Feel
free to edit it if you'd like, but it should work as-is.
::
$ cd devstack
$ cp ../neutron/devstack/ovn-local.conf.sample local.conf
5. Run DevStack.
This is going to take a while. It installs a bunch of packages, clones a bunch
of git repos, and installs everything from these git repos.
::
$ ./stack.sh
Once DevStack completes successfully, you should see output that looks
something like this::
This is your host IP address: 172.16.189.6
This is your host IPv6 address: ::1
Horizon is now available at http://172.16.189.6/dashboard
Keystone is serving at http://172.16.189.6/identity/
The default users are: admin and demo
The password: password
2017-03-09 15:10:54.117 | stack.sh completed in 2110 seconds.
Environment Variables
---------------------
Once DevStack finishes successfully, we're ready to start interacting with
OpenStack APIs. OpenStack provides a set of command line tools for interacting
with these APIs. DevStack provides a file you can source to set up the right
environment variables to make the OpenStack command line tools work.
::
$ . openrc
If you're curious what environment variables are set, they generally start with
an OS prefix::
$ env | grep OS
OS_REGION_NAME=RegionOne
OS_IDENTITY_API_VERSION=2.0
OS_PASSWORD=password
OS_AUTH_URL=http://192.168.122.8:5000/v2.0
OS_USERNAME=demo
OS_TENANT_NAME=demo
OS_VOLUME_API_VERSION=2
OS_CACERT=/opt/stack/data/CA/int-ca/ca-chain.pem
OS_NO_CACHE=1
Default Network Configuration
-----------------------------
By default, DevStack creates networks called ``private`` and ``public``.
Run the following command to see the existing networks::
$ openstack network list
+--------------------------------------+---------+----------------------------------------------------------------------------+
| ID | Name | Subnets |
+--------------------------------------+---------+----------------------------------------------------------------------------+
| 40080dad-0064-480a-b1b0-592ae51c1471 | private | 5ff81545-7939-4ae0-8365-1658d45fa85c, da34f952-3bfc-45bb-b062-d2d973c1a751 |
| 7ec986dd-aae4-40b5-86cf-8668feeeab67 | public | 60d0c146-a29b-4cd3-bd90-3745603b1a4b, f010c309-09be-4af2-80d6-e6af9c78bae7 |
+--------------------------------------+---------+----------------------------------------------------------------------------+
A Neutron network is implemented as an OVN logical switch. OVN driver
creates logical switches with a name in the format neutron-<network UUID>.
We can use ``ovn-nbctl`` to list the configured logical switches and see that
their names correlate with the output from ``openstack network list``::
$ ovn-nbctl ls-list
71206f5c-b0e6-49ce-b572-eb2e964b2c4e (neutron-40080dad-0064-480a-b1b0-592ae51c1471)
8d8270e7-fd51-416f-ae85-16565200b8a4 (neutron-7ec986dd-aae4-40b5-86cf-8668feeeab67)
$ ovn-nbctl get Logical_Switch neutron-40080dad-0064-480a-b1b0-592ae51c1471 external_ids
{"neutron:network_name"=private}
Booting VMs
-----------
In this section we'll go through the steps to create two VMs that have a
virtual NIC attached to the ``private`` Neutron network.
DevStack uses libvirt as the Nova backend by default. If KVM is available, it
will be used. Otherwise, it will just run qemu emulated guests. This is
perfectly fine for our testing, as we only need these VMs to be able to send
and receive a small amount of traffic so performance is not very important.
1. Get the Network UUID.
Start by getting the UUID for the ``private`` network from the output of
``openstack network list`` from earlier and save it off::
$ PRIVATE_NET_ID=$(openstack network show private -c id -f value)
2. Create an SSH keypair.
Next create an SSH keypair in Nova. Later, when we boot a VM, we'll ask that
the public key be put in the VM so we can SSH into it.
::
$ openstack keypair create demo > id_rsa_demo
$ chmod 600 id_rsa_demo
3. Choose a flavor.
We need minimal resources for these test VMs, so the ``m1.nano`` flavor is
sufficient.
::
$ openstack flavor list
+----+-----------+-------+------+-----------+-------+-----------+
| ID | Name | RAM | Disk | Ephemeral | VCPUs | Is Public |
+----+-----------+-------+------+-----------+-------+-----------+
| 1 | m1.tiny | 512 | 1 | 0 | 1 | True |
| 2 | m1.small | 2048 | 20 | 0 | 1 | True |
| 3 | m1.medium | 4096 | 40 | 0 | 2 | True |
| 4 | m1.large | 8192 | 80 | 0 | 4 | True |
| 42 | m1.nano | 64 | 0 | 0 | 1 | True |
| 5 | m1.xlarge | 16384 | 160 | 0 | 8 | True |
| 84 | m1.micro | 128 | 0 | 0 | 1 | True |
| c1 | cirros256 | 256 | 0 | 0 | 1 | True |
| d1 | ds512M | 512 | 5 | 0 | 1 | True |
| d2 | ds1G | 1024 | 10 | 0 | 1 | True |
| d3 | ds2G | 2048 | 10 | 0 | 2 | True |
| d4 | ds4G | 4096 | 20 | 0 | 4 | True |
+----+-----------+-------+------+-----------+-------+-----------+
$ FLAVOR_ID=$(openstack flavor show m1.nano -c id -f value)
4. Choose an image.
DevStack imports the CirrOS image by default, which is perfect for our testing.
It's a very small test image.
::
$ openstack image list
+--------------------------------------+--------------------------+--------+
| ID | Name | Status |
+--------------------------------------+--------------------------+--------+
| 849a8db2-3754-4cf6-9271-491fa4ff7195 | cirros-0.3.5-x86_64-disk | active |
+--------------------------------------+--------------------------+--------+
$ IMAGE_ID=$(openstack image list -c ID -f value)
5. Setup a security rule so that we can access the VMs we will boot up next.
By default, DevStack does not allow users to access VMs, to enable that, we
will need to add a rule. We will allow both ICMP and SSH.
::
$ openstack security group rule create --ingress --ethertype IPv4 --dst-port 22 --protocol tcp default
$ openstack security group rule create --ingress --ethertype IPv4 --protocol ICMP default
$ openstack security group rule list
+--------------------------------------+-------------+-----------+------------+--------------------------------------+--------------------------------------+
| ID | IP Protocol | IP Range | Port Range | Remote Security Group | Security Group |
+--------------------------------------+-------------+-----------+------------+--------------------------------------+--------------------------------------+
...
| ade97198-db44-429e-9b30-24693d86d9b1 | tcp | 0.0.0.0/0 | 22:22 | None | a47b14da-5607-404a-8de4-3a0f1ad3649c |
| d0861a98-f90e-4d1a-abfb-827b416bc2f6 | icmp | 0.0.0.0/0 | | None | a47b14da-5607-404a-8de4-3a0f1ad3649c |
...
+--------------------------------------+-------------+-----------+------------+--------------------------------------+--------------------------------------+
6. Boot some VMs.
Now we will boot two VMs. We'll name them ``test1`` and ``test2``.
::
$ openstack server create --nic net-id=$PRIVATE_NET_ID --flavor $FLAVOR_ID --image $IMAGE_ID --key-name demo test1
+-----------------------------+-----------------------------------------------------------------+
| Field | Value |
+-----------------------------+-----------------------------------------------------------------+
| OS-DCF:diskConfig | MANUAL |
| OS-EXT-AZ:availability_zone | |
| OS-EXT-STS:power_state | NOSTATE |
| OS-EXT-STS:task_state | scheduling |
| OS-EXT-STS:vm_state | building |
| OS-SRV-USG:launched_at | None |
| OS-SRV-USG:terminated_at | None |
| accessIPv4 | |
| accessIPv6 | |
| addresses | |
| adminPass | BzAWWA6byGP6 |
| config_drive | |
| created | 2017-03-09T16:56:08Z |
| flavor | m1.nano (42) |
| hostId | |
| id | d8b8084e-58ff-44f4-b029-a57e7ef6ba61 |
| image | cirros-0.3.5-x86_64-disk (849a8db2-3754-4cf6-9271-491fa4ff7195) |
| key_name | demo |
| name | test1 |
| progress | 0 |
| project_id | b6522570f7344c06b1f24303abf3c479 |
| properties | |
| security_groups | name='default' |
| status | BUILD |
| updated | 2017-03-09T16:56:08Z |
| user_id | c68f77f1d85e43eb9e5176380a68ac1f |
| volumes_attached | |
+-----------------------------+-----------------------------------------------------------------+
$ openstack server create --nic net-id=$PRIVATE_NET_ID --flavor $FLAVOR_ID --image $IMAGE_ID --key-name demo test2
+-----------------------------+-----------------------------------------------------------------+
| Field | Value |
+-----------------------------+-----------------------------------------------------------------+
| OS-DCF:diskConfig | MANUAL |
| OS-EXT-AZ:availability_zone | |
| OS-EXT-STS:power_state | NOSTATE |
| OS-EXT-STS:task_state | scheduling |
| OS-EXT-STS:vm_state | building |
| OS-SRV-USG:launched_at | None |
| OS-SRV-USG:terminated_at | None |
| accessIPv4 | |
| accessIPv6 | |
| addresses | |
| adminPass | YB8dmt5v88JV |
| config_drive | |
| created | 2017-03-09T16:56:50Z |
| flavor | m1.nano (42) |
| hostId | |
| id | 170d4f37-9299-4a08-b48b-2b90fce8e09b |
| image | cirros-0.3.5-x86_64-disk (849a8db2-3754-4cf6-9271-491fa4ff7195) |
| key_name | demo |
| name | test2 |
| progress | 0 |
| project_id | b6522570f7344c06b1f24303abf3c479 |
| properties | |
| security_groups | name='default' |
| status | BUILD |
| updated | 2017-03-09T16:56:51Z |
| user_id | c68f77f1d85e43eb9e5176380a68ac1f |
| volumes_attached | |
+-----------------------------+-----------------------------------------------------------------+
Once both VMs have been started, they will have a status of ``ACTIVE``::
$ openstack server list
+--------------------------------------+-------+--------+---------------------------------------------------------+--------------------------+
| ID | Name | Status | Networks | Image Name |
+--------------------------------------+-------+--------+---------------------------------------------------------+--------------------------+
| 170d4f37-9299-4a08-b48b-2b90fce8e09b | test2 | ACTIVE | private=fd5d:9d1b:457c:0:f816:3eff:fe24:49df, 10.0.0.3 | cirros-0.3.5-x86_64-disk |
| d8b8084e-58ff-44f4-b029-a57e7ef6ba61 | test1 | ACTIVE | private=fd5d:9d1b:457c:0:f816:3eff:fe3f:953d, 10.0.0.10 | cirros-0.3.5-x86_64-disk |
+--------------------------------------+-------+--------+---------------------------------------------------------+--------------------------+
Our two VMs have addresses of ``10.0.0.3`` and ``10.0.0.10``. If we list
Neutron ports, there are two new ports with these addresses associated
with them::
$ openstack port list
+--------------------------------------+------+-------------------+-----------------------------------------------------------------------------------------------------+--------+
| ID | Name | MAC Address | Fixed IP Addresses | Status |
+--------------------------------------+------+-------------------+-----------------------------------------------------------------------------------------------------+--------+
...
| 97c970b0-485d-47ec-868d-783c2f7acde3 | | fa:16:3e:3f:95:3d | ip_address='10.0.0.10', subnet_id='da34f952-3bfc-45bb-b062-d2d973c1a751' | ACTIVE |
| | | | ip_address='fd5d:9d1b:457c:0:f816:3eff:fe3f:953d', subnet_id='5ff81545-7939-4ae0-8365-1658d45fa85c' | |
| e003044d-334a-4de3-96d9-35b2d2280454 | | fa:16:3e:24:49:df | ip_address='10.0.0.3', subnet_id='da34f952-3bfc-45bb-b062-d2d973c1a751' | ACTIVE |
| | | | ip_address='fd5d:9d1b:457c:0:f816:3eff:fe24:49df', subnet_id='5ff81545-7939-4ae0-8365-1658d45fa85c' | |
...
+--------------------------------------+------+-------------------+-----------------------------------------------------------------------------------------------------+--------+
Now we can look at OVN using ``ovn-nbctl`` to see the logical switch ports
that were created for these two Neutron ports. The first part of the output
is the OVN logical switch port UUID. The second part in parentheses is the
logical switch port name. Neutron sets the logical switch port name equal to
the Neutron port ID.
::
$ ovn-nbctl lsp-list neutron-$PRIVATE_NET_ID
...
fde1744b-e03b-46b7-b181-abddcbe60bf2 (97c970b0-485d-47ec-868d-783c2f7acde3)
7ce284a8-a48a-42f5-bf84-b2bca62cd0fe (e003044d-334a-4de3-96d9-35b2d2280454)
...
These two ports correspond to the two VMs we created.
VM Connectivity
---------------
We can connect to our VMs by associating a floating IP address from the public
network.
::
$ TEST1_PORT_ID=$(openstack port list --server test1 -c id -f value)
$ openstack floating ip create --port $TEST1_PORT_ID public
+---------------------+--------------------------------------+
| Field | Value |
+---------------------+--------------------------------------+
| created_at | 2017-03-09T18:58:12Z |
| description | |
| fixed_ip_address | 10.0.0.10 |
| floating_ip_address | 172.24.4.8 |
| floating_network_id | 7ec986dd-aae4-40b5-86cf-8668feeeab67 |
| id | 24ff0799-5a72-4a5b-abc0-58b301c9aee5 |
| name | None |
| port_id | 97c970b0-485d-47ec-868d-783c2f7acde3 |
| project_id | b6522570f7344c06b1f24303abf3c479 |
| revision_number | 1 |
| router_id | ee51adeb-0dd8-4da0-ab6f-7ce60e00e7b0 |
| status | DOWN |
| updated_at | 2017-03-09T18:58:12Z |
+---------------------+--------------------------------------+
Devstack does not wire up the public network by default so we must do
that before connecting to this floating IP address.
::
$ sudo ip link set br-ex up
$ sudo ip route add 172.24.4.0/24 dev br-ex
$ sudo ip addr add 172.24.4.1/24 dev br-ex
Now you should be able to connect to the VM via its floating IP address.
First, ping the address.
::
$ ping -c 1 172.24.4.8
PING 172.24.4.8 (172.24.4.8) 56(84) bytes of data.
64 bytes from 172.24.4.8: icmp_seq=1 ttl=63 time=0.823 ms
--- 172.24.4.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.823/0.823/0.823/0.000 ms
Now SSH to the VM::
$ ssh -i id_rsa_demo [email protected] hostname
test1
Adding Another Compute Node
---------------------------
After completing the earlier instructions for setting up devstack, you can use
a second VM to emulate an additional compute node. This is important for OVN
testing as it exercises the tunnels created by OVN between the hypervisors.
Just as before, create a throwaway VM but make sure that this VM has a
different host name. Having same host name for both VMs will confuse Nova and
will not produce two hypervisors when you query nova hypervisor list later.
Once the VM is setup, create the ``stack`` user::
$ git clone https://opendev.org/openstack/devstack.git
$ sudo ./devstack/tools/create-stack-user.sh
Switch to the ``stack`` user and clone DevStack and neutron::
$ sudo su - stack
$ git clone https://opendev.org/openstack/devstack.git
$ git clone https://opendev.org/openstack/neutron.git
OVN comes with another sample configuration file that can be used
for this::
$ cd devstack
$ cp ../neutron/devstack/ovn-compute-local.conf.sample local.conf
You must set SERVICE_HOST in local.conf. The value should be the IP address of
the main DevStack host. You must also set HOST_IP to the IP address of this
new host. See the text in the sample configuration file for more
information. Once that is complete, run DevStack::
$ cd devstack
$ ./stack.sh
This should complete in less time than before, as it's only running a single
OpenStack service (nova-compute) along with OVN (ovn-controller, ovs-vswitchd,
ovsdb-server). The final output will look something like this::
This is your host IP address: 172.16.189.30
This is your host IPv6 address: ::1
2017-03-09 18:39:27.058 | stack.sh completed in 1149 seconds.
Now go back to your main DevStack host. You can use admin credentials to
verify that the additional hypervisor has been added to the deployment::
$ cd devstack
$ . openrc admin
$ ./tools/discover_hosts.sh
$ openstack hypervisor list
+----+------------------------+-----------------+---------------+-------+
| ID | Hypervisor Hostname | Hypervisor Type | Host IP | State |
+----+------------------------+-----------------+---------------+-------+
| 1 | centos7-ovn-devstack | QEMU | 172.16.189.6 | up |
| 2 | centos7-ovn-devstack-2 | QEMU | 172.16.189.30 | up |
+----+------------------------+-----------------+---------------+-------+
You can also look at OVN and OVS to see that the second host has shown up. For
example, there will be a second entry in the Chassis table of the
OVN_Southbound database. You can use the ``ovn-sbctl`` utility to list
chassis, their configuration, and the ports bound to each of them::
$ ovn-sbctl show
Chassis "ddc8991a-d838-4758-8d15-71032da9d062"
hostname: "centos7-ovn-devstack"
Encap vxlan
ip: "172.16.189.6"
options: {csum="true"}
Encap geneve
ip: "172.16.189.6"
options: {csum="true"}
Port_Binding "97c970b0-485d-47ec-868d-783c2f7acde3"
Port_Binding "e003044d-334a-4de3-96d9-35b2d2280454"
Port_Binding "cr-lrp-08d1f28d-cc39-4397-b12b-7124080899a1"
Chassis "b194d07e-0733-4405-b795-63b172b722fd"
hostname: "centos7-ovn-devstack-2.os1.phx2.redhat.com"
Encap geneve
ip: "172.16.189.30"
options: {csum="true"}
Encap vxlan
ip: "172.16.189.30"
options: {csum="true"}
You can also see a tunnel created to the other compute node::
$ ovs-vsctl show
...
Bridge br-int
fail_mode: secure
...
Port "ovn-b194d0-0"
Interface "ovn-b194d0-0"
type: geneve
options: {csum="true", key=flow, remote_ip="172.16.189.30"}
...
...
Provider Networks
-----------------
Neutron has a "provider networks" API extension that lets you specify
some additional attributes on a network. These attributes let you
map a Neutron network to a physical network in your environment.
The OVN ML2 driver is adding support for this API extension. It currently
supports "flat" and "vlan" networks.
Here is how you can test it:
First you must create an OVS bridge that provides connectivity to the
provider network on every host running ovn-controller. For trivial
testing this could just be a dummy bridge. In a real environment, you
would want to add a local network interface to the bridge, as well.
::
$ ovs-vsctl add-br br-provider
ovn-controller on each host must be configured with a mapping between
a network name and the bridge that provides connectivity to that network.
In this case we'll create a mapping from the network name "providernet"
to the bridge 'br-provider".
::
$ ovs-vsctl set open . \
external-ids:ovn-bridge-mappings=providernet:br-provider
If you want to enable this chassis to host a gateway router for
external connectivity, then set ovn-cms-options to enable-chassis-as-gw.
::
$ ovs-vsctl set open . \
external-ids:ovn-cms-options="enable-chassis-as-gw"
Now create a Neutron provider network.
::
$ openstack network create provider --share \
--provider-physical-network providernet \
--provider-network-type flat
Alternatively, you can define connectivity to a VLAN instead of a flat network:
::
$ openstack network create provider-101 --share \
--provider-physical-network providernet \
--provider-network-type vlan
--provider-segment 101
Observe that the OVN ML2 driver created a special logical switch port of type
localnet on the logical switch to model the connection to the physical network.
::
$ ovn-nbctl show
...
switch 5bbccbbd-f5ca-411b-bad9-01095d6f1316 (neutron-729dbbee-db84-4a3d-afc3-82c0b3701074)
port provnet-729dbbee-db84-4a3d-afc3-82c0b3701074
addresses: ["unknown"]
...
$ ovn-nbctl lsp-get-type provnet-729dbbee-db84-4a3d-afc3-82c0b3701074
localnet
$ ovn-nbctl lsp-get-options provnet-729dbbee-db84-4a3d-afc3-82c0b3701074
network_name=providernet
If VLAN is used, there will be a VLAN tag shown on the localnet port as well.
Finally, create a Neutron port on the provider network.
::
$ openstack port create --network provider myport
or if you followed the VLAN example, it would be:
::
$ openstack port create --network provider-101 myport
Skydive
-------
`Skydive <https://github.com/skydive-project/skydive>`_ is an open source
real-time network topology and protocols analyzer. It aims to provide a
comprehensive way of understanding what is happening in the network
infrastructure. Skydive works by utilizing agents to collect host-local
information, and sending this information to a central agent for
further analysis. It utilizes elasticsearch to store the data.
To enable Skydive support with OVN and devstack, enable it on the control
and compute nodes.
On the control node, enable it as follows:
::
enable_plugin skydive https://github.com/skydive-project/skydive.git
enable_service skydive-analyzer
On the compute nodes, enable it as follows:
::
enable_plugin skydive https://github.com/skydive-project/skydive.git
enable_service skydive-agent
Troubleshooting
---------------
If you run into any problems, take a look at our :doc:`/admin/ovn/troubleshooting`
page.
Additional Resources
--------------------
See the documentation and other references linked
from the :doc:`/admin/ovn/ovn` page.
| {
"content_hash": "3af5e976090eade2f5554f91bfdc2bd8",
"timestamp": "",
"source": "github",
"line_count": 601,
"max_line_length": 182,
"avg_line_length": 46.910149750415975,
"alnum_prop": 0.47394743376015325,
"repo_name": "mahak/neutron",
"id": "80f5b01b19c6111dba028b865607afef675382a1",
"size": "28193",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/source/contributor/testing/ml2_ovn_devstack.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jinja",
"bytes": "2773"
},
{
"name": "Mako",
"bytes": "1047"
},
{
"name": "Python",
"bytes": "15942116"
},
{
"name": "Ruby",
"bytes": "1257"
},
{
"name": "Shell",
"bytes": "83270"
}
],
"symlink_target": ""
} |
package org.apache.solr.common.params;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.util.StrUtils;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** SolrParams hold request parameters.
*
*
*/
public abstract class SolrParams implements Serializable {
/** returns the String value of a param, or null if not set */
public abstract String get(String param);
/** returns an array of the String values of a param, or null if none */
public abstract String[] getParams(String param);
/** returns an Iterator over the parameter names */
public abstract Iterator<String> getParameterNamesIterator();
/** returns the value of the param, or def if not set */
public String get(String param, String def) {
String val = get(param);
return val==null ? def : val;
}
/** returns a RequiredSolrParams wrapping this */
public RequiredSolrParams required()
{
// TODO? should we want to stash a reference?
return new RequiredSolrParams(this);
}
protected String fpname(String field, String param) {
return "f."+field+'.'+param;
}
/** returns the String value of the field parameter, "f.field.param", or
* the value for "param" if that is not set.
*/
public String getFieldParam(String field, String param) {
String val = get(fpname(field,param));
return val!=null ? val : get(param);
}
/** returns the String value of the field parameter, "f.field.param", or
* the value for "param" if that is not set. If that is not set, def
*/
public String getFieldParam(String field, String param, String def) {
String val = get(fpname(field,param));
return val!=null ? val : get(param, def);
}
/** returns the String values of the field parameter, "f.field.param", or
* the values for "param" if that is not set.
*/
public String[] getFieldParams(String field, String param) {
String[] val = getParams(fpname(field,param));
return val!=null ? val : getParams(param);
}
/** Returns the Boolean value of the param, or null if not set */
public Boolean getBool(String param) {
String val = get(param);
return val==null ? null : StrUtils.parseBool(val);
}
/** Returns the boolean value of the param, or def if not set */
public boolean getBool(String param, boolean def) {
String val = get(param);
return val==null ? def : StrUtils.parseBool(val);
}
/** Returns the Boolean value of the field param,
or the value for param, or null if neither is set. */
public Boolean getFieldBool(String field, String param) {
String val = getFieldParam(field, param);
return val==null ? null : StrUtils.parseBool(val);
}
/** Returns the boolean value of the field param,
or the value for param, or def if neither is set. */
public boolean getFieldBool(String field, String param, boolean def) {
String val = getFieldParam(field, param);
return val==null ? def : StrUtils.parseBool(val);
}
/** Returns the Integer value of the param, or null if not set */
public Integer getInt(String param) {
String val = get(param);
try {
return val==null ? null : Integer.valueOf(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the Long value of the param, or null if not set */
public Long getLong(String param, Long def) {
String val = get(param);
try {
return val== null ? def : Long.parseLong(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the int value of the param, or def if not set */
public int getInt(String param, int def) {
String val = get(param);
try {
return val==null ? def : Integer.parseInt(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the Long value of the param, or null if not set */
public Long getLong(String param) {
String val = get(param);
try {
return val == null ? null : Long.valueOf(val);
} catch (Exception ex) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex);
}
}
/** Returns the long value of the param, or def if not set */
public long getLong(String param, long def) {
String val = get(param);
try {
return val == null ? def : Long.parseLong(val);
} catch (Exception ex) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex);
}
}
/**
* @return The int value of the field param, or the value for param
* or <code>null</code> if neither is set.
**/
public Integer getFieldInt(String field, String param) {
String val = getFieldParam(field, param);
try {
return val==null ? null : Integer.valueOf(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the int value of the field param,
or the value for param, or def if neither is set. */
public int getFieldInt(String field, String param, int def) {
String val = getFieldParam(field, param);
try {
return val==null ? def : Integer.parseInt(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the Float value of the param, or null if not set */
public Float getFloat(String param) {
String val = get(param);
try {
return val==null ? null : Float.valueOf(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the float value of the param, or def if not set */
public float getFloat(String param, float def) {
String val = get(param);
try {
return val==null ? def : Float.parseFloat(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the Float value of the param, or null if not set */
public Double getDouble(String param) {
String val = get(param);
try {
return val==null ? null : Double.valueOf(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the float value of the param, or def if not set */
public double getDouble(String param, double def) {
String val = get(param);
try {
return val==null ? def : Double.parseDouble(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the float value of the field param. */
public Float getFieldFloat(String field, String param) {
String val = getFieldParam(field, param);
try {
return val==null ? null : Float.valueOf(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the float value of the field param,
or the value for param, or def if neither is set. */
public float getFieldFloat(String field, String param, float def) {
String val = getFieldParam(field, param);
try {
return val==null ? def : Float.parseFloat(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the float value of the field param. */
public Double getFieldDouble(String field, String param) {
String val = getFieldParam(field, param);
try {
return val==null ? null : Double.valueOf(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
/** Returns the float value of the field param,
or the value for param, or def if neither is set. */
public double getFieldDouble(String field, String param, double def) {
String val = getFieldParam(field, param);
try {
return val==null ? def : Double.parseDouble(val);
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, ex.getMessage(), ex );
}
}
public static SolrParams wrapDefaults(SolrParams params, SolrParams defaults) {
if (params == null)
return defaults;
if (defaults == null)
return params;
return new DefaultSolrParams(params,defaults);
}
public static SolrParams wrapAppended(SolrParams params, SolrParams defaults) {
if (params == null)
return defaults;
if (defaults == null)
return params;
return AppendedSolrParams.wrapAppended(params,defaults);
}
/** Create a Map<String,String> from a NamedList given no keys are repeated */
public static Map<String,String> toMap(NamedList params) {
HashMap<String,String> map = new HashMap<>();
for (int i=0; i<params.size(); i++) {
map.put(params.getName(i), params.getVal(i).toString());
}
return map;
}
/** Create a Map<String,String[]> from a NamedList */
public static Map<String,String[]> toMultiMap(NamedList params) {
HashMap<String,String[]> map = new HashMap<>();
for (int i=0; i<params.size(); i++) {
String name = params.getName(i);
Object val = params.getVal(i);
if (val instanceof String[]) {
MultiMapSolrParams.addParam(name, (String[]) val, map);
} else if (val instanceof List) {
List l = (List) val;
String[] s = new String[l.size()];
for (int j = 0; j < l.size(); j++) {
s[j] = l.get(j) == null ? null : String.valueOf(l.get(j));
}
MultiMapSolrParams.addParam(name, s, map);
} else {
MultiMapSolrParams.addParam(name, val.toString(), map);
}
}
return map;
}
/** Create SolrParams from NamedList. */
public static SolrParams toSolrParams(NamedList params) {
// always use MultiMap for easier processing further down the chain
return new MultiMapSolrParams(toMultiMap(params));
}
/** Create filtered SolrParams. */
public SolrParams toFilteredSolrParams(List<String> names) {
NamedList<String> nl = new NamedList<>();
for (Iterator<String> it = getParameterNamesIterator(); it.hasNext();) {
final String name = it.next();
if (names.contains(name)) {
final String[] values = getParams(name);
for (String value : values) {
nl.add(name, value);
}
}
}
return toSolrParams(nl);
}
/** Convert this to a NamedList */
public NamedList<Object> toNamedList() {
final SimpleOrderedMap<Object> result = new SimpleOrderedMap<>();
for(Iterator<String> it=getParameterNamesIterator(); it.hasNext(); ) {
final String name = it.next();
final String [] values = getParams(name);
if(values.length==1) {
result.add(name,values[0]);
} else {
// currently no reason not to use the same array
result.add(name,values);
}
}
return result;
}
/**Copy all params to the given map or if the given map is null
* create a new one
*/
public Map<String, Object> getAll(Map<String, Object> sink, String... params){
if(sink == null) sink = new LinkedHashMap<>();
for (String param : params) {
String[] v = getParams(param);
if(v != null && v.length>0 ) {
if(v.length == 1) {
sink.put(param, v[0]);
} else {
sink.put(param,v);
}
}
}
return sink;
}
/** Returns this SolrParams as a properly URL encoded string, starting with {@code "?"}, if not empty. */
public String toQueryString() {
try {
final String charset = StandardCharsets.UTF_8.name();
final StringBuilder sb = new StringBuilder(128);
boolean first = true;
for (final Iterator<String> it = getParameterNamesIterator(); it.hasNext();) {
final String name = it.next(), nameEnc = URLEncoder.encode(name, charset);
for (String val : getParams(name)) {
sb.append(first ? '?' : '&').append(nameEnc).append('=').append(URLEncoder.encode(val, charset));
first = false;
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
// impossible!
throw new AssertionError(e);
}
}
/** Like {@link #toQueryString()}, but only replacing enough chars so that
* the URL may be unambiguously pasted back into a browser.
* This method can be used to properly log query parameters without
* making them unreadable.
* <p>
* Characters with a numeric value less than 32 are encoded.
* &,=,%,+,space are encoded.
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(128);
try {
boolean first=true;
for (final Iterator<String> it = getParameterNamesIterator(); it.hasNext();) {
final String name = it.next();
for (String val : getParams(name)) {
if (!first) sb.append('&');
first=false;
StrUtils.partialURLEncodeVal(sb, name);
sb.append('=');
StrUtils.partialURLEncodeVal(sb, val);
}
}
return sb.toString();
} catch (IOException e) {
// impossible!
throw new AssertionError(e);
}
}
}
| {
"content_hash": "a78f25e7c86b6a537a9b1309885b92c5",
"timestamp": "",
"source": "github",
"line_count": 427,
"max_line_length": 107,
"avg_line_length": 32.50351288056206,
"alnum_prop": 0.6433460623964262,
"repo_name": "PATRIC3/p3_solr",
"id": "0c057281fec21246f736f11604e7fa45e3dd3967",
"size": "14680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "291"
},
{
"name": "ANTLR",
"bytes": "2863"
},
{
"name": "Batchfile",
"bytes": "48067"
},
{
"name": "C++",
"bytes": "13377"
},
{
"name": "CSS",
"bytes": "239934"
},
{
"name": "Gnuplot",
"bytes": "2444"
},
{
"name": "Groovy",
"bytes": "3681"
},
{
"name": "HTML",
"bytes": "800790"
},
{
"name": "Java",
"bytes": "49075301"
},
{
"name": "JavaScript",
"bytes": "1250337"
},
{
"name": "Lex",
"bytes": "108342"
},
{
"name": "Perl",
"bytes": "86525"
},
{
"name": "Python",
"bytes": "237962"
},
{
"name": "Shell",
"bytes": "160384"
},
{
"name": "XSLT",
"bytes": "160778"
}
],
"symlink_target": ""
} |
import numpy as np
from data_prep import features, targets, features_test, targets_test
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1 / (1 + np.exp(-x))
# Use to same seed to make debugging easier
np.random.seed(42)
n_records, n_features = features.shape
last_loss = None
# Initialize weights
weights = np.random.normal(scale=1 / n_features**.5, size=n_features)
# Neural Network hyperparameters
epochs = 1000
learnrate = 0.01
for e in range(epochs):
del_w = np.zeros(weights.shape)
for x, y in zip(features.values, targets):
# Loop through all records, x is the input, y is the target
# Calculate the output
output = sigmoid(np.dot(x, weights))
# Calculate the error
error = y - output
# Calculate change in weights
del_w += error * output * (1 - output) * x
# Update weights
weights += learnrate * del_w
# Printing out the mean square error on the training set
if e % (epochs / 10) == 0:
out = sigmoid(np.dot(features, weights))
loss = np.mean((out - targets) ** 2)
if last_loss and last_loss < loss:
print("Train loss: ", loss, " WARNING - Loss Increasing")
else:
print("Train loss: ", loss)
last_loss = loss
# Calculate accuracy on test data
tes_out = sigmoid(np.dot(features_test, weights))
predictions = tes_out > 0.5
accuracy = np.mean(predictions == targets_test)
print("Prediction accuracy: {:.3f}".format(accuracy))
| {
"content_hash": "03e878bf92feb312d40d44e43e356b05",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 70,
"avg_line_length": 26.50877192982456,
"alnum_prop": 0.6293845135671741,
"repo_name": "swirlingsand/deep-learning-foundations",
"id": "ef978645f47855c9c93b2fd4bf9a212ca486889d",
"size": "1511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "play/gradient_descent_2/gradient.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1564242"
},
{
"name": "Jupyter Notebook",
"bytes": "110006555"
},
{
"name": "Python",
"bytes": "194266"
},
{
"name": "Shell",
"bytes": "195"
}
],
"symlink_target": ""
} |
from django.db import models as django_models
from waldur_core.core import models as core_models
from waldur_core.quotas import fields
from waldur_core.quotas import models as quotas_models
class GrandparentModel(
core_models.UuidMixin, quotas_models.QuotaModelMixin, core_models.DescendantMixin
):
class Quotas(quotas_models.QuotaModelMixin.Quotas):
regular_quota = fields.QuotaField()
quota_with_default_limit = fields.QuotaField(default_limit=100)
usage_aggregator_quota = fields.UsageAggregatorQuotaField(
get_children=lambda scope: ChildModel.objects.filter(parent__parent=scope),
)
limit_aggregator_quota = fields.LimitAggregatorQuotaField(
get_children=lambda scope: ChildModel.objects.filter(parent__parent=scope),
)
regular_quota = fields.QuotaLimitField(quota_field=Quotas.regular_quota)
class ParentModel(
core_models.UuidMixin, quotas_models.QuotaModelMixin, core_models.DescendantMixin
):
parent = django_models.ForeignKey(
on_delete=django_models.CASCADE, to=GrandparentModel, related_name='children'
)
class Quotas(quotas_models.QuotaModelMixin.Quotas):
counter_quota = fields.CounterQuotaField(
target_models=lambda: [ChildModel], path_to_scope='parent',
)
two_targets_counter_quota = fields.CounterQuotaField(
target_models=lambda: [ChildModel, SecondChildModel],
path_to_scope='parent',
)
delta_quota = fields.CounterQuotaField(
target_models=lambda: [ChildModel],
path_to_scope='parent',
get_delta=lambda scope: 10,
)
usage_aggregator_quota = fields.UsageAggregatorQuotaField(
get_children=lambda scope: scope.children.all(),
)
limit_aggregator_quota = fields.LimitAggregatorQuotaField(
get_children=lambda scope: scope.children.all(), default_limit=0,
)
second_usage_aggregator_quota = fields.UsageAggregatorQuotaField(
get_children=lambda scope: scope.children.all(),
child_quota_name='usage_aggregator_quota',
)
total_quota = fields.TotalQuotaField(
target_models=lambda: [SecondChildModel],
path_to_scope='parent',
target_field='size',
)
def get_parents(self):
return [self.parent]
class NonQuotaParentModel(core_models.UuidMixin, core_models.DescendantMixin):
""" Allow to make sure that quotas propagation do not fail if quota scope has parent without quotas """
pass
class ChildModel(
core_models.UuidMixin, quotas_models.QuotaModelMixin, core_models.DescendantMixin
):
parent = django_models.ForeignKey(
on_delete=django_models.CASCADE, to=ParentModel, related_name='children'
)
non_quota_parent = django_models.ForeignKey(
on_delete=django_models.CASCADE,
to=NonQuotaParentModel,
related_name='children',
blank=True,
null=True,
)
class Quotas(quotas_models.QuotaModelMixin.Quotas):
regular_quota = fields.QuotaField()
usage_aggregator_quota = (
fields.QuotaField()
) # this quota is aggregated by parent and grandparent
limit_aggregator_quota = fields.QuotaField(
default_limit=0
) # this quota is aggregated by parent and grandparent
def get_parents(self):
if self.non_quota_parent:
return [self.parent, self.non_quota_parent]
return [self.parent]
class SecondChildModel(
core_models.UuidMixin, quotas_models.QuotaModelMixin, core_models.DescendantMixin
):
parent = django_models.ForeignKey(
on_delete=django_models.CASCADE, to=ParentModel, related_name='second_children'
)
size = django_models.IntegerField(default=0)
def get_parents(self):
return [self.parent]
| {
"content_hash": "d1db74bea17e2bfc29a8b02ac188808c",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 107,
"avg_line_length": 36.22222222222222,
"alnum_prop": 0.6766359918200409,
"repo_name": "opennode/nodeconductor-assembly-waldur",
"id": "c9380b3db4da23fd573f454a6b2c078471562cc6",
"size": "3912",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/waldur_core/quotas/tests/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1624"
},
{
"name": "Python",
"bytes": "412263"
},
{
"name": "Shell",
"bytes": "2031"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<global-method-security secured-annotations="disabled"
jsr250-annotations="disabled">
</global-method-security>
<http auto-config='true' >
<intercept-url pattern="/bootstrap/**" filters="none" />
<intercept-url pattern="/common/**" filters="none" />
<intercept-url pattern="/js/**" filters="none" />
<intercept-url pattern="/jquery/**" filters="none" />
<intercept-url pattern="/login.jsp" filters="none" />
<intercept-url pattern="/about.jsp" filters="none" />
<intercept-url pattern="/403.jsp" filters="none" />
<intercept-url pattern="/404.jsp" filters="none" />
<intercept-url pattern="/error.jsp" filters="none" />
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?error=true"
default-target-url="/index.jsp"
always-use-default-target="true" />
<logout logout-success-url="/login.jsp" />
<remember-me use-secure-cookie="false" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="1" password="1" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="bob" password="bobspassword" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
| {
"content_hash": "0b9453eff261ca5e7f25c1f3308931c2",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 83,
"avg_line_length": 39.78260869565217,
"alnum_prop": 0.6737704918032786,
"repo_name": "kelvem/sshstudy",
"id": "4f8bcd24fe51c785a3ecbaa7ff6008e50639eeae",
"size": "1830",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/resources/spring/_spring-context-security-simple2.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "332537"
},
{
"name": "Java",
"bytes": "325487"
},
{
"name": "JavaScript",
"bytes": "464041"
},
{
"name": "Shell",
"bytes": "76"
}
],
"symlink_target": ""
} |
package com.paypal.cascade.akka.actor
import akka.actor.{UnhandledMessage, ActorLogging, Actor, Status}
import com.paypal.cascade.akka.mailbox.ExpiredLetter
/**
* CommonActor is intended for top-level actors that have robust error-handling, and that are responsible for
* receiving exceptions from other actors. Generally, there should only be one actor (or a small pool of actors)
* extending this trait directly.
*/
trait CommonActor extends Actor with ActorLogging {
/**
* Can be overridden in subsequent actor implementations, but `super.postRestart(reason)` should also be called
* to preserve consistent behavior
* @param reason what triggered this restart cycle
*/
override def postRestart(reason: Throwable): Unit = {
log.debug(s"Restarted actor: ${self.path}")
super.postRestart(reason)
}
}
/**
* ServiceActor returns an error response for unhandled messages and escalates the error to the supervisor
* by throwing an exception. For most child actors, this trait should be preferred.
*/
trait ServiceActor extends CommonActor {
/**
* Triggered when an actor receives a message that it doesn't recognize. In order:
*
* 1) Publishes an unhandled message to the actor system's event stream.
* 2) Replies with a [[akka.actor.Status.Failure]] message to the sender.
* 3) Throws an [[UnhandledMessageException]] for delegation to the supervisor.
*
* [[com.paypal.cascade.akka.mailbox.ExpiredLetter]] messages from an [[com.paypal.cascade.akka.mailbox.ExpiringBoundedMailbox]]
* are published to the system eventstream, similar to the dead letter stream, and are otherwise ignored.
*
* @param message The unhandled message
* @throws UnhandledMessageException The unhandled message exception.
*/
@throws[UnhandledMessageException]
override def unhandled(message: Any): Unit = {
message match {
case em: ExpiredLetter => context.system.eventStream.publish(UnhandledMessage(message, sender(), self))
case Status.Failure(t: Throwable) =>
super.unhandled(message)
log.error(s"Unhandled failure message for actor: ${self.path}, sender: ${sender()}, message: ${t.getClass}")
case _ =>
super.unhandled(message)
val ex = new UnhandledMessageException(s"Unhandled message received by actor: ${self.path}, sender: ${sender()}, message: ${message.getClass}")
sender ! Status.Failure(ex)
throw ex
}
}
}
/**
* Exception raised when an unhandled message is received by a CommonActor
* @param message what happened
*/
class UnhandledMessageException(message: String) extends ActorException(message)
/**
* Base type for custom exceptions raised within an actor
* @param message what happened
* @param cause if there was another exception that triggered this, it's here
*/
abstract class ActorException(message: String, cause: Option[Throwable] = None)
extends Exception(message, cause.orNull)
| {
"content_hash": "5fdd90d1140aeedc6178bd6d5d5658f5",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 151,
"avg_line_length": 40.916666666666664,
"alnum_prop": 0.7331975560081466,
"repo_name": "paypal/cascade",
"id": "ac8f832ccba4ee3b0d5e897b43939df431a8b295",
"size": "3537",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "akka/src/main/scala/com/paypal/cascade/akka/actor/CommonActor.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "380784"
}
],
"symlink_target": ""
} |
/**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
import com.facebook.thrift.*;
import com.facebook.thrift.annotations.*;
import com.facebook.thrift.async.*;
import com.facebook.thrift.meta_data.*;
import com.facebook.thrift.server.*;
import com.facebook.thrift.transport.*;
import com.facebook.thrift.protocol.*;
@SuppressWarnings({ "unused", "serial" })
public class MyStruct implements TBase, java.io.Serializable, Cloneable {
private static final TStruct STRUCT_DESC = new TStruct("MyStruct");
private static final TField MY_INT_FIELD_FIELD_DESC = new TField("MyIntField", TType.I64, (short)1);
private static final TField MY_STRING_FIELD_FIELD_DESC = new TField("MyStringField", TType.STRING, (short)2);
private static final TField MY_DATA_FIELD_FIELD_DESC = new TField("MyDataField", TType.STRUCT, (short)3);
private static final TField MY_ENUM_FIELD_DESC = new TField("myEnum", TType.I32, (short)4);
private static final TField MY_BOOL_FIELD_FIELD_DESC = new TField("MyBoolField", TType.BOOL, (short)5);
private static final TField MY_BYTE_FIELD_FIELD_DESC = new TField("MyByteField", TType.BYTE, (short)6);
private static final TField MY_SHORT_FIELD_FIELD_DESC = new TField("MyShortField", TType.I16, (short)7);
private static final TField MY_LONG_FIELD_FIELD_DESC = new TField("MyLongField", TType.I64, (short)8);
private static final TField MY_DOUBLE_FIELD_FIELD_DESC = new TField("MyDoubleField", TType.DOUBLE, (short)9);
private static final TField L_DOUBLE_FIELD_DESC = new TField("lDouble", TType.LIST, (short)10);
private static final TField L_SHORT_FIELD_DESC = new TField("lShort", TType.LIST, (short)11);
private static final TField L_INTEGER_FIELD_DESC = new TField("lInteger", TType.LIST, (short)12);
private static final TField L_LONG_FIELD_DESC = new TField("lLong", TType.LIST, (short)13);
private static final TField L_STRING_FIELD_DESC = new TField("lString", TType.LIST, (short)14);
private static final TField L_BOOL_FIELD_DESC = new TField("lBool", TType.LIST, (short)15);
private static final TField L_BYTE_FIELD_DESC = new TField("lByte", TType.LIST, (short)16);
private static final TField M_SHORT_STRING_FIELD_DESC = new TField("mShortString", TType.MAP, (short)17);
private static final TField M_INTEGER_STRING_FIELD_DESC = new TField("mIntegerString", TType.MAP, (short)18);
private static final TField M_STRING_MY_STRUCT_FIELD_DESC = new TField("mStringMyStruct", TType.MAP, (short)19);
private static final TField M_STRING_BOOL_FIELD_DESC = new TField("mStringBool", TType.MAP, (short)20);
private static final TField M_INTEGER_INTEGER_FIELD_DESC = new TField("mIntegerInteger", TType.MAP, (short)21);
private static final TField M_INTEGER_BOOL_FIELD_DESC = new TField("mIntegerBool", TType.MAP, (short)22);
private static final TField S_SHORT_FIELD_DESC = new TField("sShort", TType.SET, (short)23);
private static final TField S_MY_STRUCT_FIELD_DESC = new TField("sMyStruct", TType.SET, (short)24);
private static final TField S_LONG_FIELD_DESC = new TField("sLong", TType.SET, (short)25);
private static final TField S_STRING_FIELD_DESC = new TField("sString", TType.SET, (short)26);
private static final TField S_BYTE_FIELD_DESC = new TField("sByte", TType.SET, (short)27);
private static final TField M_LIST_LIST_FIELD_DESC = new TField("mListList", TType.MAP, (short)28);
public long MyIntField;
public String MyStringField;
public MyDataItem MyDataField;
/**
*
* @see MyEnum
*/
public MyEnum myEnum;
public boolean MyBoolField;
public byte MyByteField;
public short MyShortField;
public long MyLongField;
public double MyDoubleField;
public List<Double> lDouble;
public List<Short> lShort;
public List<Integer> lInteger;
public List<Long> lLong;
public List<String> lString;
public List<Boolean> lBool;
public List<Byte> lByte;
public Map<Short,String> mShortString;
public Map<Integer,String> mIntegerString;
public Map<String,MyStruct> mStringMyStruct;
public Map<String,Boolean> mStringBool;
public Map<Integer,Integer> mIntegerInteger;
public Map<Integer,Boolean> mIntegerBool;
public Set<Short> sShort;
public Set<MyStruct> sMyStruct;
public Set<Long> sLong;
public Set<String> sString;
public Set<Byte> sByte;
public Map<List<Integer>,List<Integer>> mListList;
public static final int MYINTFIELD = 1;
public static final int MYSTRINGFIELD = 2;
public static final int MYDATAFIELD = 3;
public static final int MYENUM = 4;
public static final int MYBOOLFIELD = 5;
public static final int MYBYTEFIELD = 6;
public static final int MYSHORTFIELD = 7;
public static final int MYLONGFIELD = 8;
public static final int MYDOUBLEFIELD = 9;
public static final int LDOUBLE = 10;
public static final int LSHORT = 11;
public static final int LINTEGER = 12;
public static final int LLONG = 13;
public static final int LSTRING = 14;
public static final int LBOOL = 15;
public static final int LBYTE = 16;
public static final int MSHORTSTRING = 17;
public static final int MINTEGERSTRING = 18;
public static final int MSTRINGMYSTRUCT = 19;
public static final int MSTRINGBOOL = 20;
public static final int MINTEGERINTEGER = 21;
public static final int MINTEGERBOOL = 22;
public static final int SSHORT = 23;
public static final int SMYSTRUCT = 24;
public static final int SLONG = 25;
public static final int SSTRING = 26;
public static final int SBYTE = 27;
public static final int MLISTLIST = 28;
// isset id assignments
private static final int __MYINTFIELD_ISSET_ID = 0;
private static final int __MYBOOLFIELD_ISSET_ID = 1;
private static final int __MYBYTEFIELD_ISSET_ID = 2;
private static final int __MYSHORTFIELD_ISSET_ID = 3;
private static final int __MYLONGFIELD_ISSET_ID = 4;
private static final int __MYDOUBLEFIELD_ISSET_ID = 5;
private BitSet __isset_bit_vector = new BitSet(6);
public static final Map<Integer, FieldMetaData> metaDataMap;
static {
Map<Integer, FieldMetaData> tmpMetaDataMap = new HashMap<Integer, FieldMetaData>();
tmpMetaDataMap.put(MYINTFIELD, new FieldMetaData("MyIntField", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.I64)));
tmpMetaDataMap.put(MYSTRINGFIELD, new FieldMetaData("MyStringField", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.STRING)));
tmpMetaDataMap.put(MYDATAFIELD, new FieldMetaData("MyDataField", TFieldRequirementType.DEFAULT,
new StructMetaData(TType.STRUCT, MyDataItem.class)));
tmpMetaDataMap.put(MYENUM, new FieldMetaData("myEnum", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.I32)));
tmpMetaDataMap.put(MYBOOLFIELD, new FieldMetaData("MyBoolField", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.BOOL)));
tmpMetaDataMap.put(MYBYTEFIELD, new FieldMetaData("MyByteField", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.BYTE)));
tmpMetaDataMap.put(MYSHORTFIELD, new FieldMetaData("MyShortField", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.I16)));
tmpMetaDataMap.put(MYLONGFIELD, new FieldMetaData("MyLongField", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.I64)));
tmpMetaDataMap.put(MYDOUBLEFIELD, new FieldMetaData("MyDoubleField", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.DOUBLE)));
tmpMetaDataMap.put(LDOUBLE, new FieldMetaData("lDouble", TFieldRequirementType.DEFAULT,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.DOUBLE))));
tmpMetaDataMap.put(LSHORT, new FieldMetaData("lShort", TFieldRequirementType.DEFAULT,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.I16))));
tmpMetaDataMap.put(LINTEGER, new FieldMetaData("lInteger", TFieldRequirementType.DEFAULT,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.I32))));
tmpMetaDataMap.put(LLONG, new FieldMetaData("lLong", TFieldRequirementType.DEFAULT,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.I64))));
tmpMetaDataMap.put(LSTRING, new FieldMetaData("lString", TFieldRequirementType.DEFAULT,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.STRING))));
tmpMetaDataMap.put(LBOOL, new FieldMetaData("lBool", TFieldRequirementType.DEFAULT,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.BOOL))));
tmpMetaDataMap.put(LBYTE, new FieldMetaData("lByte", TFieldRequirementType.DEFAULT,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.BYTE))));
tmpMetaDataMap.put(MSHORTSTRING, new FieldMetaData("mShortString", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.I16),
new FieldValueMetaData(TType.STRING))));
tmpMetaDataMap.put(MINTEGERSTRING, new FieldMetaData("mIntegerString", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.I32),
new FieldValueMetaData(TType.STRING))));
tmpMetaDataMap.put(MSTRINGMYSTRUCT, new FieldMetaData("mStringMyStruct", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new StructMetaData(TType.STRUCT, MyStruct.class))));
tmpMetaDataMap.put(MSTRINGBOOL, new FieldMetaData("mStringBool", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new FieldValueMetaData(TType.BOOL))));
tmpMetaDataMap.put(MINTEGERINTEGER, new FieldMetaData("mIntegerInteger", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.I32),
new FieldValueMetaData(TType.I32))));
tmpMetaDataMap.put(MINTEGERBOOL, new FieldMetaData("mIntegerBool", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.I32),
new FieldValueMetaData(TType.BOOL))));
tmpMetaDataMap.put(SSHORT, new FieldMetaData("sShort", TFieldRequirementType.DEFAULT,
new SetMetaData(TType.SET,
new FieldValueMetaData(TType.I16))));
tmpMetaDataMap.put(SMYSTRUCT, new FieldMetaData("sMyStruct", TFieldRequirementType.DEFAULT,
new SetMetaData(TType.SET,
new StructMetaData(TType.STRUCT, MyStruct.class))));
tmpMetaDataMap.put(SLONG, new FieldMetaData("sLong", TFieldRequirementType.DEFAULT,
new SetMetaData(TType.SET,
new FieldValueMetaData(TType.I64))));
tmpMetaDataMap.put(SSTRING, new FieldMetaData("sString", TFieldRequirementType.DEFAULT,
new SetMetaData(TType.SET,
new FieldValueMetaData(TType.STRING))));
tmpMetaDataMap.put(SBYTE, new FieldMetaData("sByte", TFieldRequirementType.DEFAULT,
new SetMetaData(TType.SET,
new FieldValueMetaData(TType.BYTE))));
tmpMetaDataMap.put(MLISTLIST, new FieldMetaData("mListList", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.I32)),
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.I32)))));
metaDataMap = Collections.unmodifiableMap(tmpMetaDataMap);
}
static {
FieldMetaData.addStructMetaDataMap(MyStruct.class, metaDataMap);
}
public MyStruct() {
}
public MyStruct(
long MyIntField,
String MyStringField,
MyDataItem MyDataField,
MyEnum myEnum,
boolean MyBoolField,
byte MyByteField,
short MyShortField,
long MyLongField,
double MyDoubleField,
List<Double> lDouble,
List<Short> lShort,
List<Integer> lInteger,
List<Long> lLong,
List<String> lString,
List<Boolean> lBool,
List<Byte> lByte,
Map<Short,String> mShortString,
Map<Integer,String> mIntegerString,
Map<String,MyStruct> mStringMyStruct,
Map<String,Boolean> mStringBool,
Map<Integer,Integer> mIntegerInteger,
Map<Integer,Boolean> mIntegerBool,
Set<Short> sShort,
Set<MyStruct> sMyStruct,
Set<Long> sLong,
Set<String> sString,
Set<Byte> sByte,
Map<List<Integer>,List<Integer>> mListList) {
this();
this.MyIntField = MyIntField;
setMyIntFieldIsSet(true);
this.MyStringField = MyStringField;
this.MyDataField = MyDataField;
this.myEnum = myEnum;
this.MyBoolField = MyBoolField;
setMyBoolFieldIsSet(true);
this.MyByteField = MyByteField;
setMyByteFieldIsSet(true);
this.MyShortField = MyShortField;
setMyShortFieldIsSet(true);
this.MyLongField = MyLongField;
setMyLongFieldIsSet(true);
this.MyDoubleField = MyDoubleField;
setMyDoubleFieldIsSet(true);
this.lDouble = lDouble;
this.lShort = lShort;
this.lInteger = lInteger;
this.lLong = lLong;
this.lString = lString;
this.lBool = lBool;
this.lByte = lByte;
this.mShortString = mShortString;
this.mIntegerString = mIntegerString;
this.mStringMyStruct = mStringMyStruct;
this.mStringBool = mStringBool;
this.mIntegerInteger = mIntegerInteger;
this.mIntegerBool = mIntegerBool;
this.sShort = sShort;
this.sMyStruct = sMyStruct;
this.sLong = sLong;
this.sString = sString;
this.sByte = sByte;
this.mListList = mListList;
}
public static class Builder {
private long MyIntField;
private String MyStringField;
private MyDataItem MyDataField;
private MyEnum myEnum;
private boolean MyBoolField;
private byte MyByteField;
private short MyShortField;
private long MyLongField;
private double MyDoubleField;
private List<Double> lDouble;
private List<Short> lShort;
private List<Integer> lInteger;
private List<Long> lLong;
private List<String> lString;
private List<Boolean> lBool;
private List<Byte> lByte;
private Map<Short,String> mShortString;
private Map<Integer,String> mIntegerString;
private Map<String,MyStruct> mStringMyStruct;
private Map<String,Boolean> mStringBool;
private Map<Integer,Integer> mIntegerInteger;
private Map<Integer,Boolean> mIntegerBool;
private Set<Short> sShort;
private Set<MyStruct> sMyStruct;
private Set<Long> sLong;
private Set<String> sString;
private Set<Byte> sByte;
private Map<List<Integer>,List<Integer>> mListList;
BitSet __optional_isset = new BitSet(6);
public Builder() {
}
public Builder setMyIntField(final long MyIntField) {
this.MyIntField = MyIntField;
__optional_isset.set(__MYINTFIELD_ISSET_ID, true);
return this;
}
public Builder setMyStringField(final String MyStringField) {
this.MyStringField = MyStringField;
return this;
}
public Builder setMyDataField(final MyDataItem MyDataField) {
this.MyDataField = MyDataField;
return this;
}
public Builder setMyEnum(final MyEnum myEnum) {
this.myEnum = myEnum;
return this;
}
public Builder setMyBoolField(final boolean MyBoolField) {
this.MyBoolField = MyBoolField;
__optional_isset.set(__MYBOOLFIELD_ISSET_ID, true);
return this;
}
public Builder setMyByteField(final byte MyByteField) {
this.MyByteField = MyByteField;
__optional_isset.set(__MYBYTEFIELD_ISSET_ID, true);
return this;
}
public Builder setMyShortField(final short MyShortField) {
this.MyShortField = MyShortField;
__optional_isset.set(__MYSHORTFIELD_ISSET_ID, true);
return this;
}
public Builder setMyLongField(final long MyLongField) {
this.MyLongField = MyLongField;
__optional_isset.set(__MYLONGFIELD_ISSET_ID, true);
return this;
}
public Builder setMyDoubleField(final double MyDoubleField) {
this.MyDoubleField = MyDoubleField;
__optional_isset.set(__MYDOUBLEFIELD_ISSET_ID, true);
return this;
}
public Builder setLDouble(final List<Double> lDouble) {
this.lDouble = lDouble;
return this;
}
public Builder setLShort(final List<Short> lShort) {
this.lShort = lShort;
return this;
}
public Builder setLInteger(final List<Integer> lInteger) {
this.lInteger = lInteger;
return this;
}
public Builder setLLong(final List<Long> lLong) {
this.lLong = lLong;
return this;
}
public Builder setLString(final List<String> lString) {
this.lString = lString;
return this;
}
public Builder setLBool(final List<Boolean> lBool) {
this.lBool = lBool;
return this;
}
public Builder setLByte(final List<Byte> lByte) {
this.lByte = lByte;
return this;
}
public Builder setMShortString(final Map<Short,String> mShortString) {
this.mShortString = mShortString;
return this;
}
public Builder setMIntegerString(final Map<Integer,String> mIntegerString) {
this.mIntegerString = mIntegerString;
return this;
}
public Builder setMStringMyStruct(final Map<String,MyStruct> mStringMyStruct) {
this.mStringMyStruct = mStringMyStruct;
return this;
}
public Builder setMStringBool(final Map<String,Boolean> mStringBool) {
this.mStringBool = mStringBool;
return this;
}
public Builder setMIntegerInteger(final Map<Integer,Integer> mIntegerInteger) {
this.mIntegerInteger = mIntegerInteger;
return this;
}
public Builder setMIntegerBool(final Map<Integer,Boolean> mIntegerBool) {
this.mIntegerBool = mIntegerBool;
return this;
}
public Builder setSShort(final Set<Short> sShort) {
this.sShort = sShort;
return this;
}
public Builder setSMyStruct(final Set<MyStruct> sMyStruct) {
this.sMyStruct = sMyStruct;
return this;
}
public Builder setSLong(final Set<Long> sLong) {
this.sLong = sLong;
return this;
}
public Builder setSString(final Set<String> sString) {
this.sString = sString;
return this;
}
public Builder setSByte(final Set<Byte> sByte) {
this.sByte = sByte;
return this;
}
public Builder setMListList(final Map<List<Integer>,List<Integer>> mListList) {
this.mListList = mListList;
return this;
}
public MyStruct build() {
MyStruct result = new MyStruct();
if (__optional_isset.get(__MYINTFIELD_ISSET_ID)) {
result.setMyIntField(this.MyIntField);
}
result.setMyStringField(this.MyStringField);
result.setMyDataField(this.MyDataField);
result.setMyEnum(this.myEnum);
if (__optional_isset.get(__MYBOOLFIELD_ISSET_ID)) {
result.setMyBoolField(this.MyBoolField);
}
if (__optional_isset.get(__MYBYTEFIELD_ISSET_ID)) {
result.setMyByteField(this.MyByteField);
}
if (__optional_isset.get(__MYSHORTFIELD_ISSET_ID)) {
result.setMyShortField(this.MyShortField);
}
if (__optional_isset.get(__MYLONGFIELD_ISSET_ID)) {
result.setMyLongField(this.MyLongField);
}
if (__optional_isset.get(__MYDOUBLEFIELD_ISSET_ID)) {
result.setMyDoubleField(this.MyDoubleField);
}
result.setLDouble(this.lDouble);
result.setLShort(this.lShort);
result.setLInteger(this.lInteger);
result.setLLong(this.lLong);
result.setLString(this.lString);
result.setLBool(this.lBool);
result.setLByte(this.lByte);
result.setMShortString(this.mShortString);
result.setMIntegerString(this.mIntegerString);
result.setMStringMyStruct(this.mStringMyStruct);
result.setMStringBool(this.mStringBool);
result.setMIntegerInteger(this.mIntegerInteger);
result.setMIntegerBool(this.mIntegerBool);
result.setSShort(this.sShort);
result.setSMyStruct(this.sMyStruct);
result.setSLong(this.sLong);
result.setSString(this.sString);
result.setSByte(this.sByte);
result.setMListList(this.mListList);
return result;
}
}
public static Builder builder() {
return new Builder();
}
/**
* Performs a deep copy on <i>other</i>.
*/
public MyStruct(MyStruct other) {
__isset_bit_vector.clear();
__isset_bit_vector.or(other.__isset_bit_vector);
this.MyIntField = TBaseHelper.deepCopy(other.MyIntField);
if (other.isSetMyStringField()) {
this.MyStringField = TBaseHelper.deepCopy(other.MyStringField);
}
if (other.isSetMyDataField()) {
this.MyDataField = TBaseHelper.deepCopy(other.MyDataField);
}
if (other.isSetMyEnum()) {
this.myEnum = TBaseHelper.deepCopy(other.myEnum);
}
this.MyBoolField = TBaseHelper.deepCopy(other.MyBoolField);
this.MyByteField = TBaseHelper.deepCopy(other.MyByteField);
this.MyShortField = TBaseHelper.deepCopy(other.MyShortField);
this.MyLongField = TBaseHelper.deepCopy(other.MyLongField);
this.MyDoubleField = TBaseHelper.deepCopy(other.MyDoubleField);
if (other.isSetLDouble()) {
this.lDouble = TBaseHelper.deepCopy(other.lDouble);
}
if (other.isSetLShort()) {
this.lShort = TBaseHelper.deepCopy(other.lShort);
}
if (other.isSetLInteger()) {
this.lInteger = TBaseHelper.deepCopy(other.lInteger);
}
if (other.isSetLLong()) {
this.lLong = TBaseHelper.deepCopy(other.lLong);
}
if (other.isSetLString()) {
this.lString = TBaseHelper.deepCopy(other.lString);
}
if (other.isSetLBool()) {
this.lBool = TBaseHelper.deepCopy(other.lBool);
}
if (other.isSetLByte()) {
this.lByte = TBaseHelper.deepCopy(other.lByte);
}
if (other.isSetMShortString()) {
this.mShortString = TBaseHelper.deepCopy(other.mShortString);
}
if (other.isSetMIntegerString()) {
this.mIntegerString = TBaseHelper.deepCopy(other.mIntegerString);
}
if (other.isSetMStringMyStruct()) {
this.mStringMyStruct = TBaseHelper.deepCopy(other.mStringMyStruct);
}
if (other.isSetMStringBool()) {
this.mStringBool = TBaseHelper.deepCopy(other.mStringBool);
}
if (other.isSetMIntegerInteger()) {
this.mIntegerInteger = TBaseHelper.deepCopy(other.mIntegerInteger);
}
if (other.isSetMIntegerBool()) {
this.mIntegerBool = TBaseHelper.deepCopy(other.mIntegerBool);
}
if (other.isSetSShort()) {
this.sShort = TBaseHelper.deepCopy(other.sShort);
}
if (other.isSetSMyStruct()) {
this.sMyStruct = TBaseHelper.deepCopy(other.sMyStruct);
}
if (other.isSetSLong()) {
this.sLong = TBaseHelper.deepCopy(other.sLong);
}
if (other.isSetSString()) {
this.sString = TBaseHelper.deepCopy(other.sString);
}
if (other.isSetSByte()) {
this.sByte = TBaseHelper.deepCopy(other.sByte);
}
if (other.isSetMListList()) {
this.mListList = TBaseHelper.deepCopy(other.mListList);
}
}
public MyStruct deepCopy() {
return new MyStruct(this);
}
public long getMyIntField() {
return this.MyIntField;
}
public MyStruct setMyIntField(long MyIntField) {
this.MyIntField = MyIntField;
setMyIntFieldIsSet(true);
return this;
}
public void unsetMyIntField() {
__isset_bit_vector.clear(__MYINTFIELD_ISSET_ID);
}
// Returns true if field MyIntField is set (has been assigned a value) and false otherwise
public boolean isSetMyIntField() {
return __isset_bit_vector.get(__MYINTFIELD_ISSET_ID);
}
public void setMyIntFieldIsSet(boolean __value) {
__isset_bit_vector.set(__MYINTFIELD_ISSET_ID, __value);
}
public String getMyStringField() {
return this.MyStringField;
}
public MyStruct setMyStringField(String MyStringField) {
this.MyStringField = MyStringField;
return this;
}
public void unsetMyStringField() {
this.MyStringField = null;
}
// Returns true if field MyStringField is set (has been assigned a value) and false otherwise
public boolean isSetMyStringField() {
return this.MyStringField != null;
}
public void setMyStringFieldIsSet(boolean __value) {
if (!__value) {
this.MyStringField = null;
}
}
public MyDataItem getMyDataField() {
return this.MyDataField;
}
public MyStruct setMyDataField(MyDataItem MyDataField) {
this.MyDataField = MyDataField;
return this;
}
public void unsetMyDataField() {
this.MyDataField = null;
}
// Returns true if field MyDataField is set (has been assigned a value) and false otherwise
public boolean isSetMyDataField() {
return this.MyDataField != null;
}
public void setMyDataFieldIsSet(boolean __value) {
if (!__value) {
this.MyDataField = null;
}
}
/**
*
* @see MyEnum
*/
public MyEnum getMyEnum() {
return this.myEnum;
}
/**
*
* @see MyEnum
*/
public MyStruct setMyEnum(MyEnum myEnum) {
this.myEnum = myEnum;
return this;
}
public void unsetMyEnum() {
this.myEnum = null;
}
// Returns true if field myEnum is set (has been assigned a value) and false otherwise
public boolean isSetMyEnum() {
return this.myEnum != null;
}
public void setMyEnumIsSet(boolean __value) {
if (!__value) {
this.myEnum = null;
}
}
public boolean isMyBoolField() {
return this.MyBoolField;
}
public MyStruct setMyBoolField(boolean MyBoolField) {
this.MyBoolField = MyBoolField;
setMyBoolFieldIsSet(true);
return this;
}
public void unsetMyBoolField() {
__isset_bit_vector.clear(__MYBOOLFIELD_ISSET_ID);
}
// Returns true if field MyBoolField is set (has been assigned a value) and false otherwise
public boolean isSetMyBoolField() {
return __isset_bit_vector.get(__MYBOOLFIELD_ISSET_ID);
}
public void setMyBoolFieldIsSet(boolean __value) {
__isset_bit_vector.set(__MYBOOLFIELD_ISSET_ID, __value);
}
public byte getMyByteField() {
return this.MyByteField;
}
public MyStruct setMyByteField(byte MyByteField) {
this.MyByteField = MyByteField;
setMyByteFieldIsSet(true);
return this;
}
public void unsetMyByteField() {
__isset_bit_vector.clear(__MYBYTEFIELD_ISSET_ID);
}
// Returns true if field MyByteField is set (has been assigned a value) and false otherwise
public boolean isSetMyByteField() {
return __isset_bit_vector.get(__MYBYTEFIELD_ISSET_ID);
}
public void setMyByteFieldIsSet(boolean __value) {
__isset_bit_vector.set(__MYBYTEFIELD_ISSET_ID, __value);
}
public short getMyShortField() {
return this.MyShortField;
}
public MyStruct setMyShortField(short MyShortField) {
this.MyShortField = MyShortField;
setMyShortFieldIsSet(true);
return this;
}
public void unsetMyShortField() {
__isset_bit_vector.clear(__MYSHORTFIELD_ISSET_ID);
}
// Returns true if field MyShortField is set (has been assigned a value) and false otherwise
public boolean isSetMyShortField() {
return __isset_bit_vector.get(__MYSHORTFIELD_ISSET_ID);
}
public void setMyShortFieldIsSet(boolean __value) {
__isset_bit_vector.set(__MYSHORTFIELD_ISSET_ID, __value);
}
public long getMyLongField() {
return this.MyLongField;
}
public MyStruct setMyLongField(long MyLongField) {
this.MyLongField = MyLongField;
setMyLongFieldIsSet(true);
return this;
}
public void unsetMyLongField() {
__isset_bit_vector.clear(__MYLONGFIELD_ISSET_ID);
}
// Returns true if field MyLongField is set (has been assigned a value) and false otherwise
public boolean isSetMyLongField() {
return __isset_bit_vector.get(__MYLONGFIELD_ISSET_ID);
}
public void setMyLongFieldIsSet(boolean __value) {
__isset_bit_vector.set(__MYLONGFIELD_ISSET_ID, __value);
}
public double getMyDoubleField() {
return this.MyDoubleField;
}
public MyStruct setMyDoubleField(double MyDoubleField) {
this.MyDoubleField = MyDoubleField;
setMyDoubleFieldIsSet(true);
return this;
}
public void unsetMyDoubleField() {
__isset_bit_vector.clear(__MYDOUBLEFIELD_ISSET_ID);
}
// Returns true if field MyDoubleField is set (has been assigned a value) and false otherwise
public boolean isSetMyDoubleField() {
return __isset_bit_vector.get(__MYDOUBLEFIELD_ISSET_ID);
}
public void setMyDoubleFieldIsSet(boolean __value) {
__isset_bit_vector.set(__MYDOUBLEFIELD_ISSET_ID, __value);
}
public List<Double> getLDouble() {
return this.lDouble;
}
public MyStruct setLDouble(List<Double> lDouble) {
this.lDouble = lDouble;
return this;
}
public void unsetLDouble() {
this.lDouble = null;
}
// Returns true if field lDouble is set (has been assigned a value) and false otherwise
public boolean isSetLDouble() {
return this.lDouble != null;
}
public void setLDoubleIsSet(boolean __value) {
if (!__value) {
this.lDouble = null;
}
}
public List<Short> getLShort() {
return this.lShort;
}
public MyStruct setLShort(List<Short> lShort) {
this.lShort = lShort;
return this;
}
public void unsetLShort() {
this.lShort = null;
}
// Returns true if field lShort is set (has been assigned a value) and false otherwise
public boolean isSetLShort() {
return this.lShort != null;
}
public void setLShortIsSet(boolean __value) {
if (!__value) {
this.lShort = null;
}
}
public List<Integer> getLInteger() {
return this.lInteger;
}
public MyStruct setLInteger(List<Integer> lInteger) {
this.lInteger = lInteger;
return this;
}
public void unsetLInteger() {
this.lInteger = null;
}
// Returns true if field lInteger is set (has been assigned a value) and false otherwise
public boolean isSetLInteger() {
return this.lInteger != null;
}
public void setLIntegerIsSet(boolean __value) {
if (!__value) {
this.lInteger = null;
}
}
public List<Long> getLLong() {
return this.lLong;
}
public MyStruct setLLong(List<Long> lLong) {
this.lLong = lLong;
return this;
}
public void unsetLLong() {
this.lLong = null;
}
// Returns true if field lLong is set (has been assigned a value) and false otherwise
public boolean isSetLLong() {
return this.lLong != null;
}
public void setLLongIsSet(boolean __value) {
if (!__value) {
this.lLong = null;
}
}
public List<String> getLString() {
return this.lString;
}
public MyStruct setLString(List<String> lString) {
this.lString = lString;
return this;
}
public void unsetLString() {
this.lString = null;
}
// Returns true if field lString is set (has been assigned a value) and false otherwise
public boolean isSetLString() {
return this.lString != null;
}
public void setLStringIsSet(boolean __value) {
if (!__value) {
this.lString = null;
}
}
public List<Boolean> getLBool() {
return this.lBool;
}
public MyStruct setLBool(List<Boolean> lBool) {
this.lBool = lBool;
return this;
}
public void unsetLBool() {
this.lBool = null;
}
// Returns true if field lBool is set (has been assigned a value) and false otherwise
public boolean isSetLBool() {
return this.lBool != null;
}
public void setLBoolIsSet(boolean __value) {
if (!__value) {
this.lBool = null;
}
}
public List<Byte> getLByte() {
return this.lByte;
}
public MyStruct setLByte(List<Byte> lByte) {
this.lByte = lByte;
return this;
}
public void unsetLByte() {
this.lByte = null;
}
// Returns true if field lByte is set (has been assigned a value) and false otherwise
public boolean isSetLByte() {
return this.lByte != null;
}
public void setLByteIsSet(boolean __value) {
if (!__value) {
this.lByte = null;
}
}
public Map<Short,String> getMShortString() {
return this.mShortString;
}
public MyStruct setMShortString(Map<Short,String> mShortString) {
this.mShortString = mShortString;
return this;
}
public void unsetMShortString() {
this.mShortString = null;
}
// Returns true if field mShortString is set (has been assigned a value) and false otherwise
public boolean isSetMShortString() {
return this.mShortString != null;
}
public void setMShortStringIsSet(boolean __value) {
if (!__value) {
this.mShortString = null;
}
}
public Map<Integer,String> getMIntegerString() {
return this.mIntegerString;
}
public MyStruct setMIntegerString(Map<Integer,String> mIntegerString) {
this.mIntegerString = mIntegerString;
return this;
}
public void unsetMIntegerString() {
this.mIntegerString = null;
}
// Returns true if field mIntegerString is set (has been assigned a value) and false otherwise
public boolean isSetMIntegerString() {
return this.mIntegerString != null;
}
public void setMIntegerStringIsSet(boolean __value) {
if (!__value) {
this.mIntegerString = null;
}
}
public Map<String,MyStruct> getMStringMyStruct() {
return this.mStringMyStruct;
}
public MyStruct setMStringMyStruct(Map<String,MyStruct> mStringMyStruct) {
this.mStringMyStruct = mStringMyStruct;
return this;
}
public void unsetMStringMyStruct() {
this.mStringMyStruct = null;
}
// Returns true if field mStringMyStruct is set (has been assigned a value) and false otherwise
public boolean isSetMStringMyStruct() {
return this.mStringMyStruct != null;
}
public void setMStringMyStructIsSet(boolean __value) {
if (!__value) {
this.mStringMyStruct = null;
}
}
public Map<String,Boolean> getMStringBool() {
return this.mStringBool;
}
public MyStruct setMStringBool(Map<String,Boolean> mStringBool) {
this.mStringBool = mStringBool;
return this;
}
public void unsetMStringBool() {
this.mStringBool = null;
}
// Returns true if field mStringBool is set (has been assigned a value) and false otherwise
public boolean isSetMStringBool() {
return this.mStringBool != null;
}
public void setMStringBoolIsSet(boolean __value) {
if (!__value) {
this.mStringBool = null;
}
}
public Map<Integer,Integer> getMIntegerInteger() {
return this.mIntegerInteger;
}
public MyStruct setMIntegerInteger(Map<Integer,Integer> mIntegerInteger) {
this.mIntegerInteger = mIntegerInteger;
return this;
}
public void unsetMIntegerInteger() {
this.mIntegerInteger = null;
}
// Returns true if field mIntegerInteger is set (has been assigned a value) and false otherwise
public boolean isSetMIntegerInteger() {
return this.mIntegerInteger != null;
}
public void setMIntegerIntegerIsSet(boolean __value) {
if (!__value) {
this.mIntegerInteger = null;
}
}
public Map<Integer,Boolean> getMIntegerBool() {
return this.mIntegerBool;
}
public MyStruct setMIntegerBool(Map<Integer,Boolean> mIntegerBool) {
this.mIntegerBool = mIntegerBool;
return this;
}
public void unsetMIntegerBool() {
this.mIntegerBool = null;
}
// Returns true if field mIntegerBool is set (has been assigned a value) and false otherwise
public boolean isSetMIntegerBool() {
return this.mIntegerBool != null;
}
public void setMIntegerBoolIsSet(boolean __value) {
if (!__value) {
this.mIntegerBool = null;
}
}
public Set<Short> getSShort() {
return this.sShort;
}
public MyStruct setSShort(Set<Short> sShort) {
this.sShort = sShort;
return this;
}
public void unsetSShort() {
this.sShort = null;
}
// Returns true if field sShort is set (has been assigned a value) and false otherwise
public boolean isSetSShort() {
return this.sShort != null;
}
public void setSShortIsSet(boolean __value) {
if (!__value) {
this.sShort = null;
}
}
public Set<MyStruct> getSMyStruct() {
return this.sMyStruct;
}
public MyStruct setSMyStruct(Set<MyStruct> sMyStruct) {
this.sMyStruct = sMyStruct;
return this;
}
public void unsetSMyStruct() {
this.sMyStruct = null;
}
// Returns true if field sMyStruct is set (has been assigned a value) and false otherwise
public boolean isSetSMyStruct() {
return this.sMyStruct != null;
}
public void setSMyStructIsSet(boolean __value) {
if (!__value) {
this.sMyStruct = null;
}
}
public Set<Long> getSLong() {
return this.sLong;
}
public MyStruct setSLong(Set<Long> sLong) {
this.sLong = sLong;
return this;
}
public void unsetSLong() {
this.sLong = null;
}
// Returns true if field sLong is set (has been assigned a value) and false otherwise
public boolean isSetSLong() {
return this.sLong != null;
}
public void setSLongIsSet(boolean __value) {
if (!__value) {
this.sLong = null;
}
}
public Set<String> getSString() {
return this.sString;
}
public MyStruct setSString(Set<String> sString) {
this.sString = sString;
return this;
}
public void unsetSString() {
this.sString = null;
}
// Returns true if field sString is set (has been assigned a value) and false otherwise
public boolean isSetSString() {
return this.sString != null;
}
public void setSStringIsSet(boolean __value) {
if (!__value) {
this.sString = null;
}
}
public Set<Byte> getSByte() {
return this.sByte;
}
public MyStruct setSByte(Set<Byte> sByte) {
this.sByte = sByte;
return this;
}
public void unsetSByte() {
this.sByte = null;
}
// Returns true if field sByte is set (has been assigned a value) and false otherwise
public boolean isSetSByte() {
return this.sByte != null;
}
public void setSByteIsSet(boolean __value) {
if (!__value) {
this.sByte = null;
}
}
public Map<List<Integer>,List<Integer>> getMListList() {
return this.mListList;
}
public MyStruct setMListList(Map<List<Integer>,List<Integer>> mListList) {
this.mListList = mListList;
return this;
}
public void unsetMListList() {
this.mListList = null;
}
// Returns true if field mListList is set (has been assigned a value) and false otherwise
public boolean isSetMListList() {
return this.mListList != null;
}
public void setMListListIsSet(boolean __value) {
if (!__value) {
this.mListList = null;
}
}
@SuppressWarnings("unchecked")
public void setFieldValue(int fieldID, Object __value) {
switch (fieldID) {
case MYINTFIELD:
if (__value == null) {
unsetMyIntField();
} else {
setMyIntField((Long)__value);
}
break;
case MYSTRINGFIELD:
if (__value == null) {
unsetMyStringField();
} else {
setMyStringField((String)__value);
}
break;
case MYDATAFIELD:
if (__value == null) {
unsetMyDataField();
} else {
setMyDataField((MyDataItem)__value);
}
break;
case MYENUM:
if (__value == null) {
unsetMyEnum();
} else {
setMyEnum((MyEnum)__value);
}
break;
case MYBOOLFIELD:
if (__value == null) {
unsetMyBoolField();
} else {
setMyBoolField((Boolean)__value);
}
break;
case MYBYTEFIELD:
if (__value == null) {
unsetMyByteField();
} else {
setMyByteField((Byte)__value);
}
break;
case MYSHORTFIELD:
if (__value == null) {
unsetMyShortField();
} else {
setMyShortField((Short)__value);
}
break;
case MYLONGFIELD:
if (__value == null) {
unsetMyLongField();
} else {
setMyLongField((Long)__value);
}
break;
case MYDOUBLEFIELD:
if (__value == null) {
unsetMyDoubleField();
} else {
setMyDoubleField((Double)__value);
}
break;
case LDOUBLE:
if (__value == null) {
unsetLDouble();
} else {
setLDouble((List<Double>)__value);
}
break;
case LSHORT:
if (__value == null) {
unsetLShort();
} else {
setLShort((List<Short>)__value);
}
break;
case LINTEGER:
if (__value == null) {
unsetLInteger();
} else {
setLInteger((List<Integer>)__value);
}
break;
case LLONG:
if (__value == null) {
unsetLLong();
} else {
setLLong((List<Long>)__value);
}
break;
case LSTRING:
if (__value == null) {
unsetLString();
} else {
setLString((List<String>)__value);
}
break;
case LBOOL:
if (__value == null) {
unsetLBool();
} else {
setLBool((List<Boolean>)__value);
}
break;
case LBYTE:
if (__value == null) {
unsetLByte();
} else {
setLByte((List<Byte>)__value);
}
break;
case MSHORTSTRING:
if (__value == null) {
unsetMShortString();
} else {
setMShortString((Map<Short,String>)__value);
}
break;
case MINTEGERSTRING:
if (__value == null) {
unsetMIntegerString();
} else {
setMIntegerString((Map<Integer,String>)__value);
}
break;
case MSTRINGMYSTRUCT:
if (__value == null) {
unsetMStringMyStruct();
} else {
setMStringMyStruct((Map<String,MyStruct>)__value);
}
break;
case MSTRINGBOOL:
if (__value == null) {
unsetMStringBool();
} else {
setMStringBool((Map<String,Boolean>)__value);
}
break;
case MINTEGERINTEGER:
if (__value == null) {
unsetMIntegerInteger();
} else {
setMIntegerInteger((Map<Integer,Integer>)__value);
}
break;
case MINTEGERBOOL:
if (__value == null) {
unsetMIntegerBool();
} else {
setMIntegerBool((Map<Integer,Boolean>)__value);
}
break;
case SSHORT:
if (__value == null) {
unsetSShort();
} else {
setSShort((Set<Short>)__value);
}
break;
case SMYSTRUCT:
if (__value == null) {
unsetSMyStruct();
} else {
setSMyStruct((Set<MyStruct>)__value);
}
break;
case SLONG:
if (__value == null) {
unsetSLong();
} else {
setSLong((Set<Long>)__value);
}
break;
case SSTRING:
if (__value == null) {
unsetSString();
} else {
setSString((Set<String>)__value);
}
break;
case SBYTE:
if (__value == null) {
unsetSByte();
} else {
setSByte((Set<Byte>)__value);
}
break;
case MLISTLIST:
if (__value == null) {
unsetMListList();
} else {
setMListList((Map<List<Integer>,List<Integer>>)__value);
}
break;
default:
throw new IllegalArgumentException("Field " + fieldID + " doesn't exist!");
}
}
public Object getFieldValue(int fieldID) {
switch (fieldID) {
case MYINTFIELD:
return new Long(getMyIntField());
case MYSTRINGFIELD:
return getMyStringField();
case MYDATAFIELD:
return getMyDataField();
case MYENUM:
return getMyEnum();
case MYBOOLFIELD:
return new Boolean(isMyBoolField());
case MYBYTEFIELD:
return new Byte(getMyByteField());
case MYSHORTFIELD:
return new Short(getMyShortField());
case MYLONGFIELD:
return new Long(getMyLongField());
case MYDOUBLEFIELD:
return new Double(getMyDoubleField());
case LDOUBLE:
return getLDouble();
case LSHORT:
return getLShort();
case LINTEGER:
return getLInteger();
case LLONG:
return getLLong();
case LSTRING:
return getLString();
case LBOOL:
return getLBool();
case LBYTE:
return getLByte();
case MSHORTSTRING:
return getMShortString();
case MINTEGERSTRING:
return getMIntegerString();
case MSTRINGMYSTRUCT:
return getMStringMyStruct();
case MSTRINGBOOL:
return getMStringBool();
case MINTEGERINTEGER:
return getMIntegerInteger();
case MINTEGERBOOL:
return getMIntegerBool();
case SSHORT:
return getSShort();
case SMYSTRUCT:
return getSMyStruct();
case SLONG:
return getSLong();
case SSTRING:
return getSString();
case SBYTE:
return getSByte();
case MLISTLIST:
return getMListList();
default:
throw new IllegalArgumentException("Field " + fieldID + " doesn't exist!");
}
}
@Override
public boolean equals(Object _that) {
if (_that == null)
return false;
if (this == _that)
return true;
if (!(_that instanceof MyStruct))
return false;
MyStruct that = (MyStruct)_that;
if (!TBaseHelper.equalsNobinary(this.MyIntField, that.MyIntField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMyStringField(), that.isSetMyStringField(), this.MyStringField, that.MyStringField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMyDataField(), that.isSetMyDataField(), this.MyDataField, that.MyDataField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMyEnum(), that.isSetMyEnum(), this.myEnum, that.myEnum)) { return false; }
if (!TBaseHelper.equalsNobinary(this.MyBoolField, that.MyBoolField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.MyByteField, that.MyByteField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.MyShortField, that.MyShortField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.MyLongField, that.MyLongField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.MyDoubleField, that.MyDoubleField)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetLDouble(), that.isSetLDouble(), this.lDouble, that.lDouble)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetLShort(), that.isSetLShort(), this.lShort, that.lShort)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetLInteger(), that.isSetLInteger(), this.lInteger, that.lInteger)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetLLong(), that.isSetLLong(), this.lLong, that.lLong)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetLString(), that.isSetLString(), this.lString, that.lString)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetLBool(), that.isSetLBool(), this.lBool, that.lBool)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetLByte(), that.isSetLByte(), this.lByte, that.lByte)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMShortString(), that.isSetMShortString(), this.mShortString, that.mShortString)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMIntegerString(), that.isSetMIntegerString(), this.mIntegerString, that.mIntegerString)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMStringMyStruct(), that.isSetMStringMyStruct(), this.mStringMyStruct, that.mStringMyStruct)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMStringBool(), that.isSetMStringBool(), this.mStringBool, that.mStringBool)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMIntegerInteger(), that.isSetMIntegerInteger(), this.mIntegerInteger, that.mIntegerInteger)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMIntegerBool(), that.isSetMIntegerBool(), this.mIntegerBool, that.mIntegerBool)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetSShort(), that.isSetSShort(), this.sShort, that.sShort)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetSMyStruct(), that.isSetSMyStruct(), this.sMyStruct, that.sMyStruct)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetSLong(), that.isSetSLong(), this.sLong, that.sLong)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetSString(), that.isSetSString(), this.sString, that.sString)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetSByte(), that.isSetSByte(), this.sByte, that.sByte)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetMListList(), that.isSetMListList(), this.mListList, that.mListList)) { return false; }
return true;
}
@Override
public int hashCode() {
return Arrays.deepHashCode(new Object[] {MyIntField, MyStringField, MyDataField, myEnum, MyBoolField, MyByteField, MyShortField, MyLongField, MyDoubleField, lDouble, lShort, lInteger, lLong, lString, lBool, lByte, mShortString, mIntegerString, mStringMyStruct, mStringBool, mIntegerInteger, mIntegerBool, sShort, sMyStruct, sLong, sString, sByte, mListList});
}
public void read(TProtocol iprot) throws TException {
TField __field;
iprot.readStructBegin(metaDataMap);
while (true)
{
__field = iprot.readFieldBegin();
if (__field.type == TType.STOP) {
break;
}
switch (__field.id)
{
case MYINTFIELD:
if (__field.type == TType.I64) {
this.MyIntField = iprot.readI64();
setMyIntFieldIsSet(true);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYSTRINGFIELD:
if (__field.type == TType.STRING) {
this.MyStringField = iprot.readString();
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYDATAFIELD:
if (__field.type == TType.STRUCT) {
this.MyDataField = new MyDataItem();
this.MyDataField.read(iprot);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYENUM:
if (__field.type == TType.I32) {
this.myEnum = MyEnum.findByValue(iprot.readI32());
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYBOOLFIELD:
if (__field.type == TType.BOOL) {
this.MyBoolField = iprot.readBool();
setMyBoolFieldIsSet(true);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYBYTEFIELD:
if (__field.type == TType.BYTE) {
this.MyByteField = iprot.readByte();
setMyByteFieldIsSet(true);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYSHORTFIELD:
if (__field.type == TType.I16) {
this.MyShortField = iprot.readI16();
setMyShortFieldIsSet(true);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYLONGFIELD:
if (__field.type == TType.I64) {
this.MyLongField = iprot.readI64();
setMyLongFieldIsSet(true);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MYDOUBLEFIELD:
if (__field.type == TType.DOUBLE) {
this.MyDoubleField = iprot.readDouble();
setMyDoubleFieldIsSet(true);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LDOUBLE:
if (__field.type == TType.LIST) {
{
TList _list13 = iprot.readListBegin();
this.lDouble = new ArrayList<Double>(Math.max(0, _list13.size));
for (int _i14 = 0;
(_list13.size < 0) ? iprot.peekList() : (_i14 < _list13.size);
++_i14)
{
double _elem15;
_elem15 = iprot.readDouble();
this.lDouble.add(_elem15);
}
iprot.readListEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LSHORT:
if (__field.type == TType.LIST) {
{
TList _list16 = iprot.readListBegin();
this.lShort = new ArrayList<Short>(Math.max(0, _list16.size));
for (int _i17 = 0;
(_list16.size < 0) ? iprot.peekList() : (_i17 < _list16.size);
++_i17)
{
short _elem18;
_elem18 = iprot.readI16();
this.lShort.add(_elem18);
}
iprot.readListEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LINTEGER:
if (__field.type == TType.LIST) {
{
TList _list19 = iprot.readListBegin();
this.lInteger = new ArrayList<Integer>(Math.max(0, _list19.size));
for (int _i20 = 0;
(_list19.size < 0) ? iprot.peekList() : (_i20 < _list19.size);
++_i20)
{
int _elem21;
_elem21 = iprot.readI32();
this.lInteger.add(_elem21);
}
iprot.readListEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LLONG:
if (__field.type == TType.LIST) {
{
TList _list22 = iprot.readListBegin();
this.lLong = new ArrayList<Long>(Math.max(0, _list22.size));
for (int _i23 = 0;
(_list22.size < 0) ? iprot.peekList() : (_i23 < _list22.size);
++_i23)
{
long _elem24;
_elem24 = iprot.readI64();
this.lLong.add(_elem24);
}
iprot.readListEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LSTRING:
if (__field.type == TType.LIST) {
{
TList _list25 = iprot.readListBegin();
this.lString = new ArrayList<String>(Math.max(0, _list25.size));
for (int _i26 = 0;
(_list25.size < 0) ? iprot.peekList() : (_i26 < _list25.size);
++_i26)
{
String _elem27;
_elem27 = iprot.readString();
this.lString.add(_elem27);
}
iprot.readListEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LBOOL:
if (__field.type == TType.LIST) {
{
TList _list28 = iprot.readListBegin();
this.lBool = new ArrayList<Boolean>(Math.max(0, _list28.size));
for (int _i29 = 0;
(_list28.size < 0) ? iprot.peekList() : (_i29 < _list28.size);
++_i29)
{
boolean _elem30;
_elem30 = iprot.readBool();
this.lBool.add(_elem30);
}
iprot.readListEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LBYTE:
if (__field.type == TType.LIST) {
{
TList _list31 = iprot.readListBegin();
this.lByte = new ArrayList<Byte>(Math.max(0, _list31.size));
for (int _i32 = 0;
(_list31.size < 0) ? iprot.peekList() : (_i32 < _list31.size);
++_i32)
{
byte _elem33;
_elem33 = iprot.readByte();
this.lByte.add(_elem33);
}
iprot.readListEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MSHORTSTRING:
if (__field.type == TType.MAP) {
{
TMap _map34 = iprot.readMapBegin();
this.mShortString = new HashMap<Short,String>(Math.max(0, 2*_map34.size));
for (int _i35 = 0;
(_map34.size < 0) ? iprot.peekMap() : (_i35 < _map34.size);
++_i35)
{
short _key36;
String _val37;
_key36 = iprot.readI16();
_val37 = iprot.readString();
this.mShortString.put(_key36, _val37);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MINTEGERSTRING:
if (__field.type == TType.MAP) {
{
TMap _map38 = iprot.readMapBegin();
this.mIntegerString = new HashMap<Integer,String>(Math.max(0, 2*_map38.size));
for (int _i39 = 0;
(_map38.size < 0) ? iprot.peekMap() : (_i39 < _map38.size);
++_i39)
{
int _key40;
String _val41;
_key40 = iprot.readI32();
_val41 = iprot.readString();
this.mIntegerString.put(_key40, _val41);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MSTRINGMYSTRUCT:
if (__field.type == TType.MAP) {
{
TMap _map42 = iprot.readMapBegin();
this.mStringMyStruct = new HashMap<String,MyStruct>(Math.max(0, 2*_map42.size));
for (int _i43 = 0;
(_map42.size < 0) ? iprot.peekMap() : (_i43 < _map42.size);
++_i43)
{
String _key44;
MyStruct _val45;
_key44 = iprot.readString();
_val45 = new MyStruct();
_val45.read(iprot);
this.mStringMyStruct.put(_key44, _val45);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MSTRINGBOOL:
if (__field.type == TType.MAP) {
{
TMap _map46 = iprot.readMapBegin();
this.mStringBool = new HashMap<String,Boolean>(Math.max(0, 2*_map46.size));
for (int _i47 = 0;
(_map46.size < 0) ? iprot.peekMap() : (_i47 < _map46.size);
++_i47)
{
String _key48;
boolean _val49;
_key48 = iprot.readString();
_val49 = iprot.readBool();
this.mStringBool.put(_key48, _val49);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MINTEGERINTEGER:
if (__field.type == TType.MAP) {
{
TMap _map50 = iprot.readMapBegin();
this.mIntegerInteger = new HashMap<Integer,Integer>(Math.max(0, 2*_map50.size));
for (int _i51 = 0;
(_map50.size < 0) ? iprot.peekMap() : (_i51 < _map50.size);
++_i51)
{
int _key52;
int _val53;
_key52 = iprot.readI32();
_val53 = iprot.readI32();
this.mIntegerInteger.put(_key52, _val53);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MINTEGERBOOL:
if (__field.type == TType.MAP) {
{
TMap _map54 = iprot.readMapBegin();
this.mIntegerBool = new HashMap<Integer,Boolean>(Math.max(0, 2*_map54.size));
for (int _i55 = 0;
(_map54.size < 0) ? iprot.peekMap() : (_i55 < _map54.size);
++_i55)
{
int _key56;
boolean _val57;
_key56 = iprot.readI32();
_val57 = iprot.readBool();
this.mIntegerBool.put(_key56, _val57);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case SSHORT:
if (__field.type == TType.SET) {
{
TSet _set58 = iprot.readSetBegin();
this.sShort = new HashSet<Short>(Math.max(0, 2*_set58.size));
for (int _i59 = 0;
(_set58.size < 0) ? iprot.peekSet() : (_i59 < _set58.size);
++_i59)
{
short _elem60;
_elem60 = iprot.readI16();
this.sShort.add(_elem60);
}
iprot.readSetEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case SMYSTRUCT:
if (__field.type == TType.SET) {
{
TSet _set61 = iprot.readSetBegin();
this.sMyStruct = new HashSet<MyStruct>(Math.max(0, 2*_set61.size));
for (int _i62 = 0;
(_set61.size < 0) ? iprot.peekSet() : (_i62 < _set61.size);
++_i62)
{
MyStruct _elem63;
_elem63 = new MyStruct();
_elem63.read(iprot);
this.sMyStruct.add(_elem63);
}
iprot.readSetEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case SLONG:
if (__field.type == TType.SET) {
{
TSet _set64 = iprot.readSetBegin();
this.sLong = new HashSet<Long>(Math.max(0, 2*_set64.size));
for (int _i65 = 0;
(_set64.size < 0) ? iprot.peekSet() : (_i65 < _set64.size);
++_i65)
{
long _elem66;
_elem66 = iprot.readI64();
this.sLong.add(_elem66);
}
iprot.readSetEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case SSTRING:
if (__field.type == TType.SET) {
{
TSet _set67 = iprot.readSetBegin();
this.sString = new HashSet<String>(Math.max(0, 2*_set67.size));
for (int _i68 = 0;
(_set67.size < 0) ? iprot.peekSet() : (_i68 < _set67.size);
++_i68)
{
String _elem69;
_elem69 = iprot.readString();
this.sString.add(_elem69);
}
iprot.readSetEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case SBYTE:
if (__field.type == TType.SET) {
{
TSet _set70 = iprot.readSetBegin();
this.sByte = new HashSet<Byte>(Math.max(0, 2*_set70.size));
for (int _i71 = 0;
(_set70.size < 0) ? iprot.peekSet() : (_i71 < _set70.size);
++_i71)
{
byte _elem72;
_elem72 = iprot.readByte();
this.sByte.add(_elem72);
}
iprot.readSetEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case MLISTLIST:
if (__field.type == TType.MAP) {
{
TMap _map73 = iprot.readMapBegin();
this.mListList = new HashMap<List<Integer>,List<Integer>>(Math.max(0, 2*_map73.size));
for (int _i74 = 0;
(_map73.size < 0) ? iprot.peekMap() : (_i74 < _map73.size);
++_i74)
{
List<Integer> _key75;
List<Integer> _val76;
{
TList _list77 = iprot.readListBegin();
_key75 = new ArrayList<Integer>(Math.max(0, _list77.size));
for (int _i78 = 0;
(_list77.size < 0) ? iprot.peekList() : (_i78 < _list77.size);
++_i78)
{
int _elem79;
_elem79 = iprot.readI32();
_key75.add(_elem79);
}
iprot.readListEnd();
}
{
TList _list80 = iprot.readListBegin();
_val76 = new ArrayList<Integer>(Math.max(0, _list80.size));
for (int _i81 = 0;
(_list80.size < 0) ? iprot.peekList() : (_i81 < _list80.size);
++_i81)
{
int _elem82;
_elem82 = iprot.readI32();
_val76.add(_elem82);
}
iprot.readListEnd();
}
this.mListList.put(_key75, _val76);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
default:
TProtocolUtil.skip(iprot, __field.type);
break;
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
validate();
}
public void write(TProtocol oprot) throws TException {
validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(MY_INT_FIELD_FIELD_DESC);
oprot.writeI64(this.MyIntField);
oprot.writeFieldEnd();
if (this.MyStringField != null) {
oprot.writeFieldBegin(MY_STRING_FIELD_FIELD_DESC);
oprot.writeString(this.MyStringField);
oprot.writeFieldEnd();
}
if (this.MyDataField != null) {
oprot.writeFieldBegin(MY_DATA_FIELD_FIELD_DESC);
this.MyDataField.write(oprot);
oprot.writeFieldEnd();
}
if (this.myEnum != null) {
oprot.writeFieldBegin(MY_ENUM_FIELD_DESC);
oprot.writeI32(this.myEnum == null ? 0 : this.myEnum.getValue());
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(MY_BOOL_FIELD_FIELD_DESC);
oprot.writeBool(this.MyBoolField);
oprot.writeFieldEnd();
oprot.writeFieldBegin(MY_BYTE_FIELD_FIELD_DESC);
oprot.writeByte(this.MyByteField);
oprot.writeFieldEnd();
oprot.writeFieldBegin(MY_SHORT_FIELD_FIELD_DESC);
oprot.writeI16(this.MyShortField);
oprot.writeFieldEnd();
oprot.writeFieldBegin(MY_LONG_FIELD_FIELD_DESC);
oprot.writeI64(this.MyLongField);
oprot.writeFieldEnd();
oprot.writeFieldBegin(MY_DOUBLE_FIELD_FIELD_DESC);
oprot.writeDouble(this.MyDoubleField);
oprot.writeFieldEnd();
if (this.lDouble != null) {
oprot.writeFieldBegin(L_DOUBLE_FIELD_DESC);
{
oprot.writeListBegin(new TList(TType.DOUBLE, this.lDouble.size()));
for (double _iter83 : this.lDouble) {
oprot.writeDouble(_iter83);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (this.lShort != null) {
oprot.writeFieldBegin(L_SHORT_FIELD_DESC);
{
oprot.writeListBegin(new TList(TType.I16, this.lShort.size()));
for (short _iter84 : this.lShort) {
oprot.writeI16(_iter84);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (this.lInteger != null) {
oprot.writeFieldBegin(L_INTEGER_FIELD_DESC);
{
oprot.writeListBegin(new TList(TType.I32, this.lInteger.size()));
for (int _iter85 : this.lInteger) {
oprot.writeI32(_iter85);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (this.lLong != null) {
oprot.writeFieldBegin(L_LONG_FIELD_DESC);
{
oprot.writeListBegin(new TList(TType.I64, this.lLong.size()));
for (long _iter86 : this.lLong) {
oprot.writeI64(_iter86);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (this.lString != null) {
oprot.writeFieldBegin(L_STRING_FIELD_DESC);
{
oprot.writeListBegin(new TList(TType.STRING, this.lString.size()));
for (String _iter87 : this.lString) {
oprot.writeString(_iter87);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (this.lBool != null) {
oprot.writeFieldBegin(L_BOOL_FIELD_DESC);
{
oprot.writeListBegin(new TList(TType.BOOL, this.lBool.size()));
for (boolean _iter88 : this.lBool) {
oprot.writeBool(_iter88);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (this.lByte != null) {
oprot.writeFieldBegin(L_BYTE_FIELD_DESC);
{
oprot.writeListBegin(new TList(TType.BYTE, this.lByte.size()));
for (byte _iter89 : this.lByte) {
oprot.writeByte(_iter89);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (this.mShortString != null) {
oprot.writeFieldBegin(M_SHORT_STRING_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.I16, TType.STRING, this.mShortString.size()));
for (Map.Entry<Short, String> _iter90 : this.mShortString.entrySet()) {
oprot.writeI16(_iter90.getKey());
oprot.writeString(_iter90.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.mIntegerString != null) {
oprot.writeFieldBegin(M_INTEGER_STRING_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.I32, TType.STRING, this.mIntegerString.size()));
for (Map.Entry<Integer, String> _iter91 : this.mIntegerString.entrySet()) {
oprot.writeI32(_iter91.getKey());
oprot.writeString(_iter91.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.mStringMyStruct != null) {
oprot.writeFieldBegin(M_STRING_MY_STRUCT_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.STRUCT, this.mStringMyStruct.size()));
for (Map.Entry<String, MyStruct> _iter92 : this.mStringMyStruct.entrySet()) {
oprot.writeString(_iter92.getKey());
_iter92.getValue().write(oprot);
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.mStringBool != null) {
oprot.writeFieldBegin(M_STRING_BOOL_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.BOOL, this.mStringBool.size()));
for (Map.Entry<String, Boolean> _iter93 : this.mStringBool.entrySet()) {
oprot.writeString(_iter93.getKey());
oprot.writeBool(_iter93.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.mIntegerInteger != null) {
oprot.writeFieldBegin(M_INTEGER_INTEGER_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.I32, TType.I32, this.mIntegerInteger.size()));
for (Map.Entry<Integer, Integer> _iter94 : this.mIntegerInteger.entrySet()) {
oprot.writeI32(_iter94.getKey());
oprot.writeI32(_iter94.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.mIntegerBool != null) {
oprot.writeFieldBegin(M_INTEGER_BOOL_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.I32, TType.BOOL, this.mIntegerBool.size()));
for (Map.Entry<Integer, Boolean> _iter95 : this.mIntegerBool.entrySet()) {
oprot.writeI32(_iter95.getKey());
oprot.writeBool(_iter95.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.sShort != null) {
oprot.writeFieldBegin(S_SHORT_FIELD_DESC);
{
oprot.writeSetBegin(new TSet(TType.I16, this.sShort.size()));
for (short _iter96 : this.sShort) {
oprot.writeI16(_iter96);
}
oprot.writeSetEnd();
}
oprot.writeFieldEnd();
}
if (this.sMyStruct != null) {
oprot.writeFieldBegin(S_MY_STRUCT_FIELD_DESC);
{
oprot.writeSetBegin(new TSet(TType.STRUCT, this.sMyStruct.size()));
for (MyStruct _iter97 : this.sMyStruct) {
_iter97.write(oprot);
}
oprot.writeSetEnd();
}
oprot.writeFieldEnd();
}
if (this.sLong != null) {
oprot.writeFieldBegin(S_LONG_FIELD_DESC);
{
oprot.writeSetBegin(new TSet(TType.I64, this.sLong.size()));
for (long _iter98 : this.sLong) {
oprot.writeI64(_iter98);
}
oprot.writeSetEnd();
}
oprot.writeFieldEnd();
}
if (this.sString != null) {
oprot.writeFieldBegin(S_STRING_FIELD_DESC);
{
oprot.writeSetBegin(new TSet(TType.STRING, this.sString.size()));
for (String _iter99 : this.sString) {
oprot.writeString(_iter99);
}
oprot.writeSetEnd();
}
oprot.writeFieldEnd();
}
if (this.sByte != null) {
oprot.writeFieldBegin(S_BYTE_FIELD_DESC);
{
oprot.writeSetBegin(new TSet(TType.BYTE, this.sByte.size()));
for (byte _iter100 : this.sByte) {
oprot.writeByte(_iter100);
}
oprot.writeSetEnd();
}
oprot.writeFieldEnd();
}
if (this.mListList != null) {
oprot.writeFieldBegin(M_LIST_LIST_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.LIST, TType.LIST, this.mListList.size()));
for (Map.Entry<List<Integer>, List<Integer>> _iter101 : this.mListList.entrySet()) {
{
oprot.writeListBegin(new TList(TType.I32, _iter101.getKey().size()));
for (int _iter102 : _iter101.getKey()) {
oprot.writeI32(_iter102);
}
oprot.writeListEnd();
}
{
oprot.writeListBegin(new TList(TType.I32, _iter101.getValue().size()));
for (int _iter103 : _iter101.getValue()) {
oprot.writeI32(_iter103);
}
oprot.writeListEnd();
}
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
@Override
public String toString() {
return toString(1, true);
}
@Override
public String toString(int indent, boolean prettyPrint) {
String indentStr = prettyPrint ? TBaseHelper.getIndentedString(indent) : "";
String newLine = prettyPrint ? "\n" : "";
String space = prettyPrint ? " " : "";
StringBuilder sb = new StringBuilder("MyStruct");
sb.append(space);
sb.append("(");
sb.append(newLine);
boolean first = true;
sb.append(indentStr);
sb.append("MyIntField");
sb.append(space);
sb.append(":").append(space);
sb.append(TBaseHelper.toString(this.getMyIntField(), indent + 1, prettyPrint));
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("MyStringField");
sb.append(space);
sb.append(":").append(space);
if (this.getMyStringField() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMyStringField(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("MyDataField");
sb.append(space);
sb.append(":").append(space);
if (this.getMyDataField() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMyDataField(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("myEnum");
sb.append(space);
sb.append(":").append(space);
if (this.getMyEnum() == null) {
sb.append("null");
} else {
String myEnum_name = this.getMyEnum() == null ? "null" : this.getMyEnum().name();
if (myEnum_name != null) {
sb.append(myEnum_name);
sb.append(" (");
}
sb.append(this.getMyEnum());
if (myEnum_name != null) {
sb.append(")");
}
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("MyBoolField");
sb.append(space);
sb.append(":").append(space);
sb.append(TBaseHelper.toString(this.isMyBoolField(), indent + 1, prettyPrint));
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("MyByteField");
sb.append(space);
sb.append(":").append(space);
sb.append(TBaseHelper.toString(this.getMyByteField(), indent + 1, prettyPrint));
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("MyShortField");
sb.append(space);
sb.append(":").append(space);
sb.append(TBaseHelper.toString(this.getMyShortField(), indent + 1, prettyPrint));
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("MyLongField");
sb.append(space);
sb.append(":").append(space);
sb.append(TBaseHelper.toString(this.getMyLongField(), indent + 1, prettyPrint));
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("MyDoubleField");
sb.append(space);
sb.append(":").append(space);
sb.append(TBaseHelper.toString(this.getMyDoubleField(), indent + 1, prettyPrint));
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("lDouble");
sb.append(space);
sb.append(":").append(space);
if (this.getLDouble() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLDouble(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("lShort");
sb.append(space);
sb.append(":").append(space);
if (this.getLShort() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLShort(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("lInteger");
sb.append(space);
sb.append(":").append(space);
if (this.getLInteger() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLInteger(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("lLong");
sb.append(space);
sb.append(":").append(space);
if (this.getLLong() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLLong(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("lString");
sb.append(space);
sb.append(":").append(space);
if (this.getLString() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLString(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("lBool");
sb.append(space);
sb.append(":").append(space);
if (this.getLBool() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLBool(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("lByte");
sb.append(space);
sb.append(":").append(space);
if (this.getLByte() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLByte(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("mShortString");
sb.append(space);
sb.append(":").append(space);
if (this.getMShortString() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMShortString(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("mIntegerString");
sb.append(space);
sb.append(":").append(space);
if (this.getMIntegerString() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMIntegerString(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("mStringMyStruct");
sb.append(space);
sb.append(":").append(space);
if (this.getMStringMyStruct() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMStringMyStruct(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("mStringBool");
sb.append(space);
sb.append(":").append(space);
if (this.getMStringBool() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMStringBool(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("mIntegerInteger");
sb.append(space);
sb.append(":").append(space);
if (this.getMIntegerInteger() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMIntegerInteger(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("mIntegerBool");
sb.append(space);
sb.append(":").append(space);
if (this.getMIntegerBool() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMIntegerBool(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("sShort");
sb.append(space);
sb.append(":").append(space);
if (this.getSShort() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getSShort(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("sMyStruct");
sb.append(space);
sb.append(":").append(space);
if (this.getSMyStruct() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getSMyStruct(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("sLong");
sb.append(space);
sb.append(":").append(space);
if (this.getSLong() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getSLong(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("sString");
sb.append(space);
sb.append(":").append(space);
if (this.getSString() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getSString(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("sByte");
sb.append(space);
sb.append(":").append(space);
if (this.getSByte() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getSByte(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("mListList");
sb.append(space);
sb.append(":").append(space);
if (this.getMListList() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getMListList(), indent + 1, prettyPrint));
}
first = false;
sb.append(newLine + TBaseHelper.reduceIndent(indentStr));
sb.append(")");
return sb.toString();
}
public void validate() throws TException {
// check for required fields
}
}
| {
"content_hash": "221c214bdf8e491efcac77157322809b",
"timestamp": "",
"source": "github",
"line_count": 2757,
"max_line_length": 363,
"avg_line_length": 30.877765687341313,
"alnum_prop": 0.6010454598848819,
"repo_name": "facebook/fbthrift",
"id": "3636593628460ad78825e9d5e8689ee284b2f3da",
"size": "85130",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "thrift/compiler/test/fixtures/complex-struct/gen-javadeprecated/MyStruct.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "15608"
},
{
"name": "C++",
"bytes": "10658844"
},
{
"name": "CMake",
"bytes": "147347"
},
{
"name": "CSS",
"bytes": "4028"
},
{
"name": "Cython",
"bytes": "339005"
},
{
"name": "Emacs Lisp",
"bytes": "11229"
},
{
"name": "Go",
"bytes": "447092"
},
{
"name": "Hack",
"bytes": "313122"
},
{
"name": "Java",
"bytes": "1990062"
},
{
"name": "JavaScript",
"bytes": "38872"
},
{
"name": "Mustache",
"bytes": "1269560"
},
{
"name": "Python",
"bytes": "1623026"
},
{
"name": "Ruby",
"bytes": "6111"
},
{
"name": "Rust",
"bytes": "283392"
},
{
"name": "Shell",
"bytes": "6615"
},
{
"name": "Thrift",
"bytes": "1859041"
},
{
"name": "Vim Script",
"bytes": "2887"
}
],
"symlink_target": ""
} |
<?php
$icl_ncp_plugins = array(
'absolute-links/absolute-links-plugin.php',
'cms-navigation/CMS-Navigation.php'
);
$active_plugins = get_option('active_plugins');
$icl_ncp_plugins = array_intersect($icl_ncp_plugins, $active_plugins);
if(!empty($icl_ncp_plugins)){
$icl_sitepress_disabled = true;
$icl_sitepress_idx = array_search(ICL_PLUGIN_FOLDER . '/sitepress.php', $active_plugins);
if(false !== $icl_sitepress_idx){
unset($active_plugins[$icl_sitepress_idx]);
update_option('active_plugins', $active_plugins);
unset($_GET['activate']);
$recently_activated = get_option('recently_activated');
if(!isset($recently_activated[ICL_PLUGIN_FOLDER . '/sitepress.php'])){
$recently_activated[ICL_PLUGIN_FOLDER . '/sitepress.php'] = time();
update_option('recently_activated', $recently_activated);
}
}
add_action('admin_notices', 'icl_incomp_plugins_warn');
function icl_incomp_plugins_warn(){
global $icl_ncp_plugins;
echo '<div class="error"><ul><li><strong>';
echo __('WPML cannot be activated together with these older plugins:', 'sitepress');
echo '<ul style="list-style:disc;margin:20px;">';
foreach($icl_ncp_plugins as $incp){
echo '<li>'.$incp.'</li>';
}
echo '</ul>';
echo __('WPML will be deactivated', 'sitepress');
echo '</strong></li></ul></div>';
}
}else{
$icl_sitepress_disabled = false;
}
if(isset($_GET['page']) && $_GET['page'] == ICL_PLUGIN_FOLDER . '/menu/troubleshooting.php' || isset($pagenow) && $pagenow=='index.php'){
$icl_ncp_plugins2 = array(
'wp-no-category-base/no-category-base.php'
);
$active_plugins = get_option('active_plugins');
$icl_ncp_plugins2 = array_intersect($icl_ncp_plugins2, $active_plugins);
if(!empty($icl_ncp_plugins2)){
if(isset($_GET['page']) && $_GET['page'] == ICL_PLUGIN_FOLDER . '/menu/troubleshooting.php'){
add_action('admin_notices', 'icl_incomp_plugins_warn2');
function icl_incomp_plugins_warn2(){
global $icl_ncp_plugins2;
echo '<a name="icl_inc_plugins_notice"></a><div class="error" style="padding:10px;">';
echo __('These plugins are known to have compatibiliy issues with WPML:', 'sitepress');
echo '<ul style="list-style:disc;margin-left:20px;">';
foreach($icl_ncp_plugins2 as $incp){
echo '<li>'.$incp.'</li>';
}
echo '</ul>';
echo '</div>';
}
}else{
add_action('icl_dashboard_widget_content_top', 'icl_incomp_plugins_warn_dashboard', 1, 0);
function icl_incomp_plugins_warn_dashboard(){
echo '<div class="icl_form_errors" style="width:98%">';
printf (__('You are using plugins that are incompatible with WPML - <a href="%s">see details</a>.', 'sitepress'), admin_url('admin.php?page='.ICL_PLUGIN_FOLDER.'/menu/troubleshooting.php'));
echo '</div>';
}
}
}
}
| {
"content_hash": "113a3564a12becb2d8790126af7fa649",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 206,
"avg_line_length": 43.76,
"alnum_prop": 0.552407068860451,
"repo_name": "netport/open-dai.eu",
"id": "791c7dc06c6fa6f1720d613531130bc9e8d17263",
"size": "3282",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "web/app/plugins/sitepress-multilingual-cms/inc/not-compatible-plugins.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50632"
},
{
"name": "JavaScript",
"bytes": "157353"
},
{
"name": "PHP",
"bytes": "2215560"
},
{
"name": "Ruby",
"bytes": "3214"
}
],
"symlink_target": ""
} |
package com.helger.xml.serialize.read;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.ext.DeclHandler;
import org.xml.sax.ext.LexicalHandler;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.annotation.ReturnsMutableObject;
import com.helger.commons.callback.CallbackList;
import com.helger.commons.callback.exception.IExceptionCallback;
import com.helger.commons.collection.impl.CommonsEnumMap;
import com.helger.commons.collection.impl.ICommonsMap;
import com.helger.commons.lang.ICloneable;
import com.helger.commons.string.ToStringGenerator;
import com.helger.xml.EXMLParserFeature;
import com.helger.xml.EXMLParserProperty;
/**
* SAX reader settings
*
* @author Philip Helger
*/
@NotThreadSafe
public class SAXReaderSettings implements ISAXReaderSettings, ICloneable <SAXReaderSettings>
{
private static final Logger LOGGER = LoggerFactory.getLogger (SAXReaderSettings.class);
private EntityResolver m_aEntityResolver;
private DTDHandler m_aDTDHandler;
private ContentHandler m_aContentHandler;
private ErrorHandler m_aErrorHandler;
private final ICommonsMap <EXMLParserProperty, Object> m_aProperties = new CommonsEnumMap <> (EXMLParserProperty.class);
private final ICommonsMap <EXMLParserFeature, Boolean> m_aFeatures = new CommonsEnumMap <> (EXMLParserFeature.class);
private final CallbackList <IExceptionCallback <Throwable>> m_aExceptionCallbacks = new CallbackList <> ();
private boolean m_bRequiresNewXMLParserExplicitly;
/**
* Default constructor
*/
public SAXReaderSettings ()
{
// Set default values
setEntityResolver (SAXReaderDefaultSettings.getEntityResolver ());
setDTDHandler (SAXReaderDefaultSettings.getDTDHandler ());
setContentHandler (SAXReaderDefaultSettings.getContentHandler ());
setErrorHandler (SAXReaderDefaultSettings.getErrorHandler ());
setPropertyValues (SAXReaderDefaultSettings.getAllPropertyValues ());
setFeatureValues (SAXReaderDefaultSettings.getAllFeatureValues ());
exceptionCallbacks ().set (SAXReaderDefaultSettings.exceptionCallbacks ());
setRequiresNewXMLParserExplicitly (SAXReaderDefaultSettings.isRequiresNewXMLParserExplicitly ());
}
/**
* Copy constructor
*
* @param aOther
* the object to copy the settings from. May not be <code>null</code>.
*/
public SAXReaderSettings (@Nonnull final ISAXReaderSettings aOther)
{
ValueEnforcer.notNull (aOther, "Other");
// Set default values
setEntityResolver (aOther.getEntityResolver ());
setDTDHandler (aOther.getDTDHandler ());
setContentHandler (aOther.getContentHandler ());
setErrorHandler (aOther.getErrorHandler ());
setPropertyValues (aOther.getAllPropertyValues ());
setFeatureValues (aOther.getAllFeatureValues ());
exceptionCallbacks ().set (aOther.exceptionCallbacks ());
setRequiresNewXMLParserExplicitly (aOther.isRequiresNewXMLParserExplicitly ());
}
@Nullable
public EntityResolver getEntityResolver ()
{
return m_aEntityResolver;
}
@Nonnull
public final SAXReaderSettings setEntityResolver (@Nullable final EntityResolver aEntityResolver)
{
m_aEntityResolver = aEntityResolver;
return this;
}
@Nullable
public DTDHandler getDTDHandler ()
{
return m_aDTDHandler;
}
@Nonnull
public final SAXReaderSettings setDTDHandler (@Nullable final DTDHandler aDTDHandler)
{
m_aDTDHandler = aDTDHandler;
return this;
}
@Nullable
public ContentHandler getContentHandler ()
{
return m_aContentHandler;
}
@Nonnull
public final SAXReaderSettings setContentHandler (@Nullable final ContentHandler aContentHandler)
{
m_aContentHandler = aContentHandler;
return this;
}
@Nullable
public ErrorHandler getErrorHandler ()
{
return m_aErrorHandler;
}
@Nonnull
public final SAXReaderSettings setErrorHandler (@Nullable final ErrorHandler aErrorHandler)
{
m_aErrorHandler = aErrorHandler;
return this;
}
@Nullable
public LexicalHandler getLexicalHandler ()
{
return (LexicalHandler) getPropertyValue (EXMLParserProperty.SAX_LEXICAL_HANDLER);
}
@Nonnull
public final SAXReaderSettings setLexicalHandler (@Nullable final LexicalHandler aLexicalHandler)
{
return setPropertyValue (EXMLParserProperty.SAX_LEXICAL_HANDLER, aLexicalHandler);
}
@Nullable
public DeclHandler getDeclarationHandler ()
{
return (DeclHandler) getPropertyValue (EXMLParserProperty.SAX_DECLARATION_HANDLER);
}
@Nonnull
public final SAXReaderSettings setDeclarationHandler (@Nullable final DeclHandler aDeclHandler)
{
return setPropertyValue (EXMLParserProperty.SAX_DECLARATION_HANDLER, aDeclHandler);
}
public boolean hasAnyProperties ()
{
return !m_aProperties.isEmpty ();
}
@Nullable
public Object getPropertyValue (@Nullable final EXMLParserProperty eProperty)
{
return eProperty == null ? null : m_aProperties.get (eProperty);
}
@Nonnull
@ReturnsMutableCopy
public ICommonsMap <EXMLParserProperty, Object> getAllPropertyValues ()
{
return m_aProperties.getClone ();
}
@Nonnull
public final SAXReaderSettings setPropertyValue (@Nonnull final EXMLParserProperty eProperty,
@Nullable final Object aPropertyValue)
{
ValueEnforcer.notNull (eProperty, "Property");
if (aPropertyValue != null &&
eProperty.getValueClass () != null &&
!eProperty.getValueClass ().isAssignableFrom (aPropertyValue.getClass ()))
if (LOGGER.isWarnEnabled ())
LOGGER.warn ("Setting the XML parser property '" +
eProperty +
"' to a value of " +
aPropertyValue.getClass () +
" will most likely not be interpreted!");
if (aPropertyValue != null)
m_aProperties.put (eProperty, aPropertyValue);
else
m_aProperties.remove (eProperty);
return this;
}
@Nonnull
public final SAXReaderSettings setPropertyValues (@Nullable final Map <EXMLParserProperty, ?> aProperties)
{
if (aProperties != null)
m_aProperties.putAll (aProperties);
return this;
}
@Nonnull
public final SAXReaderSettings removePropertyValue (@Nullable final EXMLParserProperty eProperty)
{
if (eProperty != null)
m_aProperties.removeObject (eProperty);
return this;
}
@Nonnull
public final SAXReaderSettings removeAllPropertyValues ()
{
m_aProperties.removeAll ();
return this;
}
@Nullable
public Locale getLocale ()
{
return (Locale) getPropertyValue (EXMLParserProperty.GENERAL_LOCALE);
}
@Nonnull
public SAXReaderSettings setLocale (@Nullable final Locale aLocale)
{
return setPropertyValue (EXMLParserProperty.GENERAL_LOCALE, aLocale);
}
public boolean hasAnyFeature ()
{
return !m_aFeatures.isEmpty ();
}
@Nullable
public Boolean getFeatureValue (@Nullable final EXMLParserFeature eFeature)
{
return eFeature == null ? null : m_aFeatures.get (eFeature);
}
@Nonnull
@ReturnsMutableCopy
public ICommonsMap <EXMLParserFeature, Boolean> getAllFeatureValues ()
{
return m_aFeatures.getClone ();
}
@Nonnull
public final SAXReaderSettings setFeatureValue (@Nonnull final EXMLParserFeature eFeature, final boolean bValue)
{
ValueEnforcer.notNull (eFeature, "Feature");
m_aFeatures.put (eFeature, Boolean.valueOf (bValue));
return this;
}
@Nonnull
public final SAXReaderSettings setFeatureValue (@Nonnull final EXMLParserFeature eFeature,
@Nullable final Boolean aValue)
{
ValueEnforcer.notNull (eFeature, "Feature");
if (aValue == null)
m_aFeatures.remove (eFeature);
else
m_aFeatures.put (eFeature, aValue);
return this;
}
/**
* Add multiple XML parser features at once.
*
* @param aValues
* The values to be added. May be <code>null</code>.
* @return this for chaining
*/
@Nonnull
public final SAXReaderSettings setFeatureValues (@Nullable final Map <EXMLParserFeature, Boolean> aValues)
{
if (aValues != null)
m_aFeatures.putAll (aValues);
return this;
}
@Nonnull
public final SAXReaderSettings removeFeature (@Nullable final EXMLParserFeature eFeature)
{
if (eFeature != null)
m_aFeatures.removeObject (eFeature);
return this;
}
@Nonnull
public final SAXReaderSettings removeFeatures (@Nullable final EXMLParserFeature... aFeatures)
{
if (aFeatures != null)
for (final EXMLParserFeature eFeature : aFeatures)
m_aFeatures.removeObject (eFeature);
return this;
}
@Nonnull
public final SAXReaderSettings removeAllFeatures ()
{
m_aFeatures.removeAll ();
return this;
}
public boolean requiresNewXMLParser ()
{
// Force a new XML parser?
if (m_bRequiresNewXMLParserExplicitly)
return true;
if (!m_aProperties.isEmpty () || !m_aFeatures.isEmpty ())
return true;
// Special case for JDK > 1.7.0_45 because of maximum entity expansion
// See http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html
return m_aEntityResolver != null;
}
@Nonnull
@ReturnsMutableObject
public CallbackList <IExceptionCallback <Throwable>> exceptionCallbacks ()
{
return m_aExceptionCallbacks;
}
public boolean isRequiresNewXMLParserExplicitly ()
{
return m_bRequiresNewXMLParserExplicitly;
}
@Nonnull
public final SAXReaderSettings setRequiresNewXMLParserExplicitly (final boolean bRequiresNewXMLParserExplicitly)
{
m_bRequiresNewXMLParserExplicitly = bRequiresNewXMLParserExplicitly;
return this;
}
@Nonnull
public SAXReaderSettings getClone ()
{
return new SAXReaderSettings (this);
}
public void applyToSAXReader (@Nonnull final org.xml.sax.XMLReader aParser)
{
ValueEnforcer.notNull (aParser, "Parser");
aParser.setContentHandler (getContentHandler ());
aParser.setDTDHandler (getDTDHandler ());
aParser.setEntityResolver (getEntityResolver ());
aParser.setErrorHandler (getErrorHandler ());
// Apply properties
if (hasAnyProperties ())
for (final Map.Entry <EXMLParserProperty, Object> aEntry : getAllPropertyValues ().entrySet ())
aEntry.getKey ().applyTo (aParser, aEntry.getValue ());
// Apply features
if (hasAnyFeature ())
for (final Map.Entry <EXMLParserFeature, Boolean> aEntry : getAllFeatureValues ().entrySet ())
aEntry.getKey ().applyTo (aParser, aEntry.getValue ().booleanValue ());
}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("entityResolver", m_aEntityResolver)
.append ("dtdHandler", m_aDTDHandler)
.append ("contentHandler", m_aContentHandler)
.append ("errorHandler", m_aErrorHandler)
.append ("properties", m_aProperties)
.append ("features", m_aFeatures)
.append ("exceptionHandler", m_aExceptionCallbacks)
.append ("requiresNewXMLParserExplicitly", m_bRequiresNewXMLParserExplicitly)
.getToString ();
}
/**
* Create a clone of the passed settings, depending on the parameter. If the
* parameter is <code>null</code> a new empty {@link SAXReaderSettings} object
* is created, otherwise a copy of the parameter is created.
*
* @param aOther
* The parameter to be used. May be <code>null</code>.
* @return Never <code>null</code>.
*/
@Nonnull
public static SAXReaderSettings createCloneOnDemand (@Nullable final ISAXReaderSettings aOther)
{
if (aOther == null)
{
// Create plain object
return new SAXReaderSettings ();
}
// Create a clone
return new SAXReaderSettings (aOther);
}
}
| {
"content_hash": "3081ea6dcdcf7c3e389841b0c937d8a3",
"timestamp": "",
"source": "github",
"line_count": 413,
"max_line_length": 122,
"avg_line_length": 30.062953995157386,
"alnum_prop": 0.7040914948453608,
"repo_name": "phax/ph-commons",
"id": "ed78d15b820520022503cc420b1288a80e39a86f",
"size": "13070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ph-xml/src/main/java/com/helger/xml/serialize/read/SAXReaderSettings.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "221283"
},
{
"name": "Java",
"bytes": "11003809"
},
{
"name": "XSLT",
"bytes": "3137"
}
],
"symlink_target": ""
} |
module.exports = function(app){
var controller = {};
var User = app.models.user;
controller.index = function(req, res){
var user = req.user;
res.json('users', {'user': user})
}
return controller;
}; | {
"content_hash": "e5f10fc3f1914c68bd15757ad2253d0b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 39,
"avg_line_length": 17.666666666666668,
"alnum_prop": 0.6415094339622641,
"repo_name": "waveoffice/socialwave",
"id": "33b45a852b6af1f91db4ddc315051c9912f70c2e",
"size": "242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/user.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "763826"
},
{
"name": "JavaScript",
"bytes": "2027754"
},
{
"name": "PHP",
"bytes": "172038"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--L
Copyright Oracle Inc
Distributed under the OSI-approved BSD 3-Clause License.
See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
L-->
<cgMDR:Non_Enumerated_Value_Domain xmlns:cgMDR="http://www.cancergrid.org/schema/cgMDR" item_registration_authority_identifier="GB-CANCERGRID" data_identifier="D1E576974" version="0.1">
<cgMDR:administered_item_administration_record>
<cgMDR:administrative_note>Auto generated during protege import</cgMDR:administrative_note>
<cgMDR:administrative_status>scheduledForReview</cgMDR:administrative_status>
<cgMDR:change_description/>
<cgMDR:creation_date>2006-08-08</cgMDR:creation_date>
<cgMDR:effective_date>2006-08-08</cgMDR:effective_date>
<cgMDR:explanatory_comment/>
<cgMDR:last_change_date>2006-08-08</cgMDR:last_change_date>
<cgMDR:origin/>
<cgMDR:registration_status>Incomplete</cgMDR:registration_status>
<cgMDR:unresolved_issue/>
</cgMDR:administered_item_administration_record>
<cgMDR:administered_by>GB-CANCERGRID-000005-1</cgMDR:administered_by>
<cgMDR:registered_by>GB-CANCERGRID-000009-1</cgMDR:registered_by>
<cgMDR:submitted_by>GB-CANCERGRID-000006-1</cgMDR:submitted_by>
<cgMDR:described_by>KNCSJG1HE</cgMDR:described_by>
<cgMDR:classified_by>http://www.cancergrid.org/ontologies/data-element-classification#D1E13683</cgMDR:classified_by>
<cgMDR:having>
<cgMDR:context_identifier>GB-CANCERGRID-000001-1</cgMDR:context_identifier>
<cgMDR:containing>
<cgMDR:language_section_language_identifier>
<cgMDR:country_identifier>GB</cgMDR:country_identifier>
<cgMDR:language_identifier>eng</cgMDR:language_identifier>
</cgMDR:language_section_language_identifier>
<cgMDR:name>Epirubicin value domain</cgMDR:name>
<cgMDR:definition_text>(90 mg/m2) Day 1</cgMDR:definition_text>
<cgMDR:preferred_designation>true</cgMDR:preferred_designation>
<cgMDR:definition_source_reference/>
</cgMDR:containing>
</cgMDR:having>
<cgMDR:typed_by>GB-CANCERGRID-000018-1</cgMDR:typed_by>
<cgMDR:value_domain_datatype>SMWJLQ091</cgMDR:value_domain_datatype>
<cgMDR:value_domain_unit_of_measure>mg</cgMDR:value_domain_unit_of_measure>
<cgMDR:representing>GB-CANCERGRID-D1E576973-0.1</cgMDR:representing>
</cgMDR:Non_Enumerated_Value_Domain> | {
"content_hash": "6583d39daf09dc950a52e9b9a0bbb89d",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 185,
"avg_line_length": 55.48888888888889,
"alnum_prop": 0.7164597517020425,
"repo_name": "NCIP/cadsr-cgmdr-nci-uk",
"id": "fe5fdeb62d4e651e2de97d4546e67da5d16a64c4",
"size": "2497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cancergrid/datasets/cancergrid-dataset/data/value_domain/GB-CANCERGRID-D1E576974-0.1.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "291811"
},
{
"name": "CSS",
"bytes": "46374"
},
{
"name": "Emacs Lisp",
"bytes": "1302"
},
{
"name": "Java",
"bytes": "12447025"
},
{
"name": "JavaScript",
"bytes": "659235"
},
{
"name": "Perl",
"bytes": "14339"
},
{
"name": "Python",
"bytes": "8079"
},
{
"name": "Shell",
"bytes": "47723"
},
{
"name": "XQuery",
"bytes": "592174"
},
{
"name": "XSLT",
"bytes": "441742"
}
],
"symlink_target": ""
} |
<?php
namespace DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRValueSet;
use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRValueSet\FHIRValueSetConcept;
/**
* Class FHIRValueSetConceptTest
* @package \DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRValueSet
*/
class FHIRValueSetConceptTest extends TestCase
{
public function testCanConstructTypeNoArgs()
{
$type = new FHIRValueSetConcept();
$this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRValueSet\FHIRValueSetConcept', $type);
}
}
| {
"content_hash": "a7a598426ab103cf5865c7226b9e870f",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 140,
"avg_line_length": 34.25,
"alnum_prop": 0.8116788321167884,
"repo_name": "dcarbone/php-fhir-generated",
"id": "564116535db1975dd4068fb164a44ea412f0dadb",
"size": "3575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DCarbone/PHPFHIRGenerated/DSTU2/PHPFHIRTests/FHIRElement/FHIRBackboneElement/FHIRValueSet/FHIRValueSetConceptTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "113066525"
}
],
"symlink_target": ""
} |
import * as TodoAction from "../actions/todoActions";
import * as TodoModel from "../models/todoModels";
import { handleActions } from 'redux-actions';
import Alert from "react-s-alert";
import * as immutable from "immutable";
const initialState = immutable.List<TodoModel.Todo>([]);
function AddTodoPayload(state = initialState, action) {
"use strict";
let todos = state.push(new TodoModel.Todo(action.payload.text));
Alert.success('TODOを追加しました。', {
position: 'top-right',
effect: 'scale',
beep: false,
timeout: 2000,
offset: 100,
});
return todos;
}
function ToggleTodoPayload(state = initialState, action) {
"use strict";
let targetIndex = state.findIndex((val) => {
return val.id === action.payload.id;
});
let target = state.get(targetIndex);
let newTarget = new TodoModel.Todo(target.text);
newTarget.id = target.id;
newTarget.completed = !target.completed;
Alert.success('TODO状態を更新しました。', {
position: 'top-right',
effect: 'scale',
beep: false,
timeout: 2000,
offset: 100,
});
let todos = state.set(targetIndex, newTarget);
return todos;
}
function DeleteTodoPayload(state = initialState, action) {
"use strict";
Alert.success('TODOを削除しました。', {
position: 'top-right',
effect: 'scale',
beep: false,
timeout: 2000,
offset: 100,
});
let targetIndex = state.findIndex((val) => {
return val.id === action.payload.id;
});
let todos = state.delete(targetIndex);
return todos;
}
export const todoActions = handleActions({
[TodoAction.Types.AddTodo] : AddTodoPayload,
[TodoAction.Types.ToggleTodo] : ToggleTodoPayload,
[TodoAction.Types.DeleteTodo] : DeleteTodoPayload,
}, initialState);
| {
"content_hash": "797784bb473caaf100e74dd07c3164c3",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 65,
"avg_line_length": 27.193548387096776,
"alnum_prop": 0.6915776986951364,
"repo_name": "slee-pasonatquila/ReactTypescriptDemo",
"id": "ae5e353fb856b574194c6f35975ddc1331780028",
"size": "1791",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/reducers/todoReducers.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2142"
},
{
"name": "HTML",
"bytes": "610"
},
{
"name": "JavaScript",
"bytes": "2205"
},
{
"name": "TypeScript",
"bytes": "13366"
}
],
"symlink_target": ""
} |
#ifndef INTERFACE_MODULES_REPORTCOLUMNMATRIXMISFIT_H
#define INTERFACE_MODULES_REPORTCOLUMNMATRIXMISFIT_H
#include "Interface/Modules/Math/ui_ReportColumnMatrixMisfit.h"
#include <Interface/Modules/Base/ModuleDialogGeneric.h>
#include <Interface/Modules/Math/share.h>
namespace SCIRun {
namespace Gui {
class SCISHARE ReportColumnMatrixMisfitDialog : public ModuleDialogGeneric,
public Ui::ReportColumnMatrixMisfit
{
Q_OBJECT
public:
ReportColumnMatrixMisfitDialog(const std::string& name,
SCIRun::Dataflow::Networks::ModuleStateHandle state,
QWidget* parent = 0);
private:
GuiStringTranslationMap methodMap_;
};
}
}
#endif
| {
"content_hash": "9af27707e5ed10796bc163bb34982977",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 79,
"avg_line_length": 23.233333333333334,
"alnum_prop": 0.7431850789096126,
"repo_name": "moritzdannhauer/SCIRunGUIPrototype",
"id": "f9eb64593a0c67f8a35114dad3794607984004f4",
"size": "1947",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Interface/Modules/Math/ReportColumnMatrixMisfitDialog.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1010"
},
{
"name": "C",
"bytes": "12851903"
},
{
"name": "C++",
"bytes": "15380635"
},
{
"name": "CMake",
"bytes": "598266"
},
{
"name": "DIGITAL Command Language",
"bytes": "8092"
},
{
"name": "GLSL",
"bytes": "41364"
},
{
"name": "JavaScript",
"bytes": "28938"
},
{
"name": "M4",
"bytes": "8656"
},
{
"name": "Makefile",
"bytes": "327302"
},
{
"name": "Mercury",
"bytes": "347"
},
{
"name": "Objective-C",
"bytes": "256584"
},
{
"name": "Perl",
"bytes": "3992"
},
{
"name": "Perl 6",
"bytes": "1716"
},
{
"name": "Python",
"bytes": "127158"
},
{
"name": "Roff",
"bytes": "2817"
},
{
"name": "Shell",
"bytes": "237009"
},
{
"name": "VCL",
"bytes": "4153"
},
{
"name": "XSLT",
"bytes": "14273"
}
],
"symlink_target": ""
} |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
tools:context=".ActivityStaticFragmentLayout" >
<fragment
android:name="edu.sdsmt.csc476.example.FragmentList"
android:id="@+id/fragmentList"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:name="edu.sdsmt.csc476.example.FragmentDetail"
android:id="@+id/fragmentDetail"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
| {
"content_hash": "d123fe92a9ccd87549a5134701c690ea",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 72,
"avg_line_length": 37.40909090909091,
"alnum_prop": 0.675577156743621,
"repo_name": "SDSMT-CSC476/AndroidStudio-Lecture-Examples",
"id": "e1f82d48d65700c3e47a3ca611f017aaa6d337a7",
"size": "823",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example.Fragments/app/src/main/res/layout/activity_dual_pane_static_layout.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "252676"
}
],
"symlink_target": ""
} |
#ifndef __DIRECTFB_H__
#define __DIRECTFB_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include <dfb_types.h>
#include <sys/time.h> /* struct timeval */
#include <directfb_keyboard.h>
#include <direct/interface.h>
/*
* Version handling.
*/
extern const unsigned int directfb_major_version;
extern const unsigned int directfb_minor_version;
extern const unsigned int directfb_micro_version;
extern const unsigned int directfb_binary_age;
extern const unsigned int directfb_interface_age;
/*
* Check for a certain DirectFB version.
* In case of an error a message is returned describing the mismatch.
*/
const char * DirectFBCheckVersion( unsigned int required_major,
unsigned int required_minor,
unsigned int required_micro );
/*
* Main interface of DirectFB, created by DirectFBCreate().
*/
DECLARE_INTERFACE( IDirectFB )
/*
* Interface to a surface object, being a graphics context for rendering and state control,
* buffer operations, palette access and sub area translate'n'clip logic.
*/
DECLARE_INTERFACE( IDirectFBSurface )
/*
* Interface for read/write access to the colors of a palette object and for cloning it.
*/
DECLARE_INTERFACE( IDirectFBPalette )
/*
* Input device interface for keymap access, event buffers and state queries.
*/
DECLARE_INTERFACE( IDirectFBInputDevice )
/*
* Layer interface for configuration, window stack usage or direct surface access, with shared/exclusive context.
*/
DECLARE_INTERFACE( IDirectFBDisplayLayer )
/*
* Interface to a window object, controlling appearance and focus, positioning and stacking,
* event buffers and surface access.
*/
DECLARE_INTERFACE( IDirectFBWindow )
/*
* Interface to a local event buffer to send/receive events, wait for events, abort waiting or reset buffer.
*/
DECLARE_INTERFACE( IDirectFBEventBuffer )
/*
* Font interface for getting metrics, measuring strings or single characters, query/choose encodings.
*/
DECLARE_INTERFACE( IDirectFBFont )
/*
* Interface to an image provider, retrieving information about the image and rendering it to a surface.
*/
DECLARE_INTERFACE( IDirectFBImageProvider )
/*
* Interface to a video provider for playback with advanced control and basic stream information.
*/
DECLARE_INTERFACE( IDirectFBVideoProvider )
/*
* Data buffer interface, providing unified access to different kinds of data storage and live feed.
*/
DECLARE_INTERFACE( IDirectFBDataBuffer )
/*
* Interface to different display outputs, encoders, connector settings, power management and synchronization.
*/
DECLARE_INTERFACE( IDirectFBScreen )
/*
* OpenGL context of a surface.
*/
DECLARE_INTERFACE( IDirectFBGL )
/*
* Return code of all interface methods and most functions
*
* Whenever a method has to return any information, it is done via output parameters. These are pointers to
* primitive types such as <i>int *ret_num</i>, enumerated types like <i>DFBBoolean *ret_enabled</i>, structures
* as in <i>DFBDisplayLayerConfig *ret_config</i>, just <i>void **ret_data</i> or other types...
*/
typedef enum {
/*
* Aliases for backward compatibility and uniform look in DirectFB code
*/
DFB_OK = DR_OK, /* No error occured. */
DFB_FAILURE = DR_FAILURE, /* A general or unknown error occured. */
DFB_INIT = DR_INIT, /* A general initialization error occured. */
DFB_BUG = DR_BUG, /* Internal bug or inconsistency has been detected. */
DFB_DEAD = DR_DEAD, /* Interface has a zero reference counter (available in debug mode). */
DFB_UNSUPPORTED = DR_UNSUPPORTED, /* The requested operation or an argument is (currently) not supported. */
DFB_UNIMPLEMENTED = DR_UNIMPLEMENTED, /* The requested operation is not implemented, yet. */
DFB_ACCESSDENIED = DR_ACCESSDENIED, /* Access to the resource is denied. */
DFB_INVAREA = DR_INVAREA, /* An invalid area has been specified or detected. */
DFB_INVARG = DR_INVARG, /* An invalid argument has been specified. */
DFB_NOSYSTEMMEMORY = DR_NOLOCALMEMORY, /* There's not enough system memory. */
DFB_NOSHAREDMEMORY = DR_NOSHAREDMEMORY, /* There's not enough shared memory. */
DFB_LOCKED = DR_LOCKED, /* The resource is (already) locked. */
DFB_BUFFEREMPTY = DR_BUFFEREMPTY, /* The buffer is empty. */
DFB_FILENOTFOUND = DR_FILENOTFOUND, /* The specified file has not been found. */
DFB_IO = DR_IO, /* A general I/O error occured. */
DFB_BUSY = DR_BUSY, /* The resource or device is busy. */
DFB_NOIMPL = DR_NOIMPL, /* No implementation for this interface or content type has been found. */
DFB_TIMEOUT = DR_TIMEOUT, /* The operation timed out. */
DFB_THIZNULL = DR_THIZNULL, /* 'thiz' pointer is NULL. */
DFB_IDNOTFOUND = DR_IDNOTFOUND, /* No resource has been found by the specified id. */
DFB_DESTROYED = DR_DESTROYED, /* The underlying object (e.g. a window or surface) has been destroyed. */
DFB_FUSION = DR_FUSION, /* Internal fusion error detected, most likely related to IPC resources. */
DFB_BUFFERTOOLARGE = DR_BUFFERTOOLARGE, /* Buffer is too large. */
DFB_INTERRUPTED = DR_INTERRUPTED, /* The operation has been interrupted. */
DFB_NOCONTEXT = DR_NOCONTEXT, /* No context available. */
DFB_TEMPUNAVAIL = DR_TEMPUNAVAIL, /* Temporarily unavailable. */
DFB_LIMITEXCEEDED = DR_LIMITEXCEEDED, /* Attempted to exceed limit, i.e. any kind of maximum size, count etc. */
DFB_NOSUCHMETHOD = DR_NOSUCHMETHOD, /* Requested method is not known, e.g. to remote site. */
DFB_NOSUCHINSTANCE = DR_NOSUCHINSTANCE, /* Requested instance is not known, e.g. to remote site. */
DFB_ITEMNOTFOUND = DR_ITEMNOTFOUND, /* No such item found. */
DFB_VERSIONMISMATCH = DR_VERSIONMISMATCH, /* Some versions didn't match. */
DFB_EOF = DR_EOF, /* Reached end of file. */
DFB_SUSPENDED = DR_SUSPENDED, /* The requested object is suspended. */
DFB_INCOMPLETE = DR_INCOMPLETE, /* The operation has been executed, but not completely. */
DFB_NOCORE = DR_NOCORE, /* Core part not available. */
/*
* DirectFB specific result codes starting at (after) this offset
*/
DFB__RESULT_OFFSET = D_RESULT_TYPE_BASE( 'D','F','B' ),
DFB_NOVIDEOMEMORY, /* There's not enough video memory. */
DFB_MISSINGFONT, /* No font has been set. */
DFB_MISSINGIMAGE, /* No image has been set. */
} DFBResult;
/*
* A boolean.
*/
typedef enum {
DFB_FALSE = 0,
DFB_TRUE = !DFB_FALSE
} DFBBoolean;
/*
* A point specified by x/y coordinates.
*/
typedef struct {
int x; /* X coordinate of it */
int y; /* Y coordinate of it */
} DFBPoint;
/*
* A horizontal line specified by x and width.
*/
typedef struct {
int x; /* X coordinate */
int w; /* width of span */
} DFBSpan;
/*
* A dimension specified by width and height.
*/
typedef struct {
int w; /* width of it */
int h; /* height of it */
} DFBDimension;
/*
* A rectangle specified by a point and a dimension.
*/
typedef struct {
int x; /* X coordinate of its top-left point */
int y; /* Y coordinate of its top-left point */
int w; /* width of it */
int h; /* height of it */
} DFBRectangle;
/*
* A rectangle specified by normalized coordinates.
*
* E.g. using 0.0, 0.0, 1.0, 1.0 would specify the whole screen.
*/
typedef struct {
float x; /* normalized X coordinate */
float y; /* normalized Y coordinate */
float w; /* normalized width */
float h; /* normalized height */
} DFBLocation;
/*
* A region specified by two points.
*
* The defined region includes both endpoints.
*/
typedef struct {
int x1; /* X coordinate of top-left point */
int y1; /* Y coordinate of top-left point */
int x2; /* X coordinate of lower-right point */
int y2; /* Y coordinate of lower-right point */
} DFBRegion;
/*
* Insets specify a distance from each edge of a rectangle.
*
* Positive values always mean 'outside'.
*/
typedef struct {
int l; /* distance from left edge */
int t; /* distance from top edge */
int r; /* distance from right edge */
int b; /* distance from bottom edge */
} DFBInsets;
/*
* A triangle specified by three points.
*/
typedef struct {
int x1; /* X coordinate of first edge */
int y1; /* Y coordinate of first edge */
int x2; /* X coordinate of second edge */
int y2; /* Y coordinate of second edge */
int x3; /* X coordinate of third edge */
int y3; /* Y coordinate of third edge */
} DFBTriangle;
/*
* A color defined by channels with 8bit each.
*/
typedef struct {
u8 a; /* alpha channel */
u8 r; /* red channel */
u8 g; /* green channel */
u8 b; /* blue channel */
} DFBColor;
/*
* A color key defined by R,G,B and eventually a color index.
*/
typedef struct {
u8 index; /* color index */
u8 r; /* red channel */
u8 g; /* green channel */
u8 b; /* blue channel */
} DFBColorKey;
/*
* A color defined by channels with 8bit each.
*/
typedef struct {
u8 a; /* alpha channel */
u8 y; /* luma channel */
u8 u; /* chroma channel */
u8 v; /* chroma channel */
} DFBColorYUV;
/*
* Macro to compare two points.
*/
#define DFB_POINT_EQUAL(a,b) ((a).x == (b).x && \
(a).y == (b).y)
/*
* Macro to compare two rectangles.
*/
#define DFB_RECTANGLE_EQUAL(a,b) ((a).x == (b).x && \
(a).y == (b).y && \
(a).w == (b).w && \
(a).h == (b).h)
/*
* Macro to compare two locations.
*/
#define DFB_LOCATION_EQUAL(a,b) ((a).x == (b).x && \
(a).y == (b).y && \
(a).w == (b).w && \
(a).h == (b).h)
/*
* Macro to compare two regions.
*/
#define DFB_REGION_EQUAL(a,b) ((a).x1 == (b).x1 && \
(a).y1 == (b).y1 && \
(a).x2 == (b).x2 && \
(a).y2 == (b).y2)
/*
* Macro to compare two colors.
*/
#define DFB_COLOR_EQUAL(x,y) ((x).a == (y).a && \
(x).r == (y).r && \
(x).g == (y).g && \
(x).b == (y).b)
/*
* Macro to compare two color keys.
*/
#define DFB_COLORKEY_EQUAL(x,y) ((x).index == (y).index && \
(x).r == (y).r && \
(x).g == (y).g && \
(x).b == (y).b)
/*
* Print a description of the result code along with an
* optional message that is put in front with a colon.
*/
DFBResult DirectFBError(
const char *msg, /* optional message */
DFBResult result /* result code to interpret */
);
/*
* Behaves like DirectFBError, but shuts down the calling application.
*/
DFBResult DirectFBErrorFatal(
const char *msg, /* optional message */
DFBResult result /* result code to interpret */
);
/*
* Returns a string describing 'result'.
*/
const char *DirectFBErrorString(
DFBResult result
);
/*
* Retrieves information about supported command-line flags in the
* form of a user-readable string formatted suitable to be printed
* as usage information.
*/
const char *DirectFBUsageString( void );
/*
* Parses the command-line and initializes some variables. You
* absolutely need to call this before doing anything else.
* Removes all options used by DirectFB from argv.
*/
DFBResult DirectFBInit(
int *argc, /* pointer to main()'s argc */
char *(*argv[]) /* pointer to main()'s argv */
);
/*
* Sets configuration parameters supported on command line and in
* config file. Can only be called before DirectFBCreate but after
* DirectFBInit.
*/
DFBResult DirectFBSetOption(
const char *name,
const char *value
);
/*
* Creates the super interface.
*/
DFBResult DirectFBCreate(
IDirectFB **interface /* pointer to the
created interface */
);
typedef unsigned int DFBScreenID;
typedef unsigned int DFBDisplayLayerID;
typedef unsigned int DFBDisplayLayerSourceID;
typedef unsigned int DFBWindowID;
typedef unsigned int DFBInputDeviceID;
typedef unsigned int DFBTextEncodingID;
typedef u32 DFBDisplayLayerIDs;
typedef unsigned int DFBColorID;
/*
* Predefined color IDs.
*/
#define DCID_PRIMARY 0
#define DCID_OUTLINE 1
/*
* Maximum number of color ids.
*/
#define DFB_COLOR_IDS_MAX 8
/*
* Maximum number of layer ids.
*/
#define DFB_DISPLAYLAYER_IDS_MAX 32
/*
* Adds the id to the bitmask of layer ids.
*/
#define DFB_DISPLAYLAYER_IDS_ADD(ids,id) (ids) |= (1 << (id))
/*
* Removes the id from the bitmask of layer ids.
*/
#define DFB_DISPLAYLAYER_IDS_REMOVE(ids,id) (ids) &= ~(1 << (id))
/*
* Checks if the bitmask of layer ids contains the id.
*/
#define DFB_DISPLAYLAYER_IDS_HAVE(ids,id) ((ids) & (1 << (id)))
/*
* Empties (clears) the bitmask of layer ids.
*/
#define DFB_DISPLAYLAYER_IDS_EMPTY(ids) (ids) = 0
/*
* Predefined text encoding IDs.
*/
#define DTEID_UTF8 0
#define DTEID_OTHER 1
/*
* The cooperative level controls the super interface's behaviour
* in functions like SetVideoMode or CreateSurface for the primary.
*/
typedef enum {
DFSCL_NORMAL = 0x00000000, /* Normal shared access, primary
surface will be the buffer of an
implicitly created window at the
resolution given by SetVideoMode().
*/
DFSCL_FULLSCREEN, /* Application grabs the primary layer,
SetVideoMode automates layer
control. Primary surface is the
primary layer surface. */
DFSCL_EXCLUSIVE /* All but the primary layer will be
disabled, the application has full
control over layers if desired,
other applications have no
input/output/control. Primary
surface is the primary layer
surface. */
} DFBCooperativeLevel;
/*
* Capabilities of a display layer.
*/
typedef enum {
DLCAPS_NONE = 0x00000000,
DLCAPS_SURFACE = 0x00000001, /* The layer has a surface that can be drawn to. This
may not be provided by layers that display realtime
data, e.g. from an MPEG decoder chip. Playback
control may be provided by an external API. */
DLCAPS_OPACITY = 0x00000002, /* The layer supports blending with layer(s) below
based on a global alpha factor. */
DLCAPS_ALPHACHANNEL = 0x00000004, /* The layer supports blending with layer(s) below
based on each pixel's alpha value. */
DLCAPS_SCREEN_LOCATION = 0x00000008, /* The layer location on the screen can be changed,
this includes position and size as normalized
values. The default is 0.0f, 0.0f, 1.0f, 1.0f.
Supports IDirectFBDisplayLayer::SetScreenLocation()
and IDirectFBDisplayLayer::SetScreenRectangle().
This implies DLCAPS_SCREEN_POSITION and _SIZE. */
DLCAPS_FLICKER_FILTERING = 0x00000010, /* Flicker filtering can be enabled for smooth output
on interlaced display devices. */
DLCAPS_DEINTERLACING = 0x00000020, /* The layer provides optional deinterlacing for
displaying interlaced video data on progressive
display devices. */
DLCAPS_SRC_COLORKEY = 0x00000040, /* A specific color can be declared as transparent. */
DLCAPS_DST_COLORKEY = 0x00000080, /* A specific color of layers below can be specified
as the color of the only locations where the layer
is visible. */
DLCAPS_BRIGHTNESS = 0x00000100, /* Adjustment of brightness is supported. */
DLCAPS_CONTRAST = 0x00000200, /* Adjustment of contrast is supported. */
DLCAPS_HUE = 0x00000400, /* Adjustment of hue is supported. */
DLCAPS_SATURATION = 0x00000800, /* Adjustment of saturation is supported. */
DLCAPS_LEVELS = 0x00001000, /* Adjustment of the layer's level
(z position) is supported. */
DLCAPS_FIELD_PARITY = 0x00002000, /* Field parity can be selected */
DLCAPS_WINDOWS = 0x00004000, /* Hardware window support. */
DLCAPS_SOURCES = 0x00008000, /* Sources can be selected. */
DLCAPS_ALPHA_RAMP = 0x00010000, /* Alpha values for formats with one or two alpha bits
can be chosen, i.e. using ARGB1555 or ARGB2554 the
user can define the meaning of the two or four
possibilities. In short, this feature provides a
lookup table for the alpha bits of these formats.
See also IDirectFBSurface::SetAlphaRamp(). */
DLCAPS_PREMULTIPLIED = 0x00020000, /* Surfaces with premultiplied alpha are supported. */
DLCAPS_SCREEN_POSITION = 0x00100000, /* The layer position on the screen can be changed.
Supports IDirectFBDisplayLayer::SetScreenPosition(). */
DLCAPS_SCREEN_SIZE = 0x00200000, /* The layer size (defined by its source rectangle)
can be scaled to a different size on the screen
(defined by its screen/destination rectangle or
its normalized size) and does not have to be 1:1
with it. */
DLCAPS_CLIP_REGIONS = 0x00400000, /* Supports IDirectFBDisplayLayer::SetClipRegions(). */
DLCAPS_ALL = 0x0073FFFF
} DFBDisplayLayerCapabilities;
/*
* Capabilities of a screen.
*/
typedef enum {
DSCCAPS_NONE = 0x00000000,
DSCCAPS_VSYNC = 0x00000001, /* Synchronization with the
vertical retrace supported. */
DSCCAPS_POWER_MANAGEMENT = 0x00000002, /* Power management supported. */
DSCCAPS_MIXERS = 0x00000010, /* Has mixers. */
DSCCAPS_ENCODERS = 0x00000020, /* Has encoders. */
DSCCAPS_OUTPUTS = 0x00000040, /* Has outputs. */
DSCCAPS_ALL = 0x00000073
} DFBScreenCapabilities;
/*
* Used to enable some capabilities like flicker filtering or colorkeying.
*/
typedef enum {
DLOP_NONE = 0x00000000, /* None of these. */
DLOP_ALPHACHANNEL = 0x00000001, /* Make usage of alpha channel
for blending on a pixel per
pixel basis. */
DLOP_FLICKER_FILTERING = 0x00000002, /* Enable flicker filtering. */
DLOP_DEINTERLACING = 0x00000004, /* Enable deinterlacing of an
interlaced (video) source. */
DLOP_SRC_COLORKEY = 0x00000008, /* Enable source color key. */
DLOP_DST_COLORKEY = 0x00000010, /* Enable dest. color key. */
DLOP_OPACITY = 0x00000020, /* Make usage of the global alpha
factor set by SetOpacity. */
DLOP_FIELD_PARITY = 0x00000040 /* Set field parity */
} DFBDisplayLayerOptions;
/*
* Layer Buffer Mode.
*/
typedef enum {
DLBM_UNKNOWN = 0x00000000,
DLBM_FRONTONLY = 0x00000001, /* no backbuffer */
DLBM_BACKVIDEO = 0x00000002, /* backbuffer in video memory */
DLBM_BACKSYSTEM = 0x00000004, /* backbuffer in system memory */
DLBM_TRIPLE = 0x00000008, /* triple buffering */
DLBM_WINDOWS = 0x00000010 /* no layer buffers at all,
using buffer of each window */
} DFBDisplayLayerBufferMode;
/*
* Flags defining which fields of a DFBSurfaceDescription are valid.
*/
typedef enum {
DSDESC_NONE = 0x00000000, /* none of these */
DSDESC_CAPS = 0x00000001, /* caps field is valid */
DSDESC_WIDTH = 0x00000002, /* width field is valid */
DSDESC_HEIGHT = 0x00000004, /* height field is valid */
DSDESC_PIXELFORMAT = 0x00000008, /* pixelformat field is valid */
DSDESC_PREALLOCATED = 0x00000010, /* Surface uses data that has been
preallocated by the application.
The field array 'preallocated'
has to be set using the first
element for the front buffer
and eventually the second one
for the back buffer. */
DSDESC_PALETTE = 0x00000020, /* Initialize the surfaces palette
with the entries specified in the
description. */
DSDESC_RESOURCE_ID = 0x00000100, /* user defined resource id for general purpose
surfaces is specified, or resource id of window,
layer, user is returned */
DSDESC_HINTS = 0x00000200, /* Flags for optimized allocation and pixel format selection are set.
See also DFBSurfaceHintFlags. */
DSDESC_ALL = 0x0000033F /* all of these */
} DFBSurfaceDescriptionFlags;
/*
* Flags defining which fields of a DFBPaletteDescription are valid.
*/
typedef enum {
DPDESC_CAPS = 0x00000001, /* Specify palette capabilities. */
DPDESC_SIZE = 0x00000002, /* Specify number of entries. */
DPDESC_ENTRIES = 0x00000004 /* Initialize the palette with the
entries specified in the
description. */
} DFBPaletteDescriptionFlags;
/*
* The surface capabilities.
*/
typedef enum {
DSCAPS_NONE = 0x00000000, /* None of these. */
DSCAPS_PRIMARY = 0x00000001, /* It's the primary surface. */
DSCAPS_SYSTEMONLY = 0x00000002, /* Surface data is permanently stored in system memory.<br>
There's no video memory allocation/storage. */
DSCAPS_VIDEOONLY = 0x00000004, /* Surface data is permanently stored in video memory.<br>
There's no system memory allocation/storage. */
DSCAPS_DOUBLE = 0x00000010, /* Surface is double buffered */
DSCAPS_SUBSURFACE = 0x00000020, /* Surface is just a sub area of another
one sharing the surface data. */
DSCAPS_INTERLACED = 0x00000040, /* Each buffer contains interlaced video (or graphics)
data consisting of two fields.<br>
Their lines are stored interleaved. One field's height
is a half of the surface's height. */
DSCAPS_SEPARATED = 0x00000080, /* For usage with DSCAPS_INTERLACED.<br>
DSCAPS_SEPARATED specifies that the fields are NOT
interleaved line by line in the buffer.<br>
The first field is followed by the second one. */
DSCAPS_STATIC_ALLOC = 0x00000100, /* The amount of video or system memory allocated for the
surface is never less than its initial value. This way
a surface can be resized (smaller and bigger up to the
initial size) without reallocation of the buffers. It's
useful for surfaces that need a guaranteed space in
video memory after resizing. */
DSCAPS_TRIPLE = 0x00000200, /* Surface is triple buffered. */
DSCAPS_PREMULTIPLIED = 0x00001000, /* Surface stores data with premultiplied alpha. */
DSCAPS_DEPTH = 0x00010000, /* A depth buffer is allocated. */
DSCAPS_SHARED = 0x00100000, /* The surface will be accessible among processes. */
DSCAPS_ROTATED = 0x01000000, /* The back buffers are allocated with swapped width/height (unimplemented!). */
DSCAPS_ALL = 0x011113F7, /* All of these. */
DSCAPS_FLIPPING = DSCAPS_DOUBLE | DSCAPS_TRIPLE /* Surface needs Flip() calls to make
updates/changes visible/usable. */
} DFBSurfaceCapabilities;
/*
* The palette capabilities.
*/
typedef enum {
DPCAPS_NONE = 0x00000000 /* None of these. */
} DFBPaletteCapabilities;
/*
* Flags controlling drawing commands.
*/
typedef enum {
DSDRAW_NOFX = 0x00000000, /* uses none of the effects */
DSDRAW_BLEND = 0x00000001, /* uses alpha from color */
DSDRAW_DST_COLORKEY = 0x00000002, /* write to destination only if the destination pixel
matches the destination color key */
DSDRAW_SRC_PREMULTIPLY = 0x00000004, /* multiplies the color's rgb channels by the alpha
channel before drawing */
DSDRAW_DST_PREMULTIPLY = 0x00000008, /* modulates the dest. color with the dest. alpha */
DSDRAW_DEMULTIPLY = 0x00000010, /* divides the color by the alpha before writing the
data to the destination */
DSDRAW_XOR = 0x00000020 /* bitwise xor the destination pixels with the
specified color after premultiplication */
} DFBSurfaceDrawingFlags;
/*
* Flags controlling blitting commands.
*/
typedef enum {
DSBLIT_NOFX = 0x00000000, /* uses none of the effects */
DSBLIT_BLEND_ALPHACHANNEL = 0x00000001, /* enables blending and uses
alphachannel from source */
DSBLIT_BLEND_COLORALPHA = 0x00000002, /* enables blending and uses
alpha value from color */
DSBLIT_COLORIZE = 0x00000004, /* modulates source color with
the color's r/g/b values */
DSBLIT_SRC_COLORKEY = 0x00000008, /* don't blit pixels matching the source color key */
DSBLIT_DST_COLORKEY = 0x00000010, /* write to destination only if the destination pixel
matches the destination color key */
DSBLIT_SRC_PREMULTIPLY = 0x00000020, /* modulates the source color with the (modulated)
source alpha */
DSBLIT_DST_PREMULTIPLY = 0x00000040, /* modulates the dest. color with the dest. alpha */
DSBLIT_DEMULTIPLY = 0x00000080, /* divides the color by the alpha before writing the
data to the destination */
DSBLIT_DEINTERLACE = 0x00000100, /* deinterlaces the source during blitting by reading
only one field (every second line of full
image) scaling it vertically by factor two */
DSBLIT_SRC_PREMULTCOLOR = 0x00000200, /* modulates the source color with the color alpha */
DSBLIT_XOR = 0x00000400, /* bitwise xor the destination pixels with the
source pixels after premultiplication */
DSBLIT_INDEX_TRANSLATION = 0x00000800, /* do fast indexed to indexed translation,
this flag is mutual exclusive with all others */
DSBLIT_ROTATE90 = 0x00002000, /* rotate the image by 90 degree */
DSBLIT_ROTATE180 = 0x00001000, /* rotate the image by 180 degree */
DSBLIT_ROTATE270 = 0x00004000, /* rotate the image by 270 degree */
DSBLIT_COLORKEY_PROTECT = 0x00010000, /* make sure written pixels don't match color key (internal only ATM) */
DSBLIT_SRC_MASK_ALPHA = 0x00100000, /* modulate source alpha channel with alpha channel from source mask,
see also IDirectFBSurface::SetSourceMask() */
DSBLIT_SRC_MASK_COLOR = 0x00200000, /* modulate source color channels with color channels from source mask,
see also IDirectFBSurface::SetSourceMask() */
} DFBSurfaceBlittingFlags;
/*
* Options for drawing and blitting operations. Not mandatory for acceleration.
*/
typedef enum {
DSRO_NONE = 0x00000000, /* None of these. */
DSRO_SMOOTH_UPSCALE = 0x00000001, /* Use interpolation for upscale StretchBlit(). */
DSRO_SMOOTH_DOWNSCALE = 0x00000002, /* Use interpolation for downscale StretchBlit(). */
DSRO_MATRIX = 0x00000004, /* Use the transformation matrix set via IDirectFBSurface::SetMatrix(). */
DSRO_ANTIALIAS = 0x00000008, /* Enable anti-aliasing for edges (alphablend must be enabled). */
DSRO_ALL = 0x0000000F /* All of these. */
} DFBSurfaceRenderOptions;
/*
* Mask of accelerated functions.
*/
typedef enum {
DFXL_NONE = 0x00000000, /* None of these. */
DFXL_FILLRECTANGLE = 0x00000001, /* FillRectangle() is accelerated. */
DFXL_DRAWRECTANGLE = 0x00000002, /* DrawRectangle() is accelerated. */
DFXL_DRAWLINE = 0x00000004, /* DrawLine() is accelerated. */
DFXL_FILLTRIANGLE = 0x00000008, /* FillTriangle() is accelerated. */
DFXL_BLIT = 0x00010000, /* Blit() and TileBlit() are accelerated. */
DFXL_STRETCHBLIT = 0x00020000, /* StretchBlit() is accelerated. */
DFXL_TEXTRIANGLES = 0x00040000, /* TextureTriangles() is accelerated. */
DFXL_DRAWSTRING = 0x01000000, /* DrawString() and DrawGlyph() are accelerated. */
DFXL_ALL = 0x0107000F, /* All drawing/blitting functions. */
DFXL_ALL_DRAW = 0x0000000F, /* All drawing functions. */
DFXL_ALL_BLIT = 0x01070000, /* All blitting functions. */
} DFBAccelerationMask;
/*
* @internal
*/
#define DFB_DRAWING_FUNCTION(a) ((a) & 0x0000FFFF)
/*
* @internal
*/
#define DFB_BLITTING_FUNCTION(a) ((a) & 0xFFFF0000)
/*
* Type of display layer for basic classification.
* Values may be or'ed together.
*/
typedef enum {
DLTF_NONE = 0x00000000, /* Unclassified, no specific type. */
DLTF_GRAPHICS = 0x00000001, /* Can be used for graphics output. */
DLTF_VIDEO = 0x00000002, /* Can be used for live video output.*/
DLTF_STILL_PICTURE = 0x00000004, /* Can be used for single frames. */
DLTF_BACKGROUND = 0x00000008, /* Can be used as a background layer.*/
DLTF_ALL = 0x0000000F /* All type flags set. */
} DFBDisplayLayerTypeFlags;
/*
* Type of input device for basic classification.
* Values may be or'ed together.
*/
typedef enum {
DIDTF_NONE = 0x00000000, /* Unclassified, no specific type. */
DIDTF_KEYBOARD = 0x00000001, /* Can act as a keyboard. */
DIDTF_MOUSE = 0x00000002, /* Can be used as a mouse. */
DIDTF_JOYSTICK = 0x00000004, /* Can be used as a joystick. */
DIDTF_REMOTE = 0x00000008, /* Is a remote control. */
DIDTF_VIRTUAL = 0x00000010, /* Is a virtual input device. */
DIDTF_ALL = 0x0000001F /* All type flags set. */
} DFBInputDeviceTypeFlags;
/*
* Basic input device features.
*/
typedef enum {
DICAPS_KEYS = 0x00000001, /* device supports key events */
DICAPS_AXES = 0x00000002, /* device supports axis events */
DICAPS_BUTTONS = 0x00000004, /* device supports button events */
DICAPS_ALL = 0x00000007 /* all capabilities */
} DFBInputDeviceCapabilities;
/*
* Identifier (index) for e.g. mouse or joystick buttons.
*/
typedef enum {
DIBI_LEFT = 0x00000000, /* left mouse button */
DIBI_RIGHT = 0x00000001, /* right mouse button */
DIBI_MIDDLE = 0x00000002, /* middle mouse button */
DIBI_FIRST = DIBI_LEFT, /* other buttons:
DIBI_FIRST + zero based index */
DIBI_LAST = 0x0000001F /* 32 buttons maximum */
} DFBInputDeviceButtonIdentifier;
/*
* Axis identifier (index) for e.g. mouse or joystick.
*
* The X, Y and Z axis are predefined. To access other axes,
* use DIAI_FIRST plus a zero based index, e.g. the 4th axis
* would be (DIAI_FIRST + 3).
*/
typedef enum {
DIAI_X = 0x00000000, /* X axis */
DIAI_Y = 0x00000001, /* Y axis */
DIAI_Z = 0x00000002, /* Z axis */
DIAI_FIRST = DIAI_X, /* other axis:
DIAI_FIRST + zero based index */
DIAI_LAST = 0x0000001F /* 32 axes maximum */
} DFBInputDeviceAxisIdentifier;
/*
* Flags defining which fields of a DFBWindowDescription are valid.
*/
typedef enum {
DWDESC_CAPS = 0x00000001, /* caps field is valid */
DWDESC_WIDTH = 0x00000002, /* width field is valid */
DWDESC_HEIGHT = 0x00000004, /* height field is valid */
DWDESC_PIXELFORMAT = 0x00000008, /* pixelformat field is valid */
DWDESC_POSX = 0x00000010, /* posx field is valid */
DWDESC_POSY = 0x00000020, /* posy field is valid */
DWDESC_SURFACE_CAPS = 0x00000040, /* Create the window surface with
special capabilities. */
DWDESC_PARENT = 0x00000080, /* This window has a parent according to parent_id field. */
DWDESC_OPTIONS = 0x00000100, /* Initial window options have been set. */
DWDESC_STACKING = 0x00000200, /* Initial stacking class has been set. */
DWDESC_TOPLEVEL_ID = 0x00000400, /* The top level window is set in toplevel_id field. */
DWDESC_RESOURCE_ID = 0x00001000, /* Resource id for window surface creation has been set. */
} DFBWindowDescriptionFlags;
/*
* Flags defining which fields of a DFBDataBufferDescription are valid.
*/
typedef enum {
DBDESC_FILE = 0x00000001, /* Create a static buffer for the
specified filename. */
DBDESC_MEMORY = 0x00000002 /* Create a static buffer for the
specified memory area. */
} DFBDataBufferDescriptionFlags;
/*
* Capabilities a window can have.
*/
typedef enum {
DWCAPS_NONE = 0x00000000, /* None of these. */
DWCAPS_ALPHACHANNEL = 0x00000001, /* The window has an alphachannel
for pixel-per-pixel blending. */
DWCAPS_DOUBLEBUFFER = 0x00000002, /* The window's surface is double
buffered. This is very useful
to avoid visibility of content
that is still in preparation.
Normally a window's content can
get visible before an update if
there is another reason causing
a window stack repaint. */
DWCAPS_INPUTONLY = 0x00000004, /* The window has no surface.
You can not draw to it but it
receives events */
DWCAPS_NODECORATION = 0x00000008, /* The window won't be decorated. */
DWCAPS_SUBWINDOW = 0x00000010, /* Not a top level window. */
DWCAPS_COLOR = 0x00000020, /* The window has no buffer;
it consumes no backing store.
It is filled with a constant color
and it receives events */
DWCAPS_NOFOCUS = 0x00000100, /* Window will never get focus or receive key events, unless it grabs them. */
DWCAPS_ALL = 0x0000013F /* All of these. */
} DFBWindowCapabilities;
/*
* Flags controlling the appearance and behaviour of the window.
*/
typedef enum {
DWOP_NONE = 0x00000000, /* none of these */
DWOP_COLORKEYING = 0x00000001, /* enable color key */
DWOP_ALPHACHANNEL = 0x00000002, /* enable alpha blending using the
window's alpha channel */
DWOP_OPAQUE_REGION = 0x00000004, /* overrides DWOP_ALPHACHANNEL for the
region set by SetOpaqueRegion() */
DWOP_SHAPED = 0x00000008, /* window doesn't receive mouse events for
invisible regions, must be used with
DWOP_ALPHACHANNEL or DWOP_COLORKEYING */
DWOP_KEEP_POSITION = 0x00000010, /* window can't be moved
with the mouse */
DWOP_KEEP_SIZE = 0x00000020, /* window can't be resized
with the mouse */
DWOP_KEEP_STACKING = 0x00000040, /* window can't be raised
or lowered with the mouse */
DWOP_GHOST = 0x00001000, /* never get focus or input,
clicks will go through,
implies DWOP_KEEP... */
DWOP_INDESTRUCTIBLE = 0x00002000, /* window can't be destroyed
by internal shortcut */
DWOP_INPUTONLY = 0x00004000, /* The window will be input only.
It will receive events but is not shown.
Note that toggling this bit will not
free/assign the window surface. */
DWOP_SCALE = 0x00010000, /* Surface won't be changed if window size on screen changes. The surface
can be resized separately using IDirectFBWindow::ResizeSurface(). */
DWOP_KEEP_ABOVE = 0x00100000, /* Keep window above parent window. */
DWOP_KEEP_UNDER = 0x00200000, /* Keep window under parent window. */
DWOP_FOLLOW_BOUNDS = 0x00400000, /* Follow window bounds from parent. */
DWOP_ALL = 0x0071707F /* all possible options */
} DFBWindowOptions;
/*
* The stacking class restricts the stacking order of windows.
*/
typedef enum {
DWSC_MIDDLE = 0x00000000, /* This is the default stacking
class of new windows. */
DWSC_UPPER = 0x00000001, /* Window is always above windows
in the middle stacking class.
Only windows that are also in
the upper stacking class can
get above them. */
DWSC_LOWER = 0x00000002 /* Window is always below windows
in the middle stacking class.
Only windows that are also in
the lower stacking class can
get below them. */
} DFBWindowStackingClass;
/*
* Flags describing how to load a font.
*
* These flags describe how a font is loaded and affect how the
* glyphs are drawn. There is no way to change this after the font
* has been loaded. If you need to render a font with different
* attributes, you have to create multiple FontProviders of the
* same font file.
*/
typedef enum {
DFFA_NONE = 0x00000000, /* none of these flags */
DFFA_NOKERNING = 0x00000001, /* don't use kerning */
DFFA_NOHINTING = 0x00000002, /* don't use hinting */
DFFA_MONOCHROME = 0x00000004, /* don't use anti-aliasing */
DFFA_NOCHARMAP = 0x00000008, /* no char map, glyph indices are
specified directly */
DFFA_FIXEDCLIP = 0x00000010, /* width fixed advance, clip to it */
DFFA_NOBITMAP = 0x00000020, /* ignore bitmap strikes; for
bitmap-only fonts this flag is
ignored */
DFFA_OUTLINED = 0x00000040
} DFBFontAttributes;
/*
* Flags defining which fields of a DFBFontDescription are valid.
*/
typedef enum {
DFDESC_ATTRIBUTES = 0x00000001, /* attributes field is valid */
DFDESC_HEIGHT = 0x00000002, /* height is specified */
DFDESC_WIDTH = 0x00000004, /* width is specified */
DFDESC_INDEX = 0x00000008, /* index is specified */
DFDESC_FIXEDADVANCE = 0x00000010, /* specify a fixed advance overriding
any character advance of fixed or
proportional fonts */
DFDESC_FRACT_HEIGHT = 0x00000020, /* fractional height is set */
DFDESC_FRACT_WIDTH = 0x00000040, /* fractional width is set */
DFDESC_OUTLINE_WIDTH = 0x00000080, /* outline width is set */
DFDESC_OUTLINE_OPACITY = 0x00000100, /* outline opacity is set */
DFDESC_ROTATION = 0x00002000, /* rotation is set */
} DFBFontDescriptionFlags;
/*
* Description of how to load glyphs from a font file.
*
* The attributes control how the glyphs are rendered. Width and height can be used to specify the
* desired face size in pixels. If you are loading a non-scalable font, you shouldn't specify a
* font size.
*
* Please note that the height value in the DFBFontDescription doesn't correspond to the height
* returned by IDirectFBFont::GetHeight().
*
* The index field controls which face is loaded from a font file that provides a collection of
* faces. This is rarely needed.
*
* Fractional sizes (fract_height and fract_width) are 26.6 fixed point integers and override
* the pixel sizes if both are specified.
*
* Outline parameters are ignored if DFFA_OUTLINED is not used (see DFBFontAttributes). To change the
* default values of 1.0 each use DFDESC_OUTLINE_WIDTH and/or DFDESC_OUTLINE_OPACITY.
*
* The rotation value is a 0.24 fixed point number of rotations. Use the macros DFB_DEGREES
* and DFB_RADIANS to convert from those units.
*/
typedef struct {
DFBFontDescriptionFlags flags;
DFBFontAttributes attributes;
int height;
int width;
unsigned int index;
int fixed_advance;
int fract_height;
int fract_width;
int outline_width; /* Outline width as 16.16 fixed point integer */
int outline_opacity; /* Outline opacity as 16.16 fixed point integer */
int rotation;
} DFBFontDescription;
#define DFB_DEGREES(deg) ((int)((deg)/360.0*(1<<24)))
#define DFB_RADIANS(rad) ((int)((rad)/(2.0*M_PI)*(1<<24)))
/*
* @internal
*
* Encodes format constants in the following way (bit 31 - 0):
*
* lkjj:hhgg | gfff:eeed | cccc:bbbb | baaa:aaaa
*
* a) pixelformat index<br>
* b) effective color (or index) bits per pixel of format<br>
* c) effective alpha bits per pixel of format<br>
* d) alpha channel present<br>
* e) bytes per "pixel in a row" (1/8 fragment, i.e. bits)<br>
* f) bytes per "pixel in a row" (decimal part, i.e. bytes)<br>
* g) smallest number of pixels aligned to byte boundary (minus one)<br>
* h) multiplier for planes minus one (1/4 fragment)<br>
* j) multiplier for planes minus one (decimal part)<br>
* k) color and/or alpha lookup table present<br>
* l) alpha channel is inverted
*/
#define DFB_SURFACE_PIXELFORMAT( index, color_bits, alpha_bits, has_alpha, \
row_bits, row_bytes, align, mul_f, mul_d, \
has_lut, inv_alpha ) \
( (((index ) & 0x7F) ) | \
(((color_bits) & 0x1F) << 7) | \
(((alpha_bits) & 0x0F) << 12) | \
(((has_alpha ) ? 1 :0) << 16) | \
(((row_bits ) & 0x07) << 17) | \
(((row_bytes ) & 0x07) << 20) | \
(((align ) & 0x07) << 23) | \
(((mul_f ) & 0x03) << 26) | \
(((mul_d ) & 0x03) << 28) | \
(((has_lut ) ? 1 :0) << 30) | \
(((inv_alpha ) ? 1 :0) << 31) )
/*
* Pixel format of a surface.
*/
typedef enum {
DSPF_UNKNOWN = 0x00000000, /* unknown or unspecified format */
/* 16 bit ARGB (2 byte, alpha 1@15, red 5@10, green 5@5, blue 5@0) */
DSPF_ARGB1555 = DFB_SURFACE_PIXELFORMAT( 0, 15, 1, 1, 0, 2, 0, 0, 0, 0, 0 ),
/* 16 bit RGB (2 byte, red 5@11, green 6@5, blue 5@0) */
DSPF_RGB16 = DFB_SURFACE_PIXELFORMAT( 1, 16, 0, 0, 0, 2, 0, 0, 0, 0, 0 ),
/* 24 bit RGB (3 byte, red 8@16, green 8@8, blue 8@0) */
DSPF_RGB24 = DFB_SURFACE_PIXELFORMAT( 2, 24, 0, 0, 0, 3, 0, 0, 0, 0, 0 ),
/* 24 bit RGB (4 byte, nothing@24, red 8@16, green 8@8, blue 8@0) */
DSPF_RGB32 = DFB_SURFACE_PIXELFORMAT( 3, 24, 0, 0, 0, 4, 0, 0, 0, 0, 0 ),
/* 32 bit ARGB (4 byte, alpha 8@24, red 8@16, green 8@8, blue 8@0) */
DSPF_ARGB = DFB_SURFACE_PIXELFORMAT( 4, 24, 8, 1, 0, 4, 0, 0, 0, 0, 0 ),
/* 8 bit alpha (1 byte, alpha 8@0), e.g. anti-aliased glyphs */
DSPF_A8 = DFB_SURFACE_PIXELFORMAT( 5, 0, 8, 1, 0, 1, 0, 0, 0, 0, 0 ),
/* 16 bit YUV (4 byte/ 2 pixel, macropixel contains CbYCrY [31:0]) */
DSPF_YUY2 = DFB_SURFACE_PIXELFORMAT( 6, 16, 0, 0, 0, 2, 0, 0, 0, 0, 0 ),
/* 8 bit RGB (1 byte, red 3@5, green 3@2, blue 2@0) */
DSPF_RGB332 = DFB_SURFACE_PIXELFORMAT( 7, 8, 0, 0, 0, 1, 0, 0, 0, 0, 0 ),
/* 16 bit YUV (4 byte/ 2 pixel, macropixel contains YCbYCr [31:0]) */
DSPF_UYVY = DFB_SURFACE_PIXELFORMAT( 8, 16, 0, 0, 0, 2, 0, 0, 0, 0, 0 ),
/* 12 bit YUV (8 bit Y plane followed by 8 bit quarter size U/V planes) */
DSPF_I420 = DFB_SURFACE_PIXELFORMAT( 9, 12, 0, 0, 0, 1, 0, 2, 0, 0, 0 ),
/* 12 bit YUV (8 bit Y plane followed by 8 bit quarter size V/U planes) */
DSPF_YV12 = DFB_SURFACE_PIXELFORMAT( 10, 12, 0, 0, 0, 1, 0, 2, 0, 0, 0 ),
/* 8 bit LUT (8 bit color and alpha lookup from palette) */
DSPF_LUT8 = DFB_SURFACE_PIXELFORMAT( 11, 8, 0, 1, 0, 1, 0, 0, 0, 1, 0 ),
/* 8 bit ALUT (1 byte, alpha 4@4, color lookup 4@0) */
DSPF_ALUT44 = DFB_SURFACE_PIXELFORMAT( 12, 4, 4, 1, 0, 1, 0, 0, 0, 1, 0 ),
/* 32 bit ARGB (4 byte, inv. alpha 8@24, red 8@16, green 8@8, blue 8@0) */
DSPF_AiRGB = DFB_SURFACE_PIXELFORMAT( 13, 24, 8, 1, 0, 4, 0, 0, 0, 0, 1 ),
/* 1 bit alpha (1 byte/ 8 pixel, most significant bit used first) */
DSPF_A1 = DFB_SURFACE_PIXELFORMAT( 14, 0, 1, 1, 1, 0, 7, 0, 0, 0, 0 ),
/* 12 bit YUV (8 bit Y plane followed by one 16 bit quarter size Cb|Cr [7:0|7:0] plane) */
DSPF_NV12 = DFB_SURFACE_PIXELFORMAT( 15, 12, 0, 0, 0, 1, 0, 2, 0, 0, 0 ),
/* 16 bit YUV (8 bit Y plane followed by one 16 bit half width Cb|Cr [7:0|7:0] plane) */
DSPF_NV16 = DFB_SURFACE_PIXELFORMAT( 16, 24, 0, 0, 0, 1, 0, 0, 1, 0, 0 ),
/* 16 bit ARGB (2 byte, alpha 2@14, red 5@9, green 5@4, blue 4@0) */
DSPF_ARGB2554 = DFB_SURFACE_PIXELFORMAT( 17, 14, 2, 1, 0, 2, 0, 0, 0, 0, 0 ),
/* 16 bit ARGB (2 byte, alpha 4@12, red 4@8, green 4@4, blue 4@0) */
DSPF_ARGB4444 = DFB_SURFACE_PIXELFORMAT( 18, 12, 4, 1, 0, 2, 0, 0, 0, 0, 0 ),
/* 16 bit RGBA (2 byte, red 4@12, green 4@8, blue 4@4, alpha 4@0) */
DSPF_RGBA4444 = DFB_SURFACE_PIXELFORMAT( 19, 12, 4, 1, 0, 2, 0, 0, 0, 0, 0 ),
/* 12 bit YUV (8 bit Y plane followed by one 16 bit quarter size Cr|Cb [7:0|7:0] plane) */
DSPF_NV21 = DFB_SURFACE_PIXELFORMAT( 20, 12, 0, 0, 0, 1, 0, 2, 0, 0, 0 ),
/* 32 bit AYUV (4 byte, alpha 8@24, Y 8@16, Cb 8@8, Cr 8@0) */
DSPF_AYUV = DFB_SURFACE_PIXELFORMAT( 21, 24, 8, 1, 0, 4, 0, 0, 0, 0, 0 ),
/* 4 bit alpha (1 byte/ 2 pixel, more significant nibble used first) */
DSPF_A4 = DFB_SURFACE_PIXELFORMAT( 22, 0, 4, 1, 4, 0, 1, 0, 0, 0, 0 ),
/* 1 bit alpha (3 byte/ alpha 1@18, red 6@12, green 6@6, blue 6@0) */
DSPF_ARGB1666 = DFB_SURFACE_PIXELFORMAT( 23, 18, 1, 1, 0, 3, 0, 0, 0, 0, 0 ),
/* 6 bit alpha (3 byte/ alpha 6@18, red 6@12, green 6@6, blue 6@0) */
DSPF_ARGB6666 = DFB_SURFACE_PIXELFORMAT( 24, 18, 6, 1, 0, 3, 0, 0, 0, 0, 0 ),
/* 6 bit RGB (3 byte/ red 6@12, green 6@6, blue 6@0) */
DSPF_RGB18 = DFB_SURFACE_PIXELFORMAT( 25, 18, 0, 0, 0, 3, 0, 0, 0, 0, 0 ),
/* 2 bit LUT (1 byte/ 4 pixel, 2 bit color and alpha lookup from palette) */
DSPF_LUT2 = DFB_SURFACE_PIXELFORMAT( 26, 2, 0, 1, 2, 0, 3, 0, 0, 1, 0 ),
/* 16 bit RGB (2 byte, nothing @12, red 4@8, green 4@4, blue 4@0) */
DSPF_RGB444 = DFB_SURFACE_PIXELFORMAT( 27, 12, 0, 0, 0, 2, 0, 0, 0, 0, 0 ),
/* 16 bit RGB (2 byte, nothing @15, red 5@10, green 5@5, blue 5@0) */
DSPF_RGB555 = DFB_SURFACE_PIXELFORMAT( 28, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0 ),
/* 16 bit BGR (2 byte, nothing @15, blue 5@10, green 5@5, red 5@0) */
DSPF_BGR555 = DFB_SURFACE_PIXELFORMAT( 29, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0 )
} DFBSurfacePixelFormat;
/* Number of pixelformats defined */
#define DFB_NUM_PIXELFORMATS 30
/* These macros extract information about the pixel format. */
#define DFB_PIXELFORMAT_INDEX(fmt) (((fmt) & 0x0000007F) )
#define DFB_COLOR_BITS_PER_PIXEL(fmt) (((fmt) & 0x00000F80) >> 7)
#define DFB_ALPHA_BITS_PER_PIXEL(fmt) (((fmt) & 0x0000F000) >> 12)
#define DFB_PIXELFORMAT_HAS_ALPHA(fmt) (((fmt) & 0x00010000) != 0)
#define DFB_BITS_PER_PIXEL(fmt) (((fmt) & 0x007E0000) >> 17)
#define DFB_BYTES_PER_PIXEL(fmt) (((fmt) & 0x00700000) >> 20)
#define DFB_BYTES_PER_LINE(fmt,width) (((((fmt) & 0x007E0000) >> 17) * (width) + 7) >> 3)
#define DFB_PIXELFORMAT_ALIGNMENT(fmt) (((fmt) & 0x03800000) >> 23)
#define DFB_PLANE_MULTIPLY(fmt,height) ((((((fmt) & 0x3C000000) >> 26) + 4) * (height)) >> 2)
#define DFB_PIXELFORMAT_IS_INDEXED(fmt) (((fmt) & 0x40000000) != 0)
#define DFB_PLANAR_PIXELFORMAT(fmt) (((fmt) & 0x3C000000) != 0)
#define DFB_PIXELFORMAT_INV_ALPHA(fmt) (((fmt) & 0x80000000) != 0)
/*
* Hint flags for optimized allocation, format selection etc.
*/
typedef enum {
DSHF_NONE = 0x00000000,
DSHF_LAYER = 0x00000001, /* Surface optimized for display layer usage */
DSHF_WINDOW = 0x00000002, /* Surface optimized for being a window buffer */
DSHF_CURSOR = 0x00000004, /* Surface optimized for usage as a cursor shape */
DSHF_FONT = 0x00000008, /* Surface optimized for text rendering */
DSHF_ALL = 0x0000000F
} DFBSurfaceHintFlags;
/*
* Description of the surface that is to be created.
*/
typedef struct {
DFBSurfaceDescriptionFlags flags; /* field validation */
DFBSurfaceCapabilities caps; /* capabilities */
int width; /* pixel width */
int height; /* pixel height */
DFBSurfacePixelFormat pixelformat; /* pixel format */
struct {
void *data; /* data pointer of existing buffer */
int pitch; /* pitch of buffer */
} preallocated[2];
struct {
const DFBColor *entries;
unsigned int size;
} palette; /* initial palette */
unsigned long resource_id; /* universal resource id, either user specified for general
purpose surfaces or id of layer or window */
DFBSurfaceHintFlags hints; /* usage hints for optimized allocation, format selection etc. */
} DFBSurfaceDescription;
/*
* Description of the palette that is to be created.
*/
typedef struct {
DFBPaletteDescriptionFlags flags; /* Validation of fields. */
DFBPaletteCapabilities caps; /* Palette capabilities. */
unsigned int size; /* Number of entries. */
const DFBColor *entries; /* Preset palette
entries. */
} DFBPaletteDescription;
#define DFB_DISPLAY_LAYER_DESC_NAME_LENGTH 32
/*
* Description of the display layer capabilities.
*/
typedef struct {
DFBDisplayLayerTypeFlags type; /* Classification of the display layer. */
DFBDisplayLayerCapabilities caps; /* Capability flags of the display layer. */
char name[DFB_DISPLAY_LAYER_DESC_NAME_LENGTH]; /* Display layer name. */
int level; /* Default level. */
int regions; /* Number of concurrent regions supported.<br>
-1 = unlimited,
0 = unknown/one,
>0 = actual number */
int sources; /* Number of selectable sources. */
int clip_regions; /* Number of clipping regions. */
} DFBDisplayLayerDescription;
/*
* Capabilities of a display layer source.
*/
typedef enum {
DDLSCAPS_NONE = 0x00000000, /* none of these */
DDLSCAPS_SURFACE = 0x00000001, /* source has an accessable surface */
DDLSCAPS_ALL = 0x00000001 /* all of these */
} DFBDisplayLayerSourceCaps;
#define DFB_DISPLAY_LAYER_SOURCE_DESC_NAME_LENGTH 24
/*
* Description of a display layer source.
*/
typedef struct {
DFBDisplayLayerSourceID source_id; /* ID of the source. */
char name[DFB_DISPLAY_LAYER_SOURCE_DESC_NAME_LENGTH]; /* Name of the source. */
DFBDisplayLayerSourceCaps caps; /* Capabilites of the source. */
} DFBDisplayLayerSourceDescription;
#define DFB_SCREEN_DESC_NAME_LENGTH 32
/*
* Description of the display encoder capabilities.
*/
typedef struct {
DFBScreenCapabilities caps; /* Capability flags of
the screen. */
char name[DFB_SCREEN_DESC_NAME_LENGTH]; /* Rough description. */
int mixers; /* Number of mixers
available. */
int encoders; /* Number of display
encoders available. */
int outputs; /* Number of output
connectors available. */
} DFBScreenDescription;
#define DFB_INPUT_DEVICE_DESC_NAME_LENGTH 32
#define DFB_INPUT_DEVICE_DESC_VENDOR_LENGTH 40
/*
* Description of the input device capabilities.
*/
typedef struct {
DFBInputDeviceTypeFlags type; /* classification of
input device */
DFBInputDeviceCapabilities caps; /* capabilities,
validates the
following fields */
int min_keycode; /* minimum hardware
keycode or -1 if
no differentiation
between hardware
keys is made */
int max_keycode; /* maximum hardware
keycode or -1 if
no differentiation
between hardware
keys is made */
DFBInputDeviceAxisIdentifier max_axis; /* highest axis
identifier */
DFBInputDeviceButtonIdentifier max_button; /* highest button
identifier */
char name[DFB_INPUT_DEVICE_DESC_NAME_LENGTH]; /* Device name */
char vendor[DFB_INPUT_DEVICE_DESC_VENDOR_LENGTH]; /* Device vendor */
int vendor_id; /* Vendor ID */
int product_id; /* Product ID */
} DFBInputDeviceDescription;
typedef enum {
DIAIF_NONE = 0x00000000,
DIAIF_ABS_MIN = 0x00000001,
DIAIF_ABS_MAX = 0x00000002,
DIAIF_ALL = 0x00000003
} DFBInputDeviceAxisInfoFlags;
typedef struct {
DFBInputDeviceAxisInfoFlags flags;
int abs_min;
int abs_max;
} DFBInputDeviceAxisInfo;
#define DFB_GRAPHICS_DRIVER_INFO_NAME_LENGTH 40
#define DFB_GRAPHICS_DRIVER_INFO_VENDOR_LENGTH 60
typedef struct {
int major; /* Major version */
int minor; /* Minor version */
char name[DFB_GRAPHICS_DRIVER_INFO_NAME_LENGTH]; /* Driver name */
char vendor[DFB_GRAPHICS_DRIVER_INFO_VENDOR_LENGTH]; /* Driver vendor */
} DFBGraphicsDriverInfo;
#define DFB_GRAPHICS_DEVICE_DESC_NAME_LENGTH 48
#define DFB_GRAPHICS_DEVICE_DESC_VENDOR_LENGTH 64
/*
* Description of the graphics device capabilities.
*/
typedef struct {
DFBAccelerationMask acceleration_mask; /* Accelerated functions */
DFBSurfaceBlittingFlags blitting_flags; /* Supported blitting flags */
DFBSurfaceDrawingFlags drawing_flags; /* Supported drawing flags */
unsigned int video_memory; /* Amount of video memory in bytes */
char name[DFB_GRAPHICS_DEVICE_DESC_NAME_LENGTH]; /* Device/Chipset name */
char vendor[DFB_GRAPHICS_DEVICE_DESC_VENDOR_LENGTH]; /* Device vendor */
DFBGraphicsDriverInfo driver;
} DFBGraphicsDeviceDescription;
/*
* Description of the window that is to be created.
*/
typedef struct {
DFBWindowDescriptionFlags flags; /* field validation */
DFBWindowCapabilities caps; /* capabilities */
int width; /* pixel width */
int height; /* pixel height */
DFBSurfacePixelFormat pixelformat; /* pixel format */
int posx; /* distance from left layer border */
int posy; /* distance from upper layer border */
DFBSurfaceCapabilities surface_caps; /* pixel format */
DFBWindowID parent_id; /* window id of parent window */
DFBWindowOptions options; /* initial window options */
DFBWindowStackingClass stacking; /* initial stacking class */
unsigned long resource_id; /* resource id used to create the window surface */
DFBWindowID toplevel_id; /* top level window, if != 0 window will be a sub window */
} DFBWindowDescription;
/*
* Description of a data buffer that is to be created.
*/
typedef struct {
DFBDataBufferDescriptionFlags flags; /* field validation */
const char *file; /* for file based data buffers */
struct {
const void *data; /* static data pointer */
unsigned int length; /* length of buffer */
} memory; /* memory based buffers */
} DFBDataBufferDescription;
/*
* Return value of callback function of enumerations.
*/
typedef enum {
DFENUM_OK = 0x00000000, /* Proceed with enumeration */
DFENUM_CANCEL = 0x00000001 /* Cancel enumeration */
} DFBEnumerationResult;
/*
* Called for each supported video mode.
*/
typedef DFBEnumerationResult (*DFBVideoModeCallback) (
int width,
int height,
int bpp,
void *callbackdata
);
/*
* Called for each existing screen.
* "screen_id" can be used to get an interface to the screen.
*/
typedef DFBEnumerationResult (*DFBScreenCallback) (
DFBScreenID screen_id,
DFBScreenDescription desc,
void *callbackdata
);
/*
* Called for each existing display layer.
* "layer_id" can be used to get an interface to the layer.
*/
typedef DFBEnumerationResult (*DFBDisplayLayerCallback) (
DFBDisplayLayerID layer_id,
DFBDisplayLayerDescription desc,
void *callbackdata
);
/*
* Called for each existing input device.
* "device_id" can be used to get an interface to the device.
*/
typedef DFBEnumerationResult (*DFBInputDeviceCallback) (
DFBInputDeviceID device_id,
DFBInputDeviceDescription desc,
void *callbackdata
);
/*
* Called for each block of continous data requested, e.g. by a
* Video Provider. Write as many data as you can but not more
* than specified by length. Return the number of bytes written
* or 'EOF' if no data is available anymore.
*/
typedef int (*DFBGetDataCallback) (
void *buffer,
unsigned int length,
void *callbackdata
);
/*
* Information about an IDirectFBVideoProvider.
*/
typedef enum {
DVCAPS_BASIC = 0x00000000, /* basic ops (PlayTo, Stop) */
DVCAPS_SEEK = 0x00000001, /* supports SeekTo */
DVCAPS_SCALE = 0x00000002, /* can scale the video */
DVCAPS_INTERLACED = 0x00000004, /* supports interlaced surfaces */
DVCAPS_SPEED = 0x00000008, /* supports changing playback speed */
DVCAPS_BRIGHTNESS = 0x00000010, /* supports Brightness adjustment */
DVCAPS_CONTRAST = 0x00000020, /* supports Contrast adjustment */
DVCAPS_HUE = 0x00000040, /* supports Hue adjustment */
DVCAPS_SATURATION = 0x00000080, /* supports Saturation adjustment */
DVCAPS_INTERACTIVE = 0x00000100, /* supports SendEvent */
DVCAPS_VOLUME = 0x00000200, /* supports Volume adjustment */
DVCAPS_EVENT = 0x00000400, /* supports the sending of events as video/audio data changes.*/
DVCAPS_ATTRIBUTES = 0x00000800, /* supports dynamic changing of atrributes.*/
DVCAPS_AUDIO_SEL = 0x00001000, /* Supportes chosing audio outputs.*/
} DFBVideoProviderCapabilities;
/*
* Information about the status of an IDirectFBVideoProvider.
*/
typedef enum {
DVSTATE_UNKNOWN = 0x00000000, /* unknown status */
DVSTATE_PLAY = 0x00000001, /* video provider is playing */
DVSTATE_STOP = 0x00000002, /* playback was stopped */
DVSTATE_FINISHED = 0x00000003, /* playback is finished */
DVSTATE_BUFFERING = 0x00000004 /* video provider is buffering,
playback is running */
} DFBVideoProviderStatus;
/*
* Flags controlling playback mode of a IDirectFBVideoProvider.
*/
typedef enum {
DVPLAY_NOFX = 0x00000000, /* normal playback */
DVPLAY_REWIND = 0x00000001, /* reverse playback */
DVPLAY_LOOPING = 0x00000002 /* automatically restart
playback when end-of-stream
is reached (gapless). */
} DFBVideoProviderPlaybackFlags;
/*
* Flags to allow Audio Unit selection.
*/
typedef enum {
DVAUDIOUNIT_NONE = 0x00000000, /* No Audio Unit */
DVAUDIOUNIT_ONE = 0x00000001, /* Audio Unit One */
DVAUDIOUNIT_TWO = 0x00000002, /* Audio Unit Two */
DVAUDIOUNIT_THREE = 0x00000004, /* Audio Unit Three */
DVAUDIOUNIT_FOUR = 0x00000008, /* Audio Unit Four */
DVAUDIOUNIT_ALL = 0x0000000F, /* Audio Unit One */
} DFBVideoProviderAudioUnits;
/*
* Flags defining which fields of a DFBColorAdjustment are valid.
*/
typedef enum {
DCAF_NONE = 0x00000000, /* none of these */
DCAF_BRIGHTNESS = 0x00000001, /* brightness field is valid */
DCAF_CONTRAST = 0x00000002, /* contrast field is valid */
DCAF_HUE = 0x00000004, /* hue field is valid */
DCAF_SATURATION = 0x00000008, /* saturation field is valid */
DCAF_ALL = 0x0000000F /* all of these */
} DFBColorAdjustmentFlags;
/*
* Color Adjustment used to adjust video colors.
*
* All fields are in the range 0x0 to 0xFFFF with
* 0x8000 as the default value (no adjustment).
*/
typedef struct {
DFBColorAdjustmentFlags flags;
u16 brightness;
u16 contrast;
u16 hue;
u16 saturation;
} DFBColorAdjustment;
/*
* <i><b>IDirectFB</b></i> is the main interface. It can be
* retrieved by a call to <i>DirectFBCreate</i>. It's the only
* interface with a global creation facility. Other interfaces
* are created by this interface or interfaces created by it.
*
* <b>Hardware capabilities</b> such as the amount of video
* memory or a list of supported drawing/blitting functions and
* flags can be retrieved. It also provides enumeration of all
* supported video modes.
*
* <b>Input devices</b> and <b>display layers</b> that are
* present can be enumerated via a callback mechanism. The
* callback is given the capabilities and the device or layer
* ID. An interface to specific input devices or display layers
* can be retrieved by passing the device or layer ID to the
* corresponding method.
*
* <b>Surfaces</b> for general purpose use can be created via
* <i>CreateSurface</i>. These surfaces are so called "offscreen
* surfaces" and could be used for sprites or icons.
*
* The <b>primary surface</b> is an abstraction and API shortcut
* for getting a surface for visual output. Fullscreen games for
* example have the whole screen as their primary
* surface. Alternatively fullscreen applications can be forced
* to run in a window. The primary surface is also created via
* <i>CreateSurface</i> but with the special capability
* DSCAPS_PRIMARY.
*
* The <b>cooperative level</b> selects the type of the primary
* surface. With a call to <i>SetCooperativeLevel</i> the
* application can choose between the surface of an implicitly
* created window and the surface of the primary layer
* (deactivating the window stack). The application doesn't need
* to have any extra functionality to run in a window. If the
* application is forced to run in a window the call to
* <i>SetCooperativeLevel</i> fails with DFB_ACCESSDENIED.
* Applications that want to be "window aware" shouldn't exit on
* this error.
*
* The <b>video mode</b> can be changed via <i>SetVideoMode</i>
* and is the size and depth of the primary surface, i.e. the
* screen when in exclusive cooperative level. Without exclusive
* access <i>SetVideoMode</i> sets the size of the implicitly
* created window.
*
* <b>Event buffers</b> can be created with an option to
* automatically attach input devices matching the specified
* capabilities. If DICAPS_NONE is passed an event buffer with
* nothing attached to is created. An event buffer can be
* attached to input devices and windows.
*
* <b>Fonts, images and videos</b> are created by this
* interface. There are different implementations for different
* content types. On creation a suitable implementation is
* automatically chosen.
*/
DEFINE_INTERFACE( IDirectFB,
/** Cooperative level, video mode **/
/*
* Puts the interface into the specified cooperative level.
*
* Function fails with DFB_LOCKED if another instance already
* is in a cooperative level other than DFSCL_NORMAL.
*/
DFBResult (*SetCooperativeLevel) (
IDirectFB *thiz,
DFBCooperativeLevel level
);
/*
* Switch the current video mode (primary layer).
*
* If in shared cooperative level this function sets the
* resolution of the window that is created implicitly for
* the primary surface.
*/
DFBResult (*SetVideoMode) (
IDirectFB *thiz,
int width,
int height,
int bpp
);
/** Hardware capabilities **/
/*
* Get a description of the graphics device.
*
* For more detailed information use
* IDirectFBSurface::GetAccelerationMask().
*/
DFBResult (*GetDeviceDescription) (
IDirectFB *thiz,
DFBGraphicsDeviceDescription *ret_desc
);
/*
* Enumerate supported video modes.
*
* Calls the given callback for all available video modes.
* Useful to select a certain mode to be used with
* IDirectFB::SetVideoMode().
*/
DFBResult (*EnumVideoModes) (
IDirectFB *thiz,
DFBVideoModeCallback callback,
void *callbackdata
);
/** Surfaces & Palettes **/
/*
* Create a surface matching the specified description.
*/
DFBResult (*CreateSurface) (
IDirectFB *thiz,
const DFBSurfaceDescription *desc,
IDirectFBSurface **ret_interface
);
/*
* Create a palette matching the specified description.
*
* Passing a NULL description creates a default palette with
* 256 entries filled with colors matching the RGB332 format.
*/
DFBResult (*CreatePalette) (
IDirectFB *thiz,
const DFBPaletteDescription *desc,
IDirectFBPalette **ret_interface
);
/** Screens **/
/*
* Enumerate all existing screen.
*
* Calls the given callback for each available screen.
* The callback is passed the screen id that can be
* used to retrieve an interface to a specific screen using
* IDirectFB::GetScreen().
*/
DFBResult (*EnumScreens) (
IDirectFB *thiz,
DFBScreenCallback callback,
void *callbackdata
);
/*
* Retrieve an interface to a specific screen.
*/
DFBResult (*GetScreen) (
IDirectFB *thiz,
DFBScreenID screen_id,
IDirectFBScreen **ret_interface
);
/** Display Layers **/
/*
* Enumerate all existing display layers.
*
* Calls the given callback for each available display
* layer. The callback is passed the layer id that can be
* used to retrieve an interface to a specific layer using
* IDirectFB::GetDisplayLayer().
*/
DFBResult (*EnumDisplayLayers) (
IDirectFB *thiz,
DFBDisplayLayerCallback callback,
void *callbackdata
);
/*
* Retrieve an interface to a specific display layer.
*
* The default <i>layer_id</i> is DLID_PRIMARY.
* Others can be obtained using IDirectFB::EnumDisplayLayers().
*/
DFBResult (*GetDisplayLayer) (
IDirectFB *thiz,
DFBDisplayLayerID layer_id,
IDirectFBDisplayLayer **ret_interface
);
/** Input Devices **/
/*
* Enumerate all existing input devices.
*
* Calls the given callback for all available input devices.
* The callback is passed the device id that can be used to
* retrieve an interface on a specific device using
* IDirectFB::GetInputDevice().
*/
DFBResult (*EnumInputDevices) (
IDirectFB *thiz,
DFBInputDeviceCallback callback,
void *callbackdata
);
/*
* Retrieve an interface to a specific input device.
*/
DFBResult (*GetInputDevice) (
IDirectFB *thiz,
DFBInputDeviceID device_id,
IDirectFBInputDevice **ret_interface
);
/*
* Create a buffer for events.
*
* Creates an empty event buffer without event sources connected to it.
*/
DFBResult (*CreateEventBuffer) (
IDirectFB *thiz,
IDirectFBEventBuffer **ret_buffer
);
/*
* Create a buffer for events with input devices connected.
*
* Creates an event buffer and attaches all input devices
* with matching capabilities. If no input devices match,
* e.g. by specifying DICAPS_NONE, a buffer will be returned
* that has no event sources connected to it.
*
* If global is DFB_FALSE events will only be delivered if this
* instance of IDirectFB has a focused primary (either running fullscreen
* or running in windowed mode with the window being focused).
*
* If global is DFB_TRUE no event will be discarded.
*/
DFBResult (*CreateInputEventBuffer) (
IDirectFB *thiz,
DFBInputDeviceCapabilities caps,
DFBBoolean global,
IDirectFBEventBuffer **ret_buffer
);
/** Media **/
/*
* Create an image provider for the specified file.
*/
DFBResult (*CreateImageProvider) (
IDirectFB *thiz,
const char *filename,
IDirectFBImageProvider **ret_interface
);
/*
* Create a video provider.
*/
DFBResult (*CreateVideoProvider) (
IDirectFB *thiz,
const char *filename,
IDirectFBVideoProvider **ret_interface
);
/*
* Load a font from the specified file given a description
* of how to load the glyphs.
*/
DFBResult (*CreateFont) (
IDirectFB *thiz,
const char *filename,
const DFBFontDescription *desc,
IDirectFBFont **ret_interface
);
/*
* Create a data buffer.
*
* If no description is specified (NULL) a streamed data buffer
* is created.
*/
DFBResult (*CreateDataBuffer) (
IDirectFB *thiz,
const DFBDataBufferDescription *desc,
IDirectFBDataBuffer **ret_interface
);
/** Clipboard **/
/*
* Set clipboard content.
*
* This is an experimental and intermediate API call that is
* supposed to change soon.
*
* If timestamp is non null DirectFB returns the time stamp
* that it associated with the new data.
*/
DFBResult (*SetClipboardData) (
IDirectFB *thiz,
const char *mime_type,
const void *data,
unsigned int size,
struct timeval *ret_timestamp
);
/*
* Get clipboard content.
*
* Memory returned in *ret_mimetype and *ret_data has to be freed.
*
* This is an experimental and intermediate API call that is
* supposed to change soon.
*/
DFBResult (*GetClipboardData) (
IDirectFB *thiz,
char **ret_mimetype,
void **ret_data,
unsigned int *ret_size
);
/*
* Get time stamp of last SetClipboardData call.
*
* This is an experimental and intermediate API call that is
* supposed to change soon.
*/
DFBResult (*GetClipboardTimeStamp) (
IDirectFB *thiz,
struct timeval *ret_timestamp
);
/** Misc **/
/*
* Suspend DirectFB, no other calls to DirectFB are allowed
* until Resume has been called.
*/
DFBResult (*Suspend) (
IDirectFB *thiz
);
/*
* Resume DirectFB, only to be called after Suspend.
*/
DFBResult (*Resume) (
IDirectFB *thiz
);
/*
* Wait until graphics card is idle,
* i.e. finish all drawing/blitting functions.
*/
DFBResult (*WaitIdle) (
IDirectFB *thiz
);
/*
* Wait for next vertical retrace.
*/
DFBResult (*WaitForSync) (
IDirectFB *thiz
);
/** Extensions **/
/*
* Load an implementation of a specific interface type.
*
* This methods loads an interface implementation of the specified
* <b>type</b> of interface, e.g. "IFusionSound".
*
* A specific implementation can be forced with the optional
* <b>implementation</b> argument.
*
* Implementations are passed <b>arg</b> during probing and construction.
*
* If an implementation has been successfully probed and the interface
* has been constructed, the resulting interface pointer is stored in
* <b>interface</b>.
*/
DFBResult (*GetInterface) (
IDirectFB *thiz,
const char *type,
const char *implementation,
void *arg,
void **ret_interface
);
/** Input Devices */
DFBResult (*RescanInputDevices) (
IDirectFB *thiz
);
)
/* predefined layer ids */
#define DLID_PRIMARY 0x0000
/* predefined layer source ids */
#define DLSID_SURFACE 0x0000
/* predefined screen ids */
#define DSCID_PRIMARY 0x0000
/* predefined input device ids */
#define DIDID_KEYBOARD 0x0000 /* primary keyboard */
#define DIDID_MOUSE 0x0001 /* primary mouse */
#define DIDID_JOYSTICK 0x0002 /* primary joystick */
#define DIDID_REMOTE 0x0003 /* primary remote control */
#define DIDID_ANY 0x0010 /* no primary device */
/*
* Cooperative level handling the access permissions.
*/
typedef enum {
DLSCL_SHARED = 0, /* shared access */
DLSCL_EXCLUSIVE, /* exclusive access,
fullscreen/mode switching */
DLSCL_ADMINISTRATIVE /* administrative access,
enumerate windows, control them */
} DFBDisplayLayerCooperativeLevel;
/*
* Background mode defining how to erase/initialize the area
* for a windowstack repaint
*/
typedef enum {
DLBM_DONTCARE = 0, /* do not clear the layer before
repainting the windowstack */
DLBM_COLOR, /* fill with solid color
(SetBackgroundColor) */
DLBM_IMAGE, /* use an image (SetBackgroundImage) */
DLBM_TILE /* use a tiled image (SetBackgroundImage) */
} DFBDisplayLayerBackgroundMode;
/*
* Layer configuration flags
*/
typedef enum {
DLCONF_NONE = 0x00000000,
DLCONF_WIDTH = 0x00000001,
DLCONF_HEIGHT = 0x00000002,
DLCONF_PIXELFORMAT = 0x00000004,
DLCONF_BUFFERMODE = 0x00000008,
DLCONF_OPTIONS = 0x00000010,
DLCONF_SOURCE = 0x00000020,
DLCONF_SURFACE_CAPS = 0x00000040,
DLCONF_ALL = 0x0000007F
} DFBDisplayLayerConfigFlags;
/*
* Layer configuration
*/
typedef struct {
DFBDisplayLayerConfigFlags flags; /* Which fields of the configuration are set */
int width; /* Pixel width */
int height; /* Pixel height */
DFBSurfacePixelFormat pixelformat; /* Pixel format */
DFBDisplayLayerBufferMode buffermode; /* Buffer mode */
DFBDisplayLayerOptions options; /* Enable capabilities */
DFBDisplayLayerSourceID source; /* Selected layer source */
DFBSurfaceCapabilities surface_caps; /* Choose surface capabilities, available:
INTERLACED, SEPARATED, PREMULTIPLIED. */
} DFBDisplayLayerConfig;
/*
* Screen Power Mode.
*/
typedef enum {
DSPM_ON = 0,
DSPM_STANDBY,
DSPM_SUSPEND,
DSPM_OFF
} DFBScreenPowerMode;
/*
* Capabilities of a mixer.
*/
typedef enum {
DSMCAPS_NONE = 0x00000000, /* None of these. */
DSMCAPS_FULL = 0x00000001, /* Can mix full tree as specified in the description. */
DSMCAPS_SUB_LEVEL = 0x00000002, /* Can set a maximum layer level, e.g. to exclude an OSD from VCR output. */
DSMCAPS_SUB_LAYERS = 0x00000004, /* Can select a number of layers individually as specified in the description. */
DSMCAPS_BACKGROUND = 0x00000008 /* Background color is configurable. */
} DFBScreenMixerCapabilities;
#define DFB_SCREEN_MIXER_DESC_NAME_LENGTH 24
/*
* Description of a mixer.
*/
typedef struct {
DFBScreenMixerCapabilities caps;
DFBDisplayLayerIDs layers; /* Visible layers if the
full tree is selected. */
int sub_num; /* Number of layers that can
be selected in sub mode. */
DFBDisplayLayerIDs sub_layers; /* Layers available for sub mode
with layer selection. */
char name[DFB_SCREEN_MIXER_DESC_NAME_LENGTH]; /* Mixer name */
} DFBScreenMixerDescription;
/*
* Flags for mixer configuration.
*/
typedef enum {
DSMCONF_NONE = 0x00000000, /* None of these. */
DSMCONF_TREE = 0x00000001, /* (Sub) tree is selected. */
DSMCONF_LEVEL = 0x00000002, /* Level is specified. */
DSMCONF_LAYERS = 0x00000004, /* Layer selection is set. */
DSMCONF_BACKGROUND = 0x00000010, /* Background color is set. */
DSMCONF_ALL = 0x00000017
} DFBScreenMixerConfigFlags;
/*
* (Sub) tree selection.
*/
typedef enum {
DSMT_UNKNOWN = 0x00000000, /* Unknown mode */
DSMT_FULL = 0x00000001, /* Full tree. */
DSMT_SUB_LEVEL = 0x00000002, /* Sub tree via maximum level. */
DSMT_SUB_LAYERS = 0x00000003 /* Sub tree via layer selection. */
} DFBScreenMixerTree;
/*
* Configuration of a mixer.
*/
typedef struct {
DFBScreenMixerConfigFlags flags; /* Validates struct members. */
DFBScreenMixerTree tree; /* Selected (sub) tree. */
int level; /* Max. level of sub level mode. */
DFBDisplayLayerIDs layers; /* Layers for sub layers mode. */
DFBColor background; /* Background color. */
} DFBScreenMixerConfig;
/*
* Capabilities of an output.
*/
typedef enum {
DSOCAPS_NONE = 0x00000000, /* None of these. */
DSOCAPS_CONNECTORS = 0x00000001, /* Output connectors are available. */
DSOCAPS_ENCODER_SEL = 0x00000010, /* Encoder can be selected. */
DSOCAPS_SIGNAL_SEL = 0x00000020, /* Signal(s) can be selected. */
DSOCAPS_CONNECTOR_SEL = 0x00000040, /* Connector(s) can be selected. */
DSOCAPS_SLOW_BLANKING = 0x00000080, /* Slow Blanking on outputs is supported. */
DSOCAPS_RESOLUTION = 0x00000100, /* Output Resolution can be changed. (global screen size)*/
DSOCAPS_ALL = 0x000001F1
} DFBScreenOutputCapabilities;
/*
* Type of output connector.
*/
typedef enum {
DSOC_UNKNOWN = 0x00000000, /* Unknown type */
DSOC_VGA = 0x00000001, /* VGA connector */
DSOC_SCART = 0x00000002, /* SCART connector */
DSOC_YC = 0x00000004, /* Y/C connector */
DSOC_CVBS = 0x00000008, /* CVBS connector */
DSOC_SCART2 = 0x00000010, /* 2nd SCART connector */
DSOC_COMPONENT = 0x00000020, /* Component video connector */
DSOC_HDMI = 0x00000040 /* HDMI connector */
} DFBScreenOutputConnectors;
/*
* Type of output signal.
*/
typedef enum {
DSOS_NONE = 0x00000000, /* No signal */
DSOS_VGA = 0x00000001, /* VGA signal */
DSOS_YC = 0x00000002, /* Y/C signal */
DSOS_CVBS = 0x00000004, /* CVBS signal */
DSOS_RGB = 0x00000008, /* R/G/B signal */
DSOS_YCBCR = 0x00000010, /* Y/Cb/Cr signal */
DSOS_HDMI = 0x00000020, /* HDMI signal */
DSOS_656 = 0x00000040 /* 656 Digital output signal */
} DFBScreenOutputSignals;
/*
* Type of slow blanking signalling.
*/
typedef enum {
DSOSB_OFF = 0x00000000, /* No signal */
DSOSB_16x9 = 0x00000001, /* 16*9 Widescreen signalling */
DSOSB_4x3 = 0x00000002, /* 4*3 widescreen signalling */
DSOSB_FOLLOW = 0x00000004, /* Follow signalling */
DSOSB_MONITOR = 0x00000008 /* Monitor */
} DFBScreenOutputSlowBlankingSignals;
/**
* Resolutions. TV Standards implies too many things:
* resolution / encoding / frequency.
*/
typedef enum {
DSOR_UNKNOWN = 0x00000000, /* Unknown Resolution */
DSOR_640_480 = 0x00000001, /* 640x480 Resolution */
DSOR_720_480 = 0x00000002, /* 720x480 Resolution */
DSOR_720_576 = 0x00000004, /* 720x576 Resolution */
DSOR_800_600 = 0x00000008, /* 800x600 Resolution */
DSOR_1024_768 = 0x00000010, /* 1024x768 Resolution */
DSOR_1152_864 = 0x00000020, /* 1152x864 Resolution */
DSOR_1280_720 = 0x00000040, /* 1280x720 Resolution */
DSOR_1280_768 = 0x00000080, /* 1280x768 Resolution */
DSOR_1280_960 = 0x00000100, /* 1280x960 Resolution */
DSOR_1280_1024 = 0x00000200, /* 1280x1024 Resolution */
DSOR_1400_1050 = 0x00000400, /* 1400x1050 Resolution */
DSOR_1600_1200 = 0x00000800, /* 1600x1200 Resolution */
DSOR_1920_1080 = 0x00001000, /* 1920x1080 Resolution */
DSOR_ALL = 0x00001FFF /* All Resolution */
} DFBScreenOutputResolution;
#define DFB_SCREEN_OUTPUT_DESC_NAME_LENGTH 24
/*
* Description of a screen output.
*/
typedef struct {
DFBScreenOutputCapabilities caps; /* Screen capabilities. */
DFBScreenOutputConnectors all_connectors; /* Output connectors. */
DFBScreenOutputSignals all_signals; /* Output signals. */
DFBScreenOutputResolution all_resolutions; /* Output Resolutions */
char name[DFB_SCREEN_OUTPUT_DESC_NAME_LENGTH]; /* Output name */
} DFBScreenOutputDescription;
/*
* Flags for screen output configuration.
*/
typedef enum {
DSOCONF_NONE = 0x00000000, /* None of these. */
DSOCONF_ENCODER = 0x00000001, /* Set encoder the signal(s) comes from. */
DSOCONF_SIGNALS = 0x00000002, /* Select signal(s) from encoder. */
DSOCONF_CONNECTORS = 0x00000004, /* Select output connector(s). */
DSOCONF_SLOW_BLANKING= 0x00000008, /* Can select slow blanking support. */
DSOCONF_RESOLUTION = 0x00000010, /* Can change output resolution */
DSOCONF_ALL = 0x0000001F
} DFBScreenOutputConfigFlags;
/*
* Configuration of an output.
*/
typedef struct {
DFBScreenOutputConfigFlags flags; /* Validates struct members. */
int encoder; /* Chosen encoder. */
DFBScreenOutputSignals out_signals; /* Selected encoder signal(s). */
DFBScreenOutputConnectors out_connectors; /* Selected output connector(s). */
DFBScreenOutputSlowBlankingSignals slow_blanking;/* Slow Blanking signals. */
DFBScreenOutputResolution resolution; /* Output Resolution */
} DFBScreenOutputConfig;
/*
* Capabilities of a display encoder.
*/
typedef enum {
DSECAPS_NONE = 0x00000000, /* None of these. */
DSECAPS_TV_STANDARDS = 0x00000001, /* TV standards can be selected. */
DSECAPS_TEST_PICTURE = 0x00000002, /* Test picture generation supported. */
DSECAPS_MIXER_SEL = 0x00000004, /* Mixer can be selected. */
DSECAPS_OUT_SIGNALS = 0x00000008, /* Different output signals are supported. */
DSECAPS_SCANMODE = 0x00000010, /* Can switch between interlaced and progressive output. */
DSECAPS_FREQUENCY = 0x00000020, /* Can switch between different frequencies. */
DSECAPS_BRIGHTNESS = 0x00000100, /* Adjustment of brightness is supported. */
DSECAPS_CONTRAST = 0x00000200, /* Adjustment of contrast is supported. */
DSECAPS_HUE = 0x00000400, /* Adjustment of hue is supported. */
DSECAPS_SATURATION = 0x00000800, /* Adjustment of saturation is supported. */
DSECAPS_CONNECTORS = 0x00001000, /* Select output connector(s). */
DSECAPS_SLOW_BLANKING = 0x00002000, /* Slow Blanking on outputs is supported. */
DSECAPS_RESOLUTION = 0x00004000, /* Different encoder resolutions supported */
DSECAPS_ALL = 0x00007f3f
} DFBScreenEncoderCapabilities;
/*
* Type of display encoder.
*/
typedef enum {
DSET_UNKNOWN = 0x00000000, /* Unknown type */
DSET_CRTC = 0x00000001, /* Encoder is a CRTC. */
DSET_TV = 0x00000002, /* TV output encoder. */
DSET_DIGITAL = 0x00000004 /* Support signals other than SD TV standards. */
} DFBScreenEncoderType;
/*
* TV standards.
*/
typedef enum {
DSETV_UNKNOWN = 0x00000000, /* Unknown standard */
DSETV_PAL = 0x00000001, /* PAL */
DSETV_NTSC = 0x00000002, /* NTSC */
DSETV_SECAM = 0x00000004, /* SECAM */
DSETV_PAL_60 = 0x00000008, /* PAL-60 */
DSETV_PAL_BG = 0x00000010, /* PAL BG support (specific) */
DSETV_PAL_I = 0x00000020, /* PAL I support (specific) */
DSETV_PAL_M = 0x00000040, /* PAL M support (specific) */
DSETV_PAL_N = 0x00000080, /* PAL N support (specific) */
DSETV_PAL_NC = 0x00000100, /* PAL NC support (specific) */
DSETV_NTSC_M_JPN = 0x00000200, /* NTSC_JPN support */
DSETV_NTSC_443 = 0x00000800, /* NTSC with 4.43MHz colour carrier */
DSETV_DIGITAL = 0x00000400, /* TV standards from the digital domain. specify resolution, scantype, frequency.*/
DSETV_ALL = 0x00000FFF /* All TV Standards*/
} DFBScreenEncoderTVStandards;
/*
* Scan modes.
*/
typedef enum {
DSESM_UNKNOWN = 0x00000000, /* Unknown mode */
DSESM_INTERLACED = 0x00000001, /* Interlaced scan mode */
DSESM_PROGRESSIVE = 0x00000002 /* Progressive scan mode */
} DFBScreenEncoderScanMode;
/*
* Frequency of output signal.
*/
typedef enum {
DSEF_UNKNOWN = 0x00000000, /* Unknown Frequency */
DSEF_25HZ = 0x00000001, /* 25 Hz Output. */
DSEF_29_97HZ = 0x00000002, /* 29.97 Hz Output. */
DSEF_50HZ = 0x00000004, /* 50 Hz Output. */
DSEF_59_94HZ = 0x00000008, /* 59.94 Hz Output. */
DSEF_60HZ = 0x00000010, /* 60 Hz Output. */
DSEF_75HZ = 0x00000020, /* 75 Hz Output. */
DSEF_30HZ = 0x00000040, /* 30 Hz Output. */
DSEF_24HZ = 0x00000080, /* 24 Hz Output. */
DSEF_23_976HZ = 0x00000100, /* 23.976 Hz Output. */
} DFBScreenEncoderFrequency;
#define DFB_SCREEN_ENCODER_DESC_NAME_LENGTH 24
/*
* Description of a display encoder.
*/
typedef struct {
DFBScreenEncoderCapabilities caps; /* Encoder capabilities. */
DFBScreenEncoderType type; /* Type of encoder. */
DFBScreenEncoderTVStandards tv_standards; /* Supported TV standards. */
DFBScreenOutputSignals out_signals; /* Supported output signals. */
DFBScreenOutputConnectors all_connectors; /* Supported output connectors */
DFBScreenOutputResolution all_resolutions; /* Supported Resolutions*/
char name[DFB_SCREEN_ENCODER_DESC_NAME_LENGTH]; /* Encoder name */
} DFBScreenEncoderDescription;
/*
* Flags for display encoder configuration.
*/
typedef enum {
DSECONF_NONE = 0x00000000, /* None of these. */
DSECONF_TV_STANDARD = 0x00000001, /* Set TV standard. */
DSECONF_TEST_PICTURE = 0x00000002, /* Set test picture mode. */
DSECONF_MIXER = 0x00000004, /* Select mixer. */
DSECONF_OUT_SIGNALS = 0x00000008, /* Select generated output signal(s). */
DSECONF_SCANMODE = 0x00000010, /* Select interlaced or progressive output. */
DSECONF_TEST_COLOR = 0x00000020, /* Set color for DSETP_SINGLE. */
DSECONF_ADJUSTMENT = 0x00000040, /* Set color adjustment. */
DSECONF_FREQUENCY = 0x00000080, /* Set Output Frequency*/
DSECONF_CONNECTORS = 0x00000100, /* Select output connector(s). */
DSECONF_SLOW_BLANKING = 0x00000200, /* Can select slow blanking support. */
DSECONF_RESOLUTION = 0x00000400, /* Can change resolution of the encoder.*/
DSECONF_ALL = 0x000007FF
} DFBScreenEncoderConfigFlags;
/*
* Test picture mode.
*/
typedef enum {
DSETP_OFF = 0x00000000, /* Disable test picture. */
DSETP_MULTI = 0x00000001, /* Show color bars. */
DSETP_SINGLE = 0x00000002, /* Whole screen as defined in configuration. */
DSETP_WHITE = 0x00000010, /* Whole screen (ff, ff, ff). */
DSETP_YELLOW = 0x00000020, /* Whole screen (ff, ff, 00). */
DSETP_CYAN = 0x00000030, /* Whole screen (00, ff, ff). */
DSETP_GREEN = 0x00000040, /* Whole screen (00, ff, 00). */
DSETP_MAGENTA = 0x00000050, /* Whole screen (ff, 00, ff). */
DSETP_RED = 0x00000060, /* Whole screen (ff, 00, 00). */
DSETP_BLUE = 0x00000070, /* Whole screen (00, 00, ff). */
DSETP_BLACK = 0x00000080 /* Whole screen (00, 00, 00). */
} DFBScreenEncoderTestPicture;
/*
* Configuration of a display encoder.
*/
typedef struct {
DFBScreenEncoderConfigFlags flags; /* Validates struct members. */
DFBScreenEncoderTVStandards tv_standard; /* TV standard. */
DFBScreenEncoderTestPicture test_picture; /* Test picture mode. */
int mixer; /* Selected mixer. */
DFBScreenOutputSignals out_signals; /* Generated output signals. */
DFBScreenOutputConnectors out_connectors; /* Selected output connector(s). */
DFBScreenOutputSlowBlankingSignals slow_blanking;/* Slow Blanking signals. */
DFBScreenEncoderScanMode scanmode; /* Interlaced or progressive output. */
DFBColor test_color; /* Color for DSETP_SINGLE. */
DFBColorAdjustment adjustment; /* Color adjustment. */
DFBScreenEncoderFrequency frequency; /* Selected Output Frequency*/
DFBScreenOutputResolution resolution; /* Selected Output resolution*/
} DFBScreenEncoderConfig;
/*******************
* IDirectFBScreen *
*******************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBScreen,
/** Retrieving information **/
/*
* Get the unique screen ID.
*/
DFBResult (*GetID) (
IDirectFBScreen *thiz,
DFBScreenID *ret_screen_id
);
/*
* Get a description of this screen, i.e. the capabilities.
*/
DFBResult (*GetDescription) (
IDirectFBScreen *thiz,
DFBScreenDescription *ret_desc
);
/*
* Get the screen's width and height in pixels.
*/
DFBResult (*GetSize) (
IDirectFBScreen *thiz,
int *ret_width,
int *ret_height
);
/** Display Layers **/
/*
* Enumerate all existing display layers for this screen.
*
* Calls the given callback for each available display
* layer. The callback is passed the layer id that can be
* used to retrieve an interface to a specific layer using
* IDirectFB::GetDisplayLayer().
*/
DFBResult (*EnumDisplayLayers) (
IDirectFBScreen *thiz,
DFBDisplayLayerCallback callback,
void *callbackdata
);
/** Power management **/
/*
* Set screen power mode.
*/
DFBResult (*SetPowerMode) (
IDirectFBScreen *thiz,
DFBScreenPowerMode mode
);
/** Synchronization **/
/*
* Wait for next vertical retrace.
*/
DFBResult (*WaitForSync) (
IDirectFBScreen *thiz
);
/** Mixers **/
/*
* Get a description of available mixers.
*
* All descriptions are written to the array pointed to by
* <b>ret_descriptions</b>. The number of mixers is returned by
* IDirectFBScreen::GetDescription().
*/
DFBResult (*GetMixerDescriptions) (
IDirectFBScreen *thiz,
DFBScreenMixerDescription *ret_descriptions
);
/*
* Get current mixer configuration.
*/
DFBResult (*GetMixerConfiguration) (
IDirectFBScreen *thiz,
int mixer,
DFBScreenMixerConfig *ret_config
);
/*
* Test mixer configuration.
*
* If configuration fails and 'ret_failed' is not NULL it will
* indicate which fields of the configuration caused the error.
*/
DFBResult (*TestMixerConfiguration) (
IDirectFBScreen *thiz,
int mixer,
const DFBScreenMixerConfig *config,
DFBScreenMixerConfigFlags *ret_failed
);
/*
* Set mixer configuration.
*/
DFBResult (*SetMixerConfiguration) (
IDirectFBScreen *thiz,
int mixer,
const DFBScreenMixerConfig *config
);
/** Encoders **/
/*
* Get a description of available display encoders.
*
* All descriptions are written to the array pointed to by
* <b>ret_descriptions</b>. The number of encoders is returned by
* IDirectFBScreen::GetDescription().
*/
DFBResult (*GetEncoderDescriptions) (
IDirectFBScreen *thiz,
DFBScreenEncoderDescription *ret_descriptions
);
/*
* Get current encoder configuration.
*/
DFBResult (*GetEncoderConfiguration) (
IDirectFBScreen *thiz,
int encoder,
DFBScreenEncoderConfig *ret_config
);
/*
* Test encoder configuration.
*
* If configuration fails and 'ret_failed' is not NULL it will
* indicate which fields of the configuration caused the
* error.
*/
DFBResult (*TestEncoderConfiguration) (
IDirectFBScreen *thiz,
int encoder,
const DFBScreenEncoderConfig *config,
DFBScreenEncoderConfigFlags *ret_failed
);
/*
* Set encoder configuration.
*/
DFBResult (*SetEncoderConfiguration) (
IDirectFBScreen *thiz,
int encoder,
const DFBScreenEncoderConfig *config
);
/** Outputs **/
/*
* Get a description of available outputs.
*
* All descriptions are written to the array pointed to by
* <b>ret_descriptions</b>. The number of outputs is returned by
* IDirectFBScreen::GetDescription().
*/
DFBResult (*GetOutputDescriptions) (
IDirectFBScreen *thiz,
DFBScreenOutputDescription *ret_descriptions
);
/*
* Get current output configuration.
*/
DFBResult (*GetOutputConfiguration) (
IDirectFBScreen *thiz,
int output,
DFBScreenOutputConfig *ret_config
);
/*
* Test output configuration.
*
* If configuration fails and 'ret_failed' is not NULL it will
* indicate which fields of the configuration caused the error.
*/
DFBResult (*TestOutputConfiguration) (
IDirectFBScreen *thiz,
int output,
const DFBScreenOutputConfig *config,
DFBScreenOutputConfigFlags *ret_failed
);
/*
* Set output configuration.
*/
DFBResult (*SetOutputConfiguration) (
IDirectFBScreen *thiz,
int output,
const DFBScreenOutputConfig *config
);
)
/*************************
* IDirectFBDisplayLayer *
*************************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBDisplayLayer,
/** Information **/
/*
* Get the unique layer ID.
*/
DFBResult (*GetID) (
IDirectFBDisplayLayer *thiz,
DFBDisplayLayerID *ret_layer_id
);
/*
* Get a description of this display layer, i.e. the capabilities.
*/
DFBResult (*GetDescription) (
IDirectFBDisplayLayer *thiz,
DFBDisplayLayerDescription *ret_desc
);
/*
* Get a description of available sources.
*
* All descriptions are written to the array pointed to by
* <b>ret_descriptions</b>. The number of sources is returned by
* IDirectFBDisplayLayer::GetDescription().
*/
DFBResult (*GetSourceDescriptions) (
IDirectFBDisplayLayer *thiz,
DFBDisplayLayerSourceDescription *ret_descriptions
);
/*
* For an interlaced display, this returns the currently inactive
* field: 0 for the top field, and 1 for the bottom field.
*
* The inactive field is the one you should draw to next to avoid
* tearing, the active field is the one currently being displayed.
*
* For a progressive output, this should always return 0. We should
* also have some other call to indicate whether the display layer
* is interlaced or progressive, but this is a start.
*/
DFBResult (*GetCurrentOutputField) (
IDirectFBDisplayLayer *thiz,
int *ret_field
);
/** Interfaces **/
/*
* Get an interface to layer's surface.
*
* Only available in exclusive mode.
*/
DFBResult (*GetSurface) (
IDirectFBDisplayLayer *thiz,
IDirectFBSurface **ret_interface
);
/*
* Get an interface to the screen to which the layer belongs.
*/
DFBResult (*GetScreen) (
IDirectFBDisplayLayer *thiz,
IDirectFBScreen **ret_interface
);
/** Configuration **/
/*
* Set cooperative level to get control over the layer
* or the windows within this layer.
*/
DFBResult (*SetCooperativeLevel) (
IDirectFBDisplayLayer *thiz,
DFBDisplayLayerCooperativeLevel level
);
/*
* Get current layer configuration.
*/
DFBResult (*GetConfiguration) (
IDirectFBDisplayLayer *thiz,
DFBDisplayLayerConfig *ret_config
);
/*
* Test layer configuration.
*
* If configuration fails and 'failed' is not NULL it will
* indicate which fields of the configuration caused the
* error.
*/
DFBResult (*TestConfiguration) (
IDirectFBDisplayLayer *thiz,
const DFBDisplayLayerConfig *config,
DFBDisplayLayerConfigFlags *ret_failed
);
/*
* Set layer configuration.
*
* Only available in exclusive or administrative mode.
*/
DFBResult (*SetConfiguration) (
IDirectFBDisplayLayer *thiz,
const DFBDisplayLayerConfig *config
);
/** Layout **/
/*
* Set location on screen as normalized values.
*
* So the whole screen is 0.0, 0.0, 1.0, 1.0.
*/
DFBResult (*SetScreenLocation) (
IDirectFBDisplayLayer *thiz,
float x,
float y,
float width,
float height
);
/*
* Set location on screen in pixels.
*/
DFBResult (*SetScreenPosition) (
IDirectFBDisplayLayer *thiz,
int x,
int y
);
/*
* Set location on screen in pixels.
*/
DFBResult (*SetScreenRectangle) (
IDirectFBDisplayLayer *thiz,
int x,
int y,
int width,
int height
);
/** Misc Settings **/
/*
* Set global alpha factor for blending with layer(s) below.
*/
DFBResult (*SetOpacity) (
IDirectFBDisplayLayer *thiz,
u8 opacity
);
/*
* Set the source rectangle.
*
* Only this part of the layer will be displayed.
*/
DFBResult (*SetSourceRectangle) (
IDirectFBDisplayLayer *thiz,
int x,
int y,
int width,
int height
);
/*
* For an interlaced display, this sets the field parity.
*
* field: 0 for top field first, and 1 for bottom field first.
*/
DFBResult (*SetFieldParity) (
IDirectFBDisplayLayer *thiz,
int field
);
/*
* Set the clipping region(s).
*
* If supported, this method sets the clipping <b>regions</b> that are used to
* to enable or disable visibility of parts of the layer. The <b>num_regions</b>
* must not exceed the limit as stated in the display layer description.
*
* If <b>positive</b> is DFB_TRUE the layer will be shown only in these regions,
* otherwise it's shown as usual except in these regions.
*
* Also see IDirectFBDisplayLayer::GetDescription().
*/
DFBResult (*SetClipRegions) (
IDirectFBDisplayLayer *thiz,
const DFBRegion *regions,
int num_regions,
DFBBoolean positive
);
/** Color keys **/
/*
* Set the source color key.
*
* If a pixel of the layer matches this color the underlying
* pixel is visible at this point.
*/
DFBResult (*SetSrcColorKey) (
IDirectFBDisplayLayer *thiz,
u8 r,
u8 g,
u8 b
);
/*
* Set the destination color key.
*
* The layer is only visible at points where the underlying
* pixel matches this color.
*/
DFBResult (*SetDstColorKey) (
IDirectFBDisplayLayer *thiz,
u8 r,
u8 g,
u8 b
);
/** Z Order **/
/*
* Get the current display layer level.
*
* The level describes the z axis position of a layer. The
* primary layer is always on level zero unless a special
* driver adds support for level adjustment on the primary
* layer. Layers above have a positive level, e.g. video
* overlays. Layers below have a negative level, e.g. video
* underlays or background layers.
*/
DFBResult (*GetLevel) (
IDirectFBDisplayLayer *thiz,
int *ret_level
);
/*
* Set the display layer level.
*
* Moves the layer to the specified level. The order of all
* other layers won't be changed. Note that only a few
* layers support level adjustment which is reflected by
* their capabilities.
*/
DFBResult (*SetLevel) (
IDirectFBDisplayLayer *thiz,
int level
);
/** Background handling **/
/*
* Set the erase behaviour for windowstack repaints.
*
* Only available in exclusive or administrative mode.
*/
DFBResult (*SetBackgroundMode) (
IDirectFBDisplayLayer *thiz,
DFBDisplayLayerBackgroundMode mode
);
/*
* Set the background image for the imaged background mode.
*
* Only available in exclusive or administrative mode.
*/
DFBResult (*SetBackgroundImage) (
IDirectFBDisplayLayer *thiz,
IDirectFBSurface *surface
);
/*
* Set the color for a solid colored background.
*
* Only available in exclusive or administrative mode.
*/
DFBResult (*SetBackgroundColor) (
IDirectFBDisplayLayer *thiz,
u8 r,
u8 g,
u8 b,
u8 a
);
/** Color adjustment **/
/*
* Get the layers color adjustment.
*/
DFBResult (*GetColorAdjustment) (
IDirectFBDisplayLayer *thiz,
DFBColorAdjustment *ret_adj
);
/*
* Set the layers color adjustment.
*
* Only available in exclusive or administrative mode.
*
* This function only has an effect if the underlying
* hardware supports this operation. Check the layers
* capabilities to find out if this is the case.
*/
DFBResult (*SetColorAdjustment) (
IDirectFBDisplayLayer *thiz,
const DFBColorAdjustment *adj
);
/** Windows **/
/*
* Create a window within this layer given a
* description of the window that is to be created.
*/
DFBResult (*CreateWindow) (
IDirectFBDisplayLayer *thiz,
const DFBWindowDescription *desc,
IDirectFBWindow **ret_interface
);
/*
* Retrieve an interface to an existing window.
*
* The window is identified by its window id.
*/
DFBResult (*GetWindow) (
IDirectFBDisplayLayer *thiz,
DFBWindowID window_id,
IDirectFBWindow **ret_interface
);
/** Cursor handling **/
/*
* Enable/disable the mouse cursor for this layer.
*
* Windows on a layer will only receive motion events if
* the cursor is enabled. This function is only available
* in exclusive/administrative mode.
*/
DFBResult (*EnableCursor) (
IDirectFBDisplayLayer *thiz,
int enable
);
/*
* Returns the x/y coordinates of the layer's mouse cursor.
*/
DFBResult (*GetCursorPosition) (
IDirectFBDisplayLayer *thiz,
int *ret_x,
int *ret_y
);
/*
* Move cursor to specified position.
*
* Handles movement like a real one, i.e. generates events.
*/
DFBResult (*WarpCursor) (
IDirectFBDisplayLayer *thiz,
int x,
int y
);
/*
* Set cursor acceleration.
*
* Sets the acceleration of cursor movements. The amount
* beyond the 'threshold' will be multiplied with the
* acceleration factor. The acceleration factor is
* 'numerator/denominator'.
*/
DFBResult (*SetCursorAcceleration) (
IDirectFBDisplayLayer *thiz,
int numerator,
int denominator,
int threshold
);
/*
* Set the cursor shape and the hotspot.
*/
DFBResult (*SetCursorShape) (
IDirectFBDisplayLayer *thiz,
IDirectFBSurface *shape,
int hot_x,
int hot_y
);
/*
* Set the cursor opacity.
*
* This function is especially useful if you want
* to hide the cursor but still want windows on this
* display layer to receive motion events. In this
* case, simply set the cursor opacity to zero.
*/
DFBResult (*SetCursorOpacity) (
IDirectFBDisplayLayer *thiz,
u8 opacity
);
/** Synchronization **/
/*
* Wait for next vertical retrace.
*/
DFBResult (*WaitForSync) (
IDirectFBDisplayLayer *thiz
);
/** Contexts **/
/*
* Switch the layer context.
*
* Switches to the shared context unless <b>exclusive</b> is DFB_TRUE
* and the cooperative level of this interface is DLSCL_EXCLUSIVE.
*/
DFBResult (*SwitchContext) (
IDirectFBDisplayLayer *thiz,
DFBBoolean exclusive
);
/** Rotation **/
/*
* Set the rotation of data within the layer.
*
* Only available in exclusive or administrative mode.
*
* Any <b>rotation</b> other than 0, 90, 180 or 270 is not supported.
*
* No layer hardware feature usage, only rotated blitting is used.
*/
DFBResult (*SetRotation) (
IDirectFBDisplayLayer *thiz,
int rotation
);
/*
* Get the rotation of data within the layer.
*/
DFBResult (*GetRotation) (
IDirectFBDisplayLayer *thiz,
int *ret_rotation
);
/** Windows **/
/*
* Retrieve an interface to an existing window.
*
* The window is identified by its surface' resource id.
*/
DFBResult (*GetWindowByResourceID) (
IDirectFBDisplayLayer *thiz,
unsigned long resource_id,
IDirectFBWindow **ret_interface
);
)
/*
* Flipping flags controlling the behaviour of IDirectFBSurface::Flip().
*/
typedef enum {
DSFLIP_NONE = 0x00000000, /* None of these. */
DSFLIP_WAIT = 0x00000001, /* Flip() returns upon vertical sync. Flipping is still done
immediately unless DSFLIP_ONSYNC is specified, too. */
DSFLIP_BLIT = 0x00000002, /* Copy from back buffer to front buffer rather than
just swapping these buffers. This behaviour is enforced
if the region passed to Flip() is not NULL or if the
surface being flipped is a sub surface. */
DSFLIP_ONSYNC = 0x00000004, /* Do the actual flipping upon the next vertical sync.
The Flip() method will still return immediately unless
DSFLIP_WAIT is specified, too. */
DSFLIP_PIPELINE = 0x00000008,
DSFLIP_ONCE = 0x00000010,
DSFLIP_WAITFORSYNC = DSFLIP_WAIT | DSFLIP_ONSYNC
} DFBSurfaceFlipFlags;
/*
* Flags controlling the text layout.
*/
typedef enum {
DSTF_LEFT = 0x00000000, /* left aligned */
DSTF_CENTER = 0x00000001, /* horizontally centered */
DSTF_RIGHT = 0x00000002, /* right aligned */
DSTF_TOP = 0x00000004, /* y specifies the top
instead of the baseline */
DSTF_BOTTOM = 0x00000008, /* y specifies the bottom
instead of the baseline */
DSTF_OUTLINE = 0x00000010, /* enables outline rendering if loaded font supports it */
DSTF_TOPLEFT = DSTF_TOP | DSTF_LEFT,
DSTF_TOPCENTER = DSTF_TOP | DSTF_CENTER,
DSTF_TOPRIGHT = DSTF_TOP | DSTF_RIGHT,
DSTF_BOTTOMLEFT = DSTF_BOTTOM | DSTF_LEFT,
DSTF_BOTTOMCENTER = DSTF_BOTTOM | DSTF_CENTER,
DSTF_BOTTOMRIGHT = DSTF_BOTTOM | DSTF_RIGHT
} DFBSurfaceTextFlags;
/*
* Flags defining the type of data access.
* These are important for surface swapping management.
*/
typedef enum {
DSLF_READ = 0x00000001, /* request read access while
surface is locked */
DSLF_WRITE = 0x00000002 /* Request write access. If
specified and surface has
a back buffer, it will be
used. Otherwise, the front
buffer is used. */
} DFBSurfaceLockFlags;
/*
* Available Porter/Duff rules.
*/
typedef enum {
/* pixel = (source * fs + destination * fd),
sa = source alpha,
da = destination alpha */
DSPD_NONE = 0, /* fs: sa fd: 1.0-sa (defaults) */
DSPD_CLEAR = 1, /* fs: 0.0 fd: 0.0 */
DSPD_SRC = 2, /* fs: 1.0 fd: 0.0 */
DSPD_SRC_OVER = 3, /* fs: 1.0 fd: 1.0-sa */
DSPD_DST_OVER = 4, /* fs: 1.0-da fd: 1.0 */
DSPD_SRC_IN = 5, /* fs: da fd: 0.0 */
DSPD_DST_IN = 6, /* fs: 0.0 fd: sa */
DSPD_SRC_OUT = 7, /* fs: 1.0-da fd: 0.0 */
DSPD_DST_OUT = 8, /* fs: 0.0 fd: 1.0-sa */
DSPD_SRC_ATOP = 9, /* fs: da fd: 1.0-sa */
DSPD_DST_ATOP = 10, /* fs: 1.0-da fd: sa */
DSPD_ADD = 11, /* fs: 1.0 fd: 1.0 */
DSPD_XOR = 12, /* fs: 1.0-da fd: 1.0-sa */
} DFBSurfacePorterDuffRule;
/*
* Blend functions to use for source and destination blending
*/
typedef enum {
/*
* pixel color = sc * cf[sf] + dc * cf[df]
* pixel alpha = sa * af[sf] + da * af[df]
* sc = source color
* sa = source alpha
* dc = destination color
* da = destination alpha
* sf = source blend function
* df = destination blend function
* cf[x] = color factor for blend function x
* af[x] = alpha factor for blend function x
*/
DSBF_UNKNOWN = 0, /* */
DSBF_ZERO = 1, /* cf: 0 af: 0 */
DSBF_ONE = 2, /* cf: 1 af: 1 */
DSBF_SRCCOLOR = 3, /* cf: sc af: sa */
DSBF_INVSRCCOLOR = 4, /* cf: 1-sc af: 1-sa */
DSBF_SRCALPHA = 5, /* cf: sa af: sa */
DSBF_INVSRCALPHA = 6, /* cf: 1-sa af: 1-sa */
DSBF_DESTALPHA = 7, /* cf: da af: da */
DSBF_INVDESTALPHA = 8, /* cf: 1-da af: 1-da */
DSBF_DESTCOLOR = 9, /* cf: dc af: da */
DSBF_INVDESTCOLOR = 10, /* cf: 1-dc af: 1-da */
DSBF_SRCALPHASAT = 11, /* cf: min(sa, 1-da) af: 1 */
} DFBSurfaceBlendFunction;
/*
* Transformed vertex of a textured triangle.
*/
typedef struct {
float x; /* Destination X coordinate (in pixels) */
float y; /* Destination Y coordinate (in pixels) */
float z; /* Z coordinate */
float w; /* W coordinate */
float s; /* Texture S coordinate */
float t; /* Texture T coordinate */
} DFBVertex;
/*
* Way of building triangles from the list of vertices.
*/
typedef enum {
DTTF_LIST, /* 0/1/2 3/4/5 6/7/8 ... */
DTTF_STRIP, /* 0/1/2 1/2/3 2/3/4 ... */
DTTF_FAN /* 0/1/2 0/2/3 0/3/4 ... */
} DFBTriangleFormation;
/*
* Flags controlling surface masks set via IDirectFBSurface::SetSourceMask().
*/
typedef enum {
DSMF_NONE = 0x00000000, /* None of these. */
DSMF_STENCIL = 0x00000001, /* Take <b>x</b> and <b>y</b> as fixed start coordinates in the mask. */
DSMF_ALL = 0x00000001, /* All of these. */
} DFBSurfaceMaskFlags;
/********************
* IDirectFBSurface *
********************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBSurface,
/** Retrieving information **/
/*
* Return the capabilities of this surface.
*/
DFBResult (*GetCapabilities) (
IDirectFBSurface *thiz,
DFBSurfaceCapabilities *ret_caps
);
/*
* Get the surface's position in pixels.
*/
DFBResult (*GetPosition) (
IDirectFBSurface *thiz,
int *ret_x,
int *ret_y
);
/*
* Get the surface's width and height in pixels.
*/
DFBResult (*GetSize) (
IDirectFBSurface *thiz,
int *ret_width,
int *ret_height
);
/*
* Created sub surfaces might be clipped by their parents,
* this function returns the resulting rectangle relative
* to this surface.
*
* For non sub surfaces this function returns
* { 0, 0, width, height }.
*/
DFBResult (*GetVisibleRectangle) (
IDirectFBSurface *thiz,
DFBRectangle *ret_rect
);
/*
* Get the current pixel format.
*/
DFBResult (*GetPixelFormat) (
IDirectFBSurface *thiz,
DFBSurfacePixelFormat *ret_format
);
/*
* Get a mask of drawing functions that are hardware
* accelerated with the current settings.
*
* If a source surface is specified the mask will also
* contain accelerated blitting functions. Note that there
* is no guarantee that these will actually be accelerated
* since the surface storage (video/system) is examined only
* when something actually gets drawn or blitted.
*/
DFBResult (*GetAccelerationMask) (
IDirectFBSurface *thiz,
IDirectFBSurface *source,
DFBAccelerationMask *ret_mask
);
/** Palette & Alpha Ramp **/
/*
* Get access to the surface's palette.
*
* Returns an interface that can be used to gain
* read and/or write access to the surface's palette.
*/
DFBResult (*GetPalette) (
IDirectFBSurface *thiz,
IDirectFBPalette **ret_interface
);
/*
* Change the surface's palette.
*/
DFBResult (*SetPalette) (
IDirectFBSurface *thiz,
IDirectFBPalette *palette
);
/*
* Set the alpha ramp for formats with one or two alpha bits.
*
* Either all four values or the first and the
* last one are used, depending on the format.
* Default values are: 0x00, 0x55, 0xaa, 0xff.
*/
DFBResult (*SetAlphaRamp) (
IDirectFBSurface *thiz,
u8 a0,
u8 a1,
u8 a2,
u8 a3
);
/** Buffer operations **/
/*
* Lock the surface for the access type specified.
*
* Returns a data pointer and the line pitch of it.<br>
* <br>
* <b>Note:</b> If the surface is double/triple buffered and
* the DSLF_WRITE flag is specified, the pointer is to the back
* buffer. In all other cases, the pointer is to the front
* buffer.
*/
DFBResult (*Lock) (
IDirectFBSurface *thiz,
DFBSurfaceLockFlags flags,
void **ret_ptr,
int *ret_pitch
);
/*
* Returns the framebuffer offset of a locked surface.
*
* The surface must exist in video memory.
*/
DFBResult (*GetFramebufferOffset) (
IDirectFBSurface *thiz,
int *offset
);
/*
* Unlock the surface after direct access.
*/
DFBResult (*Unlock) (
IDirectFBSurface *thiz
);
/*
* Flip/Update surface buffers.
*
* If no region is specified the whole surface is flipped,
* otherwise blitting is used to update the region.
* If surface capabilities don't include DSCAPS_FLIPPING,
* this method has the effect to make visible changes
* made to the surface contents.
*/
DFBResult (*Flip) (
IDirectFBSurface *thiz,
const DFBRegion *region,
DFBSurfaceFlipFlags flags
);
/*
* Set the active field.
*
* Interlaced surfaces consist of two fields. Software driven
* deinterlacing uses this method to manually switch the field
* that is displayed, e.g. scaled up vertically by two.
*/
DFBResult (*SetField) (
IDirectFBSurface *thiz,
int field
);
/*
* Clear the surface and its depth buffer if existent.
*
* Fills the whole (sub) surface with the specified color while ignoring
* drawing flags and color of the current state, but limited to the current clip.
*
* As with all drawing and blitting functions the backbuffer is written to.
* If you are initializing a double buffered surface you may want to clear both
* buffers by doing a Clear-Flip-Clear sequence.
*/
DFBResult (*Clear) (
IDirectFBSurface *thiz,
u8 r,
u8 g,
u8 b,
u8 a
);
/** Drawing/blitting control **/
/*
* Set the clipping region used to limit the area for
* drawing, blitting and text functions.
*
* If no region is specified (NULL passed) the clip is set
* to the surface extents (initial clip).
*/
DFBResult (*SetClip) (
IDirectFBSurface *thiz,
const DFBRegion *clip
);
/*
* Get the clipping region used to limit the area for
* drawing, blitting and text functions.
*/
DFBResult (*GetClip) (
IDirectFBSurface *thiz,
DFBRegion *ret_clip
);
/*
* Set the color used for drawing/text functions or
* alpha/color modulation (blitting functions).
*
* If you are not using the alpha value it should be set to
* 0xff to ensure visibility when the code is ported to or
* used for surfaces with an alpha channel.
*
* This method should be avoided for surfaces with an indexed
* pixelformat, e.g. DSPF_LUT8, otherwise an expensive search
* in the color/alpha lookup table occurs.
*/
DFBResult (*SetColor) (
IDirectFBSurface *thiz,
u8 r,
u8 g,
u8 b,
u8 a
);
/*
* Set the color like with SetColor() but using
* an index to the color/alpha lookup table.
*
* This method is only supported by surfaces with an
* indexed pixelformat, e.g. DSPF_LUT8. For these formats
* this method should be used instead of SetColor().
*/
DFBResult (*SetColorIndex) (
IDirectFBSurface *thiz,
unsigned int index
);
/*
* Set the blend function that applies to the source.
*/
DFBResult (*SetSrcBlendFunction) (
IDirectFBSurface *thiz,
DFBSurfaceBlendFunction function
);
/*
* Set the blend function that applies to the destination.
*/
DFBResult (*SetDstBlendFunction) (
IDirectFBSurface *thiz,
DFBSurfaceBlendFunction function
);
/*
* Set the source and destination blend function by
* specifying a Porter/Duff rule.
*/
DFBResult (*SetPorterDuff) (
IDirectFBSurface *thiz,
DFBSurfacePorterDuffRule rule
);
/*
* Set the source color key, i.e. the color that is excluded
* when blitting FROM this surface TO another that has
* source color keying enabled.
*/
DFBResult (*SetSrcColorKey) (
IDirectFBSurface *thiz,
u8 r,
u8 g,
u8 b
);
/*
* Set the source color key like with SetSrcColorKey() but using
* an index to the color/alpha lookup table.
*
* This method is only supported by surfaces with an
* indexed pixelformat, e.g. DSPF_LUT8. For these formats
* this method should be used instead of SetSrcColorKey().
*/
DFBResult (*SetSrcColorKeyIndex) (
IDirectFBSurface *thiz,
unsigned int index
);
/*
* Set the destination color key, i.e. the only color that
* gets overwritten by drawing and blitting to this surface
* when destination color keying is enabled.
*/
DFBResult (*SetDstColorKey) (
IDirectFBSurface *thiz,
u8 r,
u8 g,
u8 b
);
/*
* Set the destination color key like with SetDstColorKey() but using
* an index to the color/alpha lookup table.
*
* This method is only supported by surfaces with an
* indexed pixelformat, e.g. DSPF_LUT8. For these formats
* this method should be used instead of SetDstColorKey().
*/
DFBResult (*SetDstColorKeyIndex) (
IDirectFBSurface *thiz,
unsigned int index
);
/** Blitting functions **/
/*
* Set the flags for all subsequent blitting commands.
*/
DFBResult (*SetBlittingFlags) (
IDirectFBSurface *thiz,
DFBSurfaceBlittingFlags flags
);
/*
* Blit an area from the source to this surface.
*
* Pass a NULL rectangle to use the whole source surface.
* Source may be the same surface.
*/
DFBResult (*Blit) (
IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *source_rect,
int x,
int y
);
/*
* Blit an area from the source tiled to this surface.
*
* Pass a NULL rectangle to use the whole source surface.
* Source may be the same surface.
*/
DFBResult (*TileBlit) (
IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *source_rect,
int x,
int y
);
/*
* Blit a bunch of areas at once.
*
* Source may be the same surface.
*/
DFBResult (*BatchBlit) (
IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *source_rects,
const DFBPoint *dest_points,
int num
);
/*
* Blit an area scaled from the source to the destination
* rectangle.
*
* Pass a NULL rectangle to use the whole source surface.
*/
DFBResult (*StretchBlit) (
IDirectFBSurface *thiz,
IDirectFBSurface *source,
const DFBRectangle *source_rect,
const DFBRectangle *destination_rect
);
/*
* Preliminary texture mapping support.
*
* Maps a <b>texture</b> onto triangles being built
* from <b>vertices</b> according to the chosen <b>formation</b>.
*
* Optional <b>indices</b> can be used to avoid rearrangement of vertex lists,
* otherwise the vertex list is processed consecutively, i.e. as if <b>indices</b>
* are ascending numbers starting at zero.
*
* Either the number of <b>indices</b> (if non NULL) or the number of <b>vertices</b> is
* specified by <b>num</b> and has to be three at least. If the chosen <b>formation</b>
* is DTTF_LIST it also has to be a multiple of three.
*/
DFBResult (*TextureTriangles) (
IDirectFBSurface *thiz,
IDirectFBSurface *texture,
const DFBVertex *vertices,
const int *indices,
int num,
DFBTriangleFormation formation
);
/** Drawing functions **/
/*
* Set the flags for all subsequent drawing commands.
*/
DFBResult (*SetDrawingFlags) (
IDirectFBSurface *thiz,
DFBSurfaceDrawingFlags flags
);
/*
* Fill the specified rectangle with the given color
* following the specified flags.
*/
DFBResult (*FillRectangle) (
IDirectFBSurface *thiz,
int x,
int y,
int w,
int h
);
/*
* Draw an outline of the specified rectangle with the given
* color following the specified flags.
*/
DFBResult (*DrawRectangle) (
IDirectFBSurface *thiz,
int x,
int y,
int w,
int h
);
/*
* Draw a line from one point to the other with the given color
* following the drawing flags.
*/
DFBResult (*DrawLine) (
IDirectFBSurface *thiz,
int x1,
int y1,
int x2,
int y2
);
/*
* Draw 'num_lines' lines with the given color following the
* drawing flags. Each line specified by a DFBRegion.
*/
DFBResult (*DrawLines) (
IDirectFBSurface *thiz,
const DFBRegion *lines,
unsigned int num_lines
);
/*
* Fill a non-textured triangle.
*/
DFBResult (*FillTriangle) (
IDirectFBSurface *thiz,
int x1,
int y1,
int x2,
int y2,
int x3,
int y3
);
/*
* Fill a bunch of rectangles with a single call.
*
* Fill <b>num</b> rectangles with the current color following the
* drawing flags. Each rectangle specified by a DFBRectangle.
*/
DFBResult (*FillRectangles) (
IDirectFBSurface *thiz,
const DFBRectangle *rects,
unsigned int num
);
/*
* Fill spans specified by x and width.
*
* Fill <b>num</b> spans with the given color following the
* drawing flags. Each span is specified by a DFBSpan.
*/
DFBResult (*FillSpans) (
IDirectFBSurface *thiz,
int y,
const DFBSpan *spans,
unsigned int num
);
/*
* Fill a bunch of triangles with a single call.
*
* Fill <b>num</b> triangles with the current color following the
* drawing flags. Each triangle specified by a DFBTriangle.
*/
DFBResult (*FillTriangles) (
IDirectFBSurface *thiz,
const DFBTriangle *tris,
unsigned int num
);
/** Text functions **/
/*
* Set the font used by DrawString() and DrawGlyph().
* You can pass NULL here to unset the font.
*/
DFBResult (*SetFont) (
IDirectFBSurface *thiz,
IDirectFBFont *font
);
/*
* Get the font associated with a surface.
*
* This function increases the font's reference count.
*/
DFBResult (*GetFont) (
IDirectFBSurface *thiz,
IDirectFBFont **ret_font
);
/*
* Draw a string at the specified position with the
* given color following the specified flags.
*
* Bytes specifies the number of bytes to take from the
* string or -1 for the complete NULL-terminated string. You
* need to set a font using the SetFont() method before
* calling this function.
*/
DFBResult (*DrawString) (
IDirectFBSurface *thiz,
const char *text,
int bytes,
int x,
int y,
DFBSurfaceTextFlags flags
);
/*
* Draw a single glyph specified by its character code at the
* specified position with the given color following the
* specified flags.
*
* If font was loaded with the DFFA_NOCHARMAP flag, index specifies
* the raw glyph index in the font.
*
* You need to set a font using the SetFont() method before
* calling this function.
*/
DFBResult (*DrawGlyph) (
IDirectFBSurface *thiz,
unsigned int character,
int x,
int y,
DFBSurfaceTextFlags flags
);
/*
* Change the encoding used for text rendering.
*/
DFBResult (*SetEncoding) (
IDirectFBSurface *thiz,
DFBTextEncodingID encoding
);
/** Lightweight helpers **/
/*
* Get an interface to a sub area of this surface.
*
* No image data is duplicated, this is a clipped graphics
* within the original surface. This is very helpful for
* lightweight components in a GUI toolkit. The new
* surface's state (color, drawingflags, etc.) is
* independent from this one. So it's a handy graphics
* context. If no rectangle is specified, the whole surface
* (or a part if this surface is a subsurface itself) is
* represented by the new one.
*/
DFBResult (*GetSubSurface) (
IDirectFBSurface *thiz,
const DFBRectangle *rect,
IDirectFBSurface **ret_interface
);
/** OpenGL **/
/*
* Get a unique OpenGL context for this surface.
*/
DFBResult (*GetGL) (
IDirectFBSurface *thiz,
IDirectFBGL **ret_interface
);
/** Debug **/
/*
* Dump the contents of the surface to one or two files.
*
* Creates a PPM file containing the RGB data and a PGM file with
* the alpha data if present.
*
* The complete filenames will be
* <b>directory</b>/<b>prefix</b>_<i>####</i>.ppm for RGB and
* <b>directory</b>/<b>prefix</b>_<i>####</i>.pgm for the alpha channel
* if present. Example: "/directory/prefix_0000.ppm". No existing files
* will be overwritten.
*/
DFBResult (*Dump) (
IDirectFBSurface *thiz,
const char *directory,
const char *prefix
);
/*
* Disable hardware acceleration.
*
* If any function in <b>mask</b> is set, acceleration will not be used for it.<br/>
* Default is DFXL_NONE.
*/
DFBResult (*DisableAcceleration) (
IDirectFBSurface *thiz,
DFBAccelerationMask mask
);
/** Resources **/
/*
* Release possible reference to source surface.
*
* For performance reasons the last surface that has been used for Blit() and others stays
* attached to the state of the destination surface to save the overhead of reprogramming
* the same values each time.
*
* That leads to the last source being still around regardless of it being released
* via its own interface. The worst case is generation of thumbnails using StretchBlit()
* from a huge surface to a small one. The small thumbnail surface keeps the big one alive,
* because no other blitting will be done to the small surface afterwards.
*
* To solve this, here's the method applications should use in such a case.
*/
DFBResult (*ReleaseSource) (
IDirectFBSurface *thiz
);
/** Blitting control **/
/*
* Set index translation table.
*
* Set the translation table used for fast indexed to indexed
* pixel format conversion.
*
* A negative index means that the pixel will not be written.
*
* Undefined indices will be treated like negative ones.
*/
DFBResult (*SetIndexTranslation) (
IDirectFBSurface *thiz,
const int *indices,
int num_indices
);
/** Rendering **/
/*
* Set options affecting the output of drawing and blitting operations.
*
* None of these is mandatory and therefore unsupported flags will not
* cause a software fallback.
*/
DFBResult (*SetRenderOptions) (
IDirectFBSurface *thiz,
DFBSurfaceRenderOptions options
);
/** Drawing/blitting control **/
/*
* Set the transformation matrix.
*
* Enable usage of this matrix by setting DSRO_MATRIX via IDirectFBSurface::SetRenderOptions().
*
* The matrix consists of 3x3 fixed point 16.16 values.
* The order in the array is from left to right and from top to bottom.
*
* All drawing and blitting will be transformed:
*
* <pre>
* X' = (X * v0 + Y * v1 + v2) / (X * v6 + Y * v7 + v8)
* Y' = (X * v3 + Y * v4 + v5) / (X * v6 + Y * v7 + v8)
* </pre>
*/
DFBResult (*SetMatrix) (
IDirectFBSurface *thiz,
const s32 *matrix
);
/*
* Set the surface to be used as a mask for blitting.
*
* The <b>mask</b> applies when DSBLIT_SRC_MASK_ALPHA or DSBLIT_SRC_MASK_COLOR is used.
*
* Depending on the <b>flags</b> reading either starts at a fixed location in the mask with
* absolute <b>x</b> and <b>y</b>, or at the same location as in the source, with <b>x</b>
* and <b>y</b> used as an offset.
*
* <i>Example with DSMF_STENCIL:</i>
* <pre>
* Blit from <b>19, 6</b> in the source
* and <b> 0, 0</b> in the mask (<b>x = 0, y = 0</b>)
* or <b>-5, 17</b> (<b>x = -5, y = 17</b>)
* or <b>23, 42</b> (<b>x = 23, y = 42</b>)
* </pre>
*
* <i>Example without:</i>
* <pre>
* Blit from <b>19, 6</b> in the source
* and <b>19, 6</b> in the mask (<b>x = 0, y = 0</b>)
* or <b>14, 23</b> (<b>x = -5, y = 17</b>)
* or <b>42, 48</b> (<b>x = 23, y = 42</b>)
* </pre>
*
* See also IDirectFBSurface::SetBlittingFlags().
*/
DFBResult (*SetSourceMask) (
IDirectFBSurface *thiz,
IDirectFBSurface *mask,
int x,
int y,
DFBSurfaceMaskFlags flags
);
/** Lightweight helpers **/
/*
* Make this a sub surface or adjust the rectangle of this sub surface.
*/
DFBResult (*MakeSubSurface) (
IDirectFBSurface *thiz,
IDirectFBSurface *from,
const DFBRectangle *rect
);
/** Direct Write/Read **/
/*
* Write to the surface without the need for (Un)Lock.
*
* <b>rect</b> defines the area inside the surface.
* <br><b>ptr</b> and <b>pitch</b> specify the source.
* <br>The format of the surface and the source data must be the same.
*/
DFBResult (*Write) (
IDirectFBSurface *thiz,
const DFBRectangle *rect,
const void *ptr,
int pitch
);
/*
* Read from the surface without the need for (Un)Lock.
*
* <b>rect</b> defines the area inside the surface to be read.
* <br><b>ptr</b> and <b>pitch</b> specify the destination.
* <br>The destination data will have the same format as the surface.
*/
DFBResult (*Read) (
IDirectFBSurface *thiz,
const DFBRectangle *rect,
void *ptr,
int pitch
);
/** Drawing/blitting control **/
/*
* Sets color values used for drawing/text functions or
* alpha/color modulation (blitting functions).
*/
DFBResult (*SetColors) (
IDirectFBSurface *thiz,
const DFBColorID *ids,
const DFBColor *colors,
unsigned int num
);
)
/********************
* IDirectFBPalette *
********************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBPalette,
/** Retrieving information **/
/*
* Return the capabilities of this palette.
*/
DFBResult (*GetCapabilities) (
IDirectFBPalette *thiz,
DFBPaletteCapabilities *ret_caps
);
/*
* Get the number of entries in the palette.
*/
DFBResult (*GetSize) (
IDirectFBPalette *thiz,
unsigned int *ret_size
);
/** Palette entries **/
/*
* Write entries to the palette.
*
* Writes the specified number of entries to the palette at the
* specified offset.
*/
DFBResult (*SetEntries) (
IDirectFBPalette *thiz,
const DFBColor *entries,
unsigned int num_entries,
unsigned int offset
);
/*
* Read entries from the palette.
*
* Reads the specified number of entries from the palette at the
* specified offset.
*/
DFBResult (*GetEntries) (
IDirectFBPalette *thiz,
DFBColor *ret_entries,
unsigned int num_entries,
unsigned int offset
);
/*
* Find the best matching entry.
*
* Searches the map for an entry which best matches the specified color.
*/
DFBResult (*FindBestMatch) (
IDirectFBPalette *thiz,
u8 r,
u8 g,
u8 b,
u8 a,
unsigned int *ret_index
);
/** Clone **/
/*
* Create a copy of the palette.
*/
DFBResult (*CreateCopy) (
IDirectFBPalette *thiz,
IDirectFBPalette **ret_interface
);
/** YUV Palette **/
/*
* Write entries to the palette.
*
* Writes the specified number of entries to the palette at the
* specified offset.
*/
DFBResult (*SetEntriesYUV) (
IDirectFBPalette *thiz,
const DFBColorYUV *entries,
unsigned int num_entries,
unsigned int offset
);
/*
* Read entries from the palette.
*
* Reads the specified number of entries from the palette at the
* specified offset.
*/
DFBResult (*GetEntriesYUV) (
IDirectFBPalette *thiz,
DFBColorYUV *ret_entries,
unsigned int num_entries,
unsigned int offset
);
/*
* Find the best matching entry.
*
* Searches the map for an entry which best matches the specified color.
*/
DFBResult (*FindBestMatchYUV) (
IDirectFBPalette *thiz,
u8 y,
u8 u,
u8 v,
u8 a,
unsigned int *ret_index
);
)
/*
* Specifies whether a key is currently down.
*/
typedef enum {
DIKS_UP = 0x00000000, /* key is not pressed */
DIKS_DOWN = 0x00000001 /* key is pressed */
} DFBInputDeviceKeyState;
/*
* Specifies whether a button is currently pressed.
*/
typedef enum {
DIBS_UP = 0x00000000, /* button is not pressed */
DIBS_DOWN = 0x00000001 /* button is pressed */
} DFBInputDeviceButtonState;
/*
* Flags specifying which buttons are currently down.
*/
typedef enum {
DIBM_LEFT = 0x00000001, /* left mouse button */
DIBM_RIGHT = 0x00000002, /* right mouse button */
DIBM_MIDDLE = 0x00000004 /* middle mouse button */
} DFBInputDeviceButtonMask;
/*
* Flags specifying which modifiers are currently pressed.
*/
typedef enum {
DIMM_SHIFT = (1 << DIMKI_SHIFT), /* Shift key is pressed */
DIMM_CONTROL = (1 << DIMKI_CONTROL), /* Control key is pressed */
DIMM_ALT = (1 << DIMKI_ALT), /* Alt key is pressed */
DIMM_ALTGR = (1 << DIMKI_ALTGR), /* AltGr key is pressed */
DIMM_META = (1 << DIMKI_META), /* Meta key is pressed */
DIMM_SUPER = (1 << DIMKI_SUPER), /* Super key is pressed */
DIMM_HYPER = (1 << DIMKI_HYPER) /* Hyper key is pressed */
} DFBInputDeviceModifierMask;
/************************
* IDirectFBInputDevice *
************************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBInputDevice,
/** Retrieving information **/
/*
* Get the unique device ID.
*/
DFBResult (*GetID) (
IDirectFBInputDevice *thiz,
DFBInputDeviceID *ret_device_id
);
/*
* Get a description of this device, i.e. the capabilities.
*/
DFBResult (*GetDescription) (
IDirectFBInputDevice *thiz,
DFBInputDeviceDescription *ret_desc
);
/** Key mapping **/
/*
* Fetch one entry from the keymap for a specific hardware keycode.
*/
DFBResult (*GetKeymapEntry) (
IDirectFBInputDevice *thiz,
int keycode,
DFBInputDeviceKeymapEntry *ret_entry
);
/*
* Set one entry of the keymap to the specified entry.
* Each entry has 4 modifier combinations for going from key to symbol.
*/
DFBResult (*SetKeymapEntry) (
IDirectFBInputDevice *thiz,
int keycode,
DFBInputDeviceKeymapEntry *entry
);
/*
* Load a keymap from the specified file.
* All specified keys will overwrite the current keymap.
* On return of an error, the keymap is in an unspecified state.
* the file must be ASCII containing lines:
* keycode <hw code> = <key id> = <symbol> .... (up to 4 symbols)
* Modifier-key-sensitive keys can be framed between
* capslock: .... :capslock or numlock: ... :numlock.
*/
DFBResult (*LoadKeymap) (
IDirectFBInputDevice *thiz,
char *filename
);
/** Event buffers **/
/*
* Create an event buffer for this device and attach it.
*/
DFBResult (*CreateEventBuffer) (
IDirectFBInputDevice *thiz,
IDirectFBEventBuffer **ret_buffer
);
/*
* Attach an existing event buffer to this device.
*
* NOTE: Attaching multiple times generates multiple events.
*
*/
DFBResult (*AttachEventBuffer) (
IDirectFBInputDevice *thiz,
IDirectFBEventBuffer *buffer
);
/*
* Detach an event buffer from this device.
*/
DFBResult (*DetachEventBuffer) (
IDirectFBInputDevice *thiz,
IDirectFBEventBuffer *buffer
);
/** General state queries **/
/*
* Get the current state of one key.
*/
DFBResult (*GetKeyState) (
IDirectFBInputDevice *thiz,
DFBInputDeviceKeyIdentifier key_id,
DFBInputDeviceKeyState *ret_state
);
/*
* Get the current modifier mask.
*/
DFBResult (*GetModifiers) (
IDirectFBInputDevice *thiz,
DFBInputDeviceModifierMask *ret_modifiers
);
/*
* Get the current state of the key locks.
*/
DFBResult (*GetLockState) (
IDirectFBInputDevice *thiz,
DFBInputDeviceLockState *ret_locks
);
/*
* Get a mask of currently pressed buttons.
*
* The first button corrensponds to the right most bit.
*/
DFBResult (*GetButtons) (
IDirectFBInputDevice *thiz,
DFBInputDeviceButtonMask *ret_buttons
);
/*
* Get the state of a button.
*/
DFBResult (*GetButtonState) (
IDirectFBInputDevice *thiz,
DFBInputDeviceButtonIdentifier button,
DFBInputDeviceButtonState *ret_state
);
/*
* Get the current value of the specified axis.
*/
DFBResult (*GetAxis) (
IDirectFBInputDevice *thiz,
DFBInputDeviceAxisIdentifier axis,
int *ret_pos
);
/** Specialized queries **/
/*
* Utility function combining two calls to GetAxis().
*
* You may leave one of the x/y arguments NULL.
*/
DFBResult (*GetXY) (
IDirectFBInputDevice *thiz,
int *ret_x,
int *ret_y
);
/** Configuration */
DFBResult (*SetSensitivity) (
IDirectFBInputDevice *thiz,
int sensitivity
);
)
/*
* Event class.
*/
typedef enum {
DFEC_NONE = 0x00, /* none of these */
DFEC_INPUT = 0x01, /* raw input event */
DFEC_WINDOW = 0x02, /* windowing event */
DFEC_USER = 0x03, /* custom event for the user of this library */
DFEC_UNIVERSAL = 0x04, /* universal event for custom usage with variable size */
DFEC_VIDEOPROVIDER = 0x05 /* video provider event */
} DFBEventClass;
/*
* The type of an input event.
*/
typedef enum {
DIET_UNKNOWN = 0, /* unknown event */
DIET_KEYPRESS, /* a key is been pressed */
DIET_KEYRELEASE, /* a key is been released */
DIET_BUTTONPRESS, /* a (mouse) button is been pressed */
DIET_BUTTONRELEASE, /* a (mouse) button is been released */
DIET_AXISMOTION /* mouse/joystick movement */
} DFBInputEventType;
/*
* Flags defining which additional (optional) event fields are valid.
*/
typedef enum {
DIEF_NONE = 0x0000, /* no additional fields */
DIEF_TIMESTAMP = 0x0001, /* timestamp is valid */
DIEF_AXISABS = 0x0002, /* axis and axisabs are valid */
DIEF_AXISREL = 0x0004, /* axis and axisrel are valid */
DIEF_KEYCODE = 0x0008, /* used internally by the input core,
always set at application level */
DIEF_KEYID = 0x0010, /* used internally by the input core,
always set at application level */
DIEF_KEYSYMBOL = 0x0020, /* used internally by the input core,
always set at application level */
DIEF_MODIFIERS = 0x0040, /* used internally by the input core,
always set at application level */
DIEF_LOCKS = 0x0080, /* used internally by the input core,
always set at application level */
DIEF_BUTTONS = 0x0100, /* used internally by the input core,
always set at application level */
DIEF_GLOBAL = 0x0200, /* Only for event buffers creates by
IDirectFB::CreateInputEventBuffer()
with global events enabled.
Indicates that the event would have been
filtered if the buffer hadn't been
global. */
DIEF_REPEAT = 0x0400, /* repeated event, e.g. key or button press */
DIEF_FOLLOW = 0x0800, /* another event will follow immediately, e.g. x/y axis */
DIEF_MIN = 0x1000, /* minimum value is set, e.g. for absolute axis motion */
DIEF_MAX = 0x2000, /* maximum value is set, e.g. for absolute axis motion */
} DFBInputEventFlags;
/*
* An input event, item of an input buffer.
*/
typedef struct {
DFBEventClass clazz; /* clazz of event */
DFBInputEventType type; /* type of event */
DFBInputDeviceID device_id; /* source of event */
DFBInputEventFlags flags; /* which optional fields
are valid? */
/* additionally (check flags) */
struct timeval timestamp; /* time of event creation */
/* DIET_KEYPRESS, DIET_KEYRELEASE */
int key_code; /* hardware keycode, no
mapping, -1 if device
doesn't differentiate
between several keys */
DFBInputDeviceKeyIdentifier key_id; /* basic mapping,
modifier independent */
DFBInputDeviceKeySymbol key_symbol; /* advanced mapping,
unicode compatible,
modifier dependent */
/* additionally (check flags) */
DFBInputDeviceModifierMask modifiers; /* pressed modifiers
(optional) */
DFBInputDeviceLockState locks; /* active locks
(optional) */
/* DIET_BUTTONPRESS, DIET_BUTTONRELEASE */
DFBInputDeviceButtonIdentifier button; /* in case of a button
event */
DFBInputDeviceButtonMask buttons; /* mask of currently
pressed buttons */
/* DIET_AXISMOTION */
DFBInputDeviceAxisIdentifier axis; /* in case of an axis
event */
/* one of these two (check flags) */
int axisabs; /* absolute mouse/
joystick coordinate */
int axisrel; /* relative mouse/
joystick movement */
/* general information */
int min; /* minimum possible value */
int max; /* maximum possible value */
} DFBInputEvent;
/*
* Window Event Types - can also be used as flags for event filters.
*/
typedef enum {
DWET_NONE = 0x00000000,
DWET_POSITION = 0x00000001, /* window has been moved by
window manager or the
application itself */
DWET_SIZE = 0x00000002, /* window has been resized
by window manager or the
application itself */
DWET_CLOSE = 0x00000004, /* closing this window has been
requested only */
DWET_DESTROYED = 0x00000008, /* window got destroyed by global
deinitialization function or
the application itself */
DWET_GOTFOCUS = 0x00000010, /* window got focus */
DWET_LOSTFOCUS = 0x00000020, /* window lost focus */
DWET_KEYDOWN = 0x00000100, /* a key has gone down while
window has focus */
DWET_KEYUP = 0x00000200, /* a key has gone up while
window has focus */
DWET_BUTTONDOWN = 0x00010000, /* mouse button went down in
the window */
DWET_BUTTONUP = 0x00020000, /* mouse button went up in
the window */
DWET_MOTION = 0x00040000, /* mouse cursor changed its
position in window */
DWET_ENTER = 0x00080000, /* mouse cursor entered
the window */
DWET_LEAVE = 0x00100000, /* mouse cursor left the window */
DWET_WHEEL = 0x00200000, /* mouse wheel was moved while
window has focus */
DWET_POSITION_SIZE = DWET_POSITION | DWET_SIZE,/* initially sent to
window when it's
created */
DWET_UPDATE = 0x10000000,
DWET_ALL = 0x103F033F /* all event types */
} DFBWindowEventType;
/*
* Flags for a window event.
*/
typedef enum {
DWEF_NONE = 0x00000000, /* none of these */
DWEF_RETURNED = 0x00000001, /* This is a returned event, e.g. unconsumed key. */
DWEF_RELATIVE = 0x00000002, /* This is a relative motion event (confined mode) */
DWEF_ALL = 0x00000003 /* all of these */
} DFBWindowEventFlags;
/*
* Video Provider Event Types - can also be used as flags for event filters.
*/
typedef enum {
DVPET_NONE = 0x00000000,
DVPET_STARTED = 0x00000001, /* The video provider has started the playback */
DVPET_STOPPED = 0x00000002, /* The video provider has stopped the playback */
DVPET_SPEEDCHANGE = 0x00000004, /* A speed change has occured */
DVPET_STREAMCHANGE = 0x00000008, /* A stream description change has occured */
DVPET_FATALERROR = 0x00000010, /* A fatal error has occured: restart must be done */
DVPET_FINISHED = 0x00000020, /* The video provider has finished the playback */
DVPET_SURFACECHANGE = 0x00000040, /* A surface description change has occured */
DVPET_FRAMEDECODED = 0x00000080, /* A frame has been decoded by the decoder */
DVPET_FRAMEDISPLAYED = 0x00000100, /* A frame has been rendered to the output */
DVPET_DATAEXHAUSTED = 0x00000200, /* There is no more data available for consumption */
DVPET_VIDEOACTION = 0x00000400, /* An action is required on the video provider */
DVPET_DATALOW = 0x00000800, /* The stream buffer is running low in data (threshold defined by implementation). */
DVPET_DATAHIGH = 0x00001000, /* The stream buffer is high. */
DVPET_BUFFERTIMELOW = 0x00002000, /* The stream buffer has less than requested playout time buffered. */
DVPET_BUFFERTIMEHIGH = 0x00004000, /* The stream buffer has more than requested playout time buffered. */
DVPET_ALL = 0x00007FFF /* All event types */
} DFBVideoProviderEventType;
/*
* Event from the windowing system.
*/
typedef struct {
DFBEventClass clazz; /* clazz of event */
DFBWindowEventType type; /* type of event */
DFBWindowEventFlags flags; /* event flags */
DFBWindowID window_id; /* source of event */
/* used by DWET_MOVE, DWET_MOTION, DWET_BUTTONDOWN, DWET_BUTTONUP,
DWET_ENTER, DWET_LEAVE */
int x; /* x position of window
or coordinate within
window */
int y; /* y position of window
or coordinate within
window */
/* used by DWET_MOTION, DWET_BUTTONDOWN, DWET_BUTTONUP,
DWET_ENTER, DWET_LEAVE */
int cx; /* x cursor position */
int cy; /* y cursor position */
/* used by DWET_WHEEL */
int step; /* wheel step */
/* used by DWET_RESIZE */
int w; /* width of window */
int h; /* height of window */
/* used by DWET_KEYDOWN, DWET_KEYUP */
int key_code; /* hardware keycode, no
mapping, -1 if device
doesn't differentiate
between several keys */
DFBInputDeviceKeyIdentifier key_id; /* basic mapping,
modifier independent */
DFBInputDeviceKeySymbol key_symbol; /* advanced mapping,
unicode compatible,
modifier dependent */
DFBInputDeviceModifierMask modifiers; /* pressed modifiers */
DFBInputDeviceLockState locks; /* active locks */
/* used by DWET_BUTTONDOWN, DWET_BUTTONUP */
DFBInputDeviceButtonIdentifier button; /* button being
pressed or released */
/* used by DWET_MOTION, DWET_BUTTONDOWN, DWET_BUTTONUP */
DFBInputDeviceButtonMask buttons; /* mask of currently
pressed buttons */
struct timeval timestamp; /* always set */
} DFBWindowEvent;
/*
* Video Provider Event Types - can also be used as flags for event filters.
*/
typedef enum {
DVPEDST_UNKNOWN = 0x00000000, /* Event is valid for unknown Data */
DVPEDST_AUDIO = 0x00000001, /* Event is valid for Audio Data */
DVPEDST_VIDEO = 0x00000002, /* Event is valid for Video Data */
DVPEDST_DATA = 0x00000004, /* Event is valid for Data types */
DVPEDST_ALL = 0x00000007, /* Event is valid for all Data types */
} DFBVideoProviderEventDataSubType;
/*
* Event from the video provider
*/
typedef struct {
DFBEventClass clazz; /* clazz of event */
DFBVideoProviderEventType type; /* type of event */
DFBVideoProviderEventDataSubType data_type; /* data type that this event is applicable for. */
int data[4]; /* custom data - large enough for 4 ints so that in most cases
memory allocation will not be needed */
} DFBVideoProviderEvent;
/*
* Event for usage by the user of this library.
*/
typedef struct {
DFBEventClass clazz; /* clazz of event */
unsigned int type; /* custom type */
void *data; /* custom data */
} DFBUserEvent;
/*
* Universal event for custom usage with variable size.
*/
typedef struct {
DFBEventClass clazz; /* clazz of event (DFEC_UNIVERSAL) */
unsigned int size; /* size of this event, minimum is sizeof(DFBUniversalEvent),
e.g. 8 bytes (on 32bit architectures) */
/* custom data follows, size of this data is 'size' - sizeof(DFBUniversalEvent) */
} DFBUniversalEvent;
/*
* General container for a DirectFB Event.
*/
typedef union {
DFBEventClass clazz; /* clazz of event */
DFBInputEvent input; /* field for input events */
DFBWindowEvent window; /* field for window events */
DFBUserEvent user; /* field for user-defined events */
DFBUniversalEvent universal; /* field for universal events */
DFBVideoProviderEvent videoprovider; /* field for video provider */
} DFBEvent;
#define DFB_EVENT(e) ((DFBEvent *) (e))
/*
* Statistics about event buffer queue.
*/
typedef struct {
unsigned int num_events; /* Total number of events in the queue. */
unsigned int DFEC_INPUT; /* Number of input events. */
unsigned int DFEC_WINDOW; /* Number of window events. */
unsigned int DFEC_USER; /* Number of user events. */
unsigned int DFEC_UNIVERSAL; /* Number of universal events. */
unsigned int DFEC_VIDEOPROVIDER; /* Number of universal events. */
unsigned int DIET_KEYPRESS;
unsigned int DIET_KEYRELEASE;
unsigned int DIET_BUTTONPRESS;
unsigned int DIET_BUTTONRELEASE;
unsigned int DIET_AXISMOTION;
unsigned int DWET_POSITION;
unsigned int DWET_SIZE;
unsigned int DWET_CLOSE;
unsigned int DWET_DESTROYED;
unsigned int DWET_GOTFOCUS;
unsigned int DWET_LOSTFOCUS;
unsigned int DWET_KEYDOWN;
unsigned int DWET_KEYUP;
unsigned int DWET_BUTTONDOWN;
unsigned int DWET_BUTTONUP;
unsigned int DWET_MOTION;
unsigned int DWET_ENTER;
unsigned int DWET_LEAVE;
unsigned int DWET_WHEEL;
unsigned int DWET_POSITION_SIZE;
unsigned int DVPET_STARTED;
unsigned int DVPET_STOPPED;
unsigned int DVPET_SPEEDCHANGE;
unsigned int DVPET_STREAMCHANGE;
unsigned int DVPET_FATALERROR;
unsigned int DVPET_FINISHED;
unsigned int DVPET_SURFACECHANGE;
unsigned int DVPET_FRAMEDECODED;
unsigned int DVPET_FRAMEDISPLAYED;
unsigned int DVPET_DATAEXHAUSTED;
unsigned int DVPET_DATALOW;
unsigned int DVPET_VIDEOACTION;
unsigned int DVPET_DATAHIGH;
unsigned int DVPET_BUFFERTIMELOW;
unsigned int DVPET_BUFFERTIMEHIGH;
} DFBEventBufferStats;
/************************
* IDirectFBEventBuffer *
************************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBEventBuffer,
/** Buffer handling **/
/*
* Clear all events stored in this buffer.
*/
DFBResult (*Reset) (
IDirectFBEventBuffer *thiz
);
/** Waiting for events **/
/*
* Wait for the next event to occur.
* Thread is idle in the meantime.
*/
DFBResult (*WaitForEvent) (
IDirectFBEventBuffer *thiz
);
/*
* Block until next event to occur or timeout is reached.
* Thread is idle in the meantime.
*/
DFBResult (*WaitForEventWithTimeout) (
IDirectFBEventBuffer *thiz,
unsigned int seconds,
unsigned int milli_seconds
);
/** Fetching events **/
/*
* Get the next event and remove it from the FIFO.
*/
DFBResult (*GetEvent) (
IDirectFBEventBuffer *thiz,
DFBEvent *ret_event
);
/*
* Get the next event but leave it there, i.e. do a preview.
*/
DFBResult (*PeekEvent) (
IDirectFBEventBuffer *thiz,
DFBEvent *ret_event
);
/*
* Check if there is a pending event in the queue. This
* function returns DFB_OK if there is at least one event,
* DFB_BUFFER_EMPTY otherwise.
*/
DFBResult (*HasEvent) (
IDirectFBEventBuffer *thiz
);
/** Sending events **/
/*
* Put an event into the FIFO.
*
* This function does not wait until the event got fetched.
*/
DFBResult (*PostEvent) (
IDirectFBEventBuffer *thiz,
const DFBEvent *event
);
/*
* Wake up any thread waiting for events in this buffer.
*
* This method causes any IDirectFBEventBuffer::WaitForEvent() or
* IDirectFBEventBuffer::WaitForEventWithTimeout() call to return with DFB_INTERRUPTED.
*
* It should be used rather than sending wake up messages which
* may pollute the queue and consume lots of CPU and memory compared to
* this 'single code line method'.
*/
DFBResult (*WakeUp) (
IDirectFBEventBuffer *thiz
);
/** Special handling **/
/*
* Create a file descriptor for reading events.
*
* This method provides an alternative for reading events from an event buffer.
* It creates a file descriptor which can be used in select(), poll() or read().
*
* In general only non-threaded applications which already use select() or poll() need it.
*
* <b>Note:</b> This method flushes the event buffer. After calling this method all other
* methods except IDirectFBEventBuffer::PostEvent() will return DFB_UNSUPPORTED.
* Calling this method again will return DFB_BUSY.
*/
DFBResult (*CreateFileDescriptor) (
IDirectFBEventBuffer *thiz,
int *ret_fd
);
/** Statistics **/
/*
* Enable/disable collection of event buffer statistics.
*/
DFBResult (*EnableStatistics) (
IDirectFBEventBuffer *thiz,
DFBBoolean enable
);
/*
* Query collected event buffer statistics.
*/
DFBResult (*GetStatistics) (
IDirectFBEventBuffer *thiz,
DFBEventBufferStats *ret_stats
);
)
/*
* The key selection defines a mode for filtering keys while the window is having the focus.
*/
typedef enum {
DWKS_ALL = 0x00000000, /* Select all keys (default). */
DWKS_NONE = 0x00000001, /* Don't select any key. */
DWKS_LIST = 0x00000002 /* Select a list of keys. */
} DFBWindowKeySelection;
typedef enum {
DWGM_DEFAULT = 0x00000000, /* Use default values. */
DWGM_FOLLOW = 0x00000001, /* Use values of parent window. */
DWGM_RECTANGLE = 0x00000002, /* Use pixel values as defined. */
DWGM_LOCATION = 0x00000003 /* Use relative values as defined. */
} DFBWindowGeometryMode;
typedef struct {
DFBWindowGeometryMode mode;
DFBRectangle rectangle;
DFBLocation location;
} DFBWindowGeometry;
typedef enum {
DWCF_NONE = 0x00000000,
DWCF_RELATIVE = 0x00000001,
DWCF_EXPLICIT = 0x00000002,
DWCF_UNCLIPPED = 0x00000004,
DWCF_TRAPPED = 0x00000008,
DWCF_FIXED = 0x00000010,
DWCF_INVISIBLE = 0x00000020,
DWCF_ALL = 0x0000003F
} DFBWindowCursorFlags;
/*******************
* IDirectFBWindow *
*******************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBWindow,
/** Retrieving information **/
/*
* Get the unique window ID.
*/
DFBResult (*GetID) (
IDirectFBWindow *thiz,
DFBWindowID *ret_window_id
);
/*
* Get the current position of this window.
*/
DFBResult (*GetPosition) (
IDirectFBWindow *thiz,
int *ret_x,
int *ret_y
);
/*
* Get the size of the window in pixels.
*/
DFBResult (*GetSize) (
IDirectFBWindow *thiz,
int *ret_width,
int *ret_height
);
/** Close & Destroy **/
/*
* Send a close message to the window.
*
* This function sends a message of type DWET_CLOSE to the window.
* It does NOT actually close it.
*/
DFBResult (*Close) (
IDirectFBWindow *thiz
);
/*
* Destroys the window and sends a destruction message.
*
* This function sends a message of type DWET_DESTROY to
* the window after removing it from the window stack and
* freeing its data. Some functions called from this
* interface will return DFB_DESTROYED after that.
*/
DFBResult (*Destroy) (
IDirectFBWindow *thiz
);
/** Surface & Scaling **/
/*
* Get an interface to the backing store surface.
*
* This surface has to be flipped to make previous drawing
* commands visible, i.e. to repaint the windowstack for
* that region.
*/
DFBResult (*GetSurface) (
IDirectFBWindow *thiz,
IDirectFBSurface **ret_surface
);
/*
* Resize the surface of a scalable window.
*
* This requires the option DWOP_SCALE.
* See IDirectFBWindow::SetOptions().
*/
DFBResult (*ResizeSurface) (
IDirectFBWindow *thiz,
int width,
int height
);
/** Events **/
/*
* Create an event buffer for this window and attach it.
*/
DFBResult (*CreateEventBuffer) (
IDirectFBWindow *thiz,
IDirectFBEventBuffer **ret_buffer
);
/*
* Attach an existing event buffer to this window.
*
* NOTE: Attaching multiple times generates multiple events.
*
*/
DFBResult (*AttachEventBuffer) (
IDirectFBWindow *thiz,
IDirectFBEventBuffer *buffer
);
/*
* Detach an event buffer from this window.
*/
DFBResult (*DetachEventBuffer) (
IDirectFBWindow *thiz,
IDirectFBEventBuffer *buffer
);
/*
* Enable specific events to be sent to the window.
*
* The argument is a mask of events that will be set in the
* window's event mask. The default event mask is DWET_ALL.
*/
DFBResult (*EnableEvents) (
IDirectFBWindow *thiz,
DFBWindowEventType mask
);
/*
* Disable specific events from being sent to the window.
*
* The argument is a mask of events that will be cleared in
* the window's event mask. The default event mask is DWET_ALL.
*/
DFBResult (*DisableEvents) (
IDirectFBWindow *thiz,
DFBWindowEventType mask
);
/** Options **/
/*
* Set options controlling appearance and behaviour of the window.
*/
DFBResult (*SetOptions) (
IDirectFBWindow *thiz,
DFBWindowOptions options
);
/*
* Get options controlling appearance and behaviour of the window.
*/
DFBResult (*GetOptions) (
IDirectFBWindow *thiz,
DFBWindowOptions *ret_options
);
/*
* Set the window color.
*
* This is used in case you specified DWCAPS_COLOR.
* It specifies the window draw color.
*/
DFBResult (*SetColor) (
IDirectFBWindow *thiz,
u8 r,
u8 g,
u8 b,
u8 a
);
/*
* Set the window color key.
*
* If a pixel of the window matches this color the
* underlying window or the background is visible at this
* point.
*/
DFBResult (*SetColorKey) (
IDirectFBWindow *thiz,
u8 r,
u8 g,
u8 b
);
/*
* Set the window color key (indexed).
*
* If a pixel (indexed format) of the window matches this
* color index the underlying window or the background is
* visible at this point.
*/
DFBResult (*SetColorKeyIndex) (
IDirectFBWindow *thiz,
unsigned int index
);
/*
* Set the window's global opacity factor.
*
* Set it to "0" to hide a window.
* Setting it to "0xFF" makes the window opaque if
* it has no alpha channel.
*/
DFBResult (*SetOpacity) (
IDirectFBWindow *thiz,
u8 opacity
);
/*
* Disable alpha channel blending for one region of the window.
*
* If DWOP_ALPHACHANNEL and DWOP_OPAQUE_REGION are set but not DWOP_COLORKEYING
* and the opacity of the window is 255 the window gets rendered
* without alpha blending within the specified region.
*
* This is extremely useful for alpha blended window decorations while
* the main content stays opaque and gets rendered faster.
*/
DFBResult (*SetOpaqueRegion) (
IDirectFBWindow *thiz,
int x1,
int y1,
int x2,
int y2
);
/*
* Get the current opacity factor of this window.
*/
DFBResult (*GetOpacity) (
IDirectFBWindow *thiz,
u8 *ret_opacity
);
/*
* Bind a cursor shape to this window.
*
* This method will set a per-window cursor shape. Everytime
* the cursor enters this window, the specified shape is set.
*
* Passing NULL will unbind a set shape and release its surface.
*/
DFBResult (*SetCursorShape) (
IDirectFBWindow *thiz,
IDirectFBSurface *shape,
int hot_x,
int hot_y
);
/** Position and Size **/
/*
* Move the window by the specified distance.
*/
DFBResult (*Move) (
IDirectFBWindow *thiz,
int dx,
int dy
);
/*
* Move the window to the specified coordinates.
*/
DFBResult (*MoveTo) (
IDirectFBWindow *thiz,
int x,
int y
);
/*
* Resize the window.
*/
DFBResult (*Resize) (
IDirectFBWindow *thiz,
int width,
int height
);
/*
* Set position and size in one step.
*/
DFBResult (*SetBounds) (
IDirectFBWindow *thiz,
int x,
int y,
int width,
int height
);
/** Stacking **/
/*
* Put the window into a specific stacking class.
*/
DFBResult (*SetStackingClass) (
IDirectFBWindow *thiz,
DFBWindowStackingClass stacking_class
);
/*
* Raise the window by one within the window stack.
*/
DFBResult (*Raise) (
IDirectFBWindow *thiz
);
/*
* Lower the window by one within the window stack.
*/
DFBResult (*Lower) (
IDirectFBWindow *thiz
);
/*
* Put the window on the top of the window stack.
*/
DFBResult (*RaiseToTop) (
IDirectFBWindow *thiz
);
/*
* Send a window to the bottom of the window stack.
*/
DFBResult (*LowerToBottom) (
IDirectFBWindow *thiz
);
/*
* Put a window on top of another window.
*/
DFBResult (*PutAtop) (
IDirectFBWindow *thiz,
IDirectFBWindow *lower
);
/*
* Put a window below another window.
*/
DFBResult (*PutBelow) (
IDirectFBWindow *thiz,
IDirectFBWindow *upper
);
/** Binding **/
/*
* Bind a window at the specified position of this window.
*
* After binding, bound window will be automatically moved
* when this window moves to a new position.<br>
* Binding the same window to multiple windows is not supported.
* Subsequent call to Bind() automatically unbounds the bound window
* before binding it again.<br>
* To move the bound window to a new position call Bind() again
* with the new coordinates.
*/
DFBResult (*Bind) (
IDirectFBWindow *thiz,
IDirectFBWindow *window,
int x,
int y
);
/*
* Unbind a window from this window.
*/
DFBResult (*Unbind) (
IDirectFBWindow *thiz,
IDirectFBWindow *window
);
/** Focus handling **/
/*
* Pass the focus to this window.
*/
DFBResult (*RequestFocus) (
IDirectFBWindow *thiz
);
/*
* Grab the keyboard, i.e. all following keyboard events are
* sent to this window ignoring the focus.
*/
DFBResult (*GrabKeyboard) (
IDirectFBWindow *thiz
);
/*
* Ungrab the keyboard, i.e. switch to standard key event
* dispatching.
*/
DFBResult (*UngrabKeyboard) (
IDirectFBWindow *thiz
);
/*
* Grab the pointer, i.e. all following mouse events are
* sent to this window ignoring the focus.
*/
DFBResult (*GrabPointer) (
IDirectFBWindow *thiz
);
/*
* Ungrab the pointer, i.e. switch to standard mouse event
* dispatching.
*/
DFBResult (*UngrabPointer) (
IDirectFBWindow *thiz
);
/*
* Grab a specific key, i.e. all following events of this key are
* sent to this window ignoring the focus.
*/
DFBResult (*GrabKey) (
IDirectFBWindow *thiz,
DFBInputDeviceKeySymbol symbol,
DFBInputDeviceModifierMask modifiers
);
/*
* Ungrab a specific key, i.e. switch to standard key event
* dispatching.
*/
DFBResult (*UngrabKey) (
IDirectFBWindow *thiz,
DFBInputDeviceKeySymbol symbol,
DFBInputDeviceModifierMask modifiers
);
/** Key selection **/
/*
* Selects a mode for filtering keys while being focused.
*
* The <b>selection</b> defines whether all, none or a specific set (list) of keys is selected.
* In case of a specific set, the <b>keys</b> array with <b>num_keys</b> has to be provided.
*
* Multiple calls to this method are possible. Each overrides all settings from the previous call.
*/
DFBResult (*SetKeySelection) (
IDirectFBWindow *thiz,
DFBWindowKeySelection selection,
const DFBInputDeviceKeySymbol *keys,
unsigned int num_keys
);
/*
* Grab all unselected (filtered out) keys.
*
* Unselected keys are those not selected by the focused window. These keys won't be sent
* to that window. Instead one window in the stack can collect them.
*
* See also IDirectFBWindow::UngrabUnselectedKeys() and IDirectFBWindow::SetKeySelection().
*/
DFBResult (*GrabUnselectedKeys) (
IDirectFBWindow *thiz
);
/*
* Release the grab of unselected (filtered out) keys.
*
* See also IDirectFBWindow::GrabUnselectedKeys() and IDirectFBWindow::SetKeySelection().
*/
DFBResult (*UngrabUnselectedKeys) (
IDirectFBWindow *thiz
);
/** Advanced Geometry **/
/*
* Set area of surface to be shown in window.
*
* Default and maximum is to show whole surface.
*/
DFBResult (*SetSrcGeometry) (
IDirectFBWindow *thiz,
const DFBWindowGeometry *geometry
);
/*
* Set destination location of window within its bounds.
*
* Default and maximum is to fill whole bounds.
*/
DFBResult (*SetDstGeometry) (
IDirectFBWindow *thiz,
const DFBWindowGeometry *geometry
);
/** Properties **/
/*
* Set property controlling appearance and behaviour of the window.
*/
DFBResult (*SetProperty) (
IDirectFBWindow *thiz,
const char *key,
void *value,
void **ret_old_value
);
/*
* Get property controlling appearance and behaviour of the window.
*/
DFBResult (*GetProperty) (
IDirectFBWindow *thiz,
const char *key,
void **ret_value
);
/*
* Remove property controlling appearance and behaviour of the window.
*/
DFBResult (*RemoveProperty) (
IDirectFBWindow *thiz,
const char *key,
void **ret_value
);
/*
* Set window rotation.
*/
DFBResult (*SetRotation) (
IDirectFBWindow *thiz,
int rotation
);
/** Association **/
/*
* Change the window association.
*
* If <b>window_id</b> is 0, the window will be dissociated.
*/
DFBResult (*SetAssociation) (
IDirectFBWindow *thiz,
DFBWindowID window_id
);
/** Updates **/
/*
* Signal start of window content updates.
*/
DFBResult (*BeginUpdates) (
IDirectFBWindow *thiz,
const DFBRegion *update
);
/** Events **/
/*
* Send event
*/
DFBResult (*SendEvent) (
IDirectFBWindow *thiz,
const DFBWindowEvent *event
);
/** Cursor **/
/*
* Set cursor flags (active when in focus).
*/
DFBResult (*SetCursorFlags) (
IDirectFBWindow *thiz,
DFBWindowCursorFlags flags
);
/*
* Set cursor resolution (coordinate space for cursor within window).
*
* The default cursor resolution is the surface dimensions.
*/
DFBResult (*SetCursorResolution) (
IDirectFBWindow *thiz,
const DFBDimension *resolution
);
/*
* Set cursor position within window coordinates (surface or cursor resolution).
*/
DFBResult (*SetCursorPosition) (
IDirectFBWindow *thiz,
int x,
int y
);
)
/*
* Called for each provided text encoding.
*/
typedef DFBEnumerationResult (*DFBTextEncodingCallback) (
DFBTextEncodingID encoding_id,
const char *name,
void *context
);
/*****************
* IDirectFBFont *
*****************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBFont,
/** Retrieving information **/
/*
* Get the distance from the baseline to the top of the
* logical extents of this font.
*/
DFBResult (*GetAscender) (
IDirectFBFont *thiz,
int *ret_ascender
);
/*
* Get the distance from the baseline to the bottom of
* the logical extents of this font.
*
* This is a negative value!
*/
DFBResult (*GetDescender) (
IDirectFBFont *thiz,
int *ret_descender
);
/*
* Get the logical height of this font. This is the
* distance from one baseline to the next when writing
* several lines of text. Note that this value does not
* correspond the height value specified when loading the
* font.
*/
DFBResult (*GetHeight) (
IDirectFBFont *thiz,
int *ret_height
);
/*
* Get the maximum character width.
*
* This is a somewhat dubious value. Not all fonts
* specify it correcly. It can give you an idea of
* the maximum expected width of a rendered string.
*/
DFBResult (*GetMaxAdvance) (
IDirectFBFont *thiz,
int *ret_maxadvance
);
/*
* Get the kerning to apply between two glyphs specified by
* their character codes.
*/
DFBResult (*GetKerning) (
IDirectFBFont *thiz,
unsigned int prev,
unsigned int current,
int *ret_kern_x,
int *ret_kern_y
);
/** Measurements **/
/*
* Get the logical width of the specified string
* as if it were drawn with this font.
*
* Bytes specifies the number of bytes to take from the
* string or -1 for the complete NULL-terminated string.
*
* The returned width may be different than the actual drawn
* width of the text since this function returns the logical
* width that should be used to layout the text. A negative
* width indicates right-to-left rendering.
*/
DFBResult (*GetStringWidth) (
IDirectFBFont *thiz,
const char *text,
int bytes,
int *ret_width
);
/*
* Get the logical and real extents of the specified
* string as if it were drawn with this font.
*
* Bytes specifies the number of bytes to take from the
* string or -1 for the complete NULL-terminated string.
*
* The logical rectangle describes the typographic extents
* and should be used to layout text. The ink rectangle
* describes the smallest rectangle containing all pixels
* that are touched when drawing the string. If you only
* need one of the rectangles, pass NULL for the other one.
*
* The ink rectangle is guaranteed to be a valid rectangle
* with positive width and height, while the logical
* rectangle may have negative width indicating right-to-left
* layout.
*
* The rectangle offsets are reported relative to the
* baseline and refer to the text being drawn using
* DSTF_LEFT.
*/
DFBResult (*GetStringExtents) (
IDirectFBFont *thiz,
const char *text,
int bytes,
DFBRectangle *ret_logical_rect,
DFBRectangle *ret_ink_rect
);
/*
* Get the extents of a glyph specified by its character code.
*
* The rectangle describes the the smallest rectangle
* containing all pixels that are touched when drawing the
* glyph. It is reported relative to the baseline. If you
* only need the advance, pass NULL for the rectangle.
*
* The advance describes the horizontal offset to the next
* glyph (without kerning applied). It may be a negative
* value indicating left-to-right rendering. If you don't
* need this value, pass NULL for advance.
*/
DFBResult (*GetGlyphExtents) (
IDirectFBFont *thiz,
unsigned int character,
DFBRectangle *ret_rect,
int *ret_advance
);
/*
* Get the next explicit or automatic break within a string
* along with the logical width of the text, the string length,
* and a pointer to the next text line.
*
* The bytes specifies the maximum number of bytes to take from the
* string or -1 for complete NULL-terminated string.
*
* The max_width specifies logical width of column onto which
* the text will be drawn. Then the logical width of fitted
* text is returned in ret_width. The returned width may overlap
* the max width specified if there's only one character
* that fits.
*
* The number of characters that fit into this column is
* returned by the ret_str_length. This value can be used as
* the number of bytes to take when using DrawString().
*
* In ret_next_line a pointer to the next line of text is returned. This
* will point to NULL or the end of the string if there's no more break.
*/
DFBResult (*GetStringBreak) (
IDirectFBFont *thiz,
const char *text,
int bytes,
int max_width,
int *ret_width,
int *ret_str_length,
const char **ret_next_line
);
/** Encodings **/
/*
* Change the default encoding used when the font is set at a surface.
*
* It's also the encoding used for the measurement functions
* of this interface, e.g. IDirectFBFont::GetStringExtents().
*/
DFBResult (*SetEncoding) (
IDirectFBFont *thiz,
DFBTextEncodingID encoding
);
/*
* Enumerate all provided text encodings.
*/
DFBResult (*EnumEncodings) (
IDirectFBFont *thiz,
DFBTextEncodingCallback callback,
void *context
);
/*
* Find an encoding by its name.
*/
DFBResult (*FindEncoding) (
IDirectFBFont *thiz,
const char *name,
DFBTextEncodingID *ret_encoding
);
/*
* Get the line spacing vector of this font. This is the
* displacement vector from one line to the next when writing
* several lines of text. It differs from the height only
* when the font is rotated.
*/
DFBResult (*GetLineSpacingVector) (
IDirectFBFont *thiz,
int *ret_xspacing,
int *ret_yspacing
);
/*
* Get the extents of a glyph specified by its character code (extended version).
*
* The rectangle describes the the smallest rectangle
* containing all pixels that are touched when drawing the
* glyph. It is reported relative to the baseline. If you
* only need the advance, pass NULL for the rectangle.
*
* The advance describes the horizontal offset to the next
* glyph (without kerning applied). It may be a negative
* value indicating left-to-right rendering. If you don't
* need this value, pass NULL for advance.
*/
DFBResult (*GetGlyphExtentsXY) (
IDirectFBFont *thiz,
unsigned int character,
DFBRectangle *ret_rect,
int *ret_xadvance,
int *ret_yadvance
);
/** Retrieving information **/
/*
* Get the description of the font.
*/
DFBResult (*GetDescription) (
IDirectFBFont *thiz,
DFBFontDescription *ret_description
);
)
/*
* Capabilities of an image.
*/
typedef enum {
DICAPS_NONE = 0x00000000, /* None of these. */
DICAPS_ALPHACHANNEL = 0x00000001, /* The image data contains an
alphachannel. */
DICAPS_COLORKEY = 0x00000002 /* The image has a colorkey,
e.g. the transparent color
of a GIF image. */
} DFBImageCapabilities;
/*
* Information about an image including capabilities and values
* belonging to available capabilities.
*/
typedef struct {
DFBImageCapabilities caps; /* capabilities */
u8 colorkey_r; /* colorkey red channel */
u8 colorkey_g; /* colorkey green channel */
u8 colorkey_b; /* colorkey blue channel */
} DFBImageDescription;
typedef enum {
DIRCR_OK,
DIRCR_ABORT
} DIRenderCallbackResult;
/*
* Called whenever a chunk of the image is decoded.
* Has to be registered with IDirectFBImageProvider::SetRenderCallback().
*/
typedef DIRenderCallbackResult (*DIRenderCallback)(DFBRectangle *rect, void *ctx);
/**************************
* IDirectFBImageProvider *
**************************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBImageProvider,
/** Retrieving information **/
/*
* Get a surface description that best matches the image
* contained in the file.
*
* For opaque image formats the pixel format of the primary
* layer is used. For images with alpha channel an ARGB
* surface description is returned.
*/
DFBResult (*GetSurfaceDescription) (
IDirectFBImageProvider *thiz,
DFBSurfaceDescription *ret_dsc
);
/*
* Get a description of the image.
*
* This includes stuff that does not belong into the surface
* description, e.g. a colorkey of a transparent GIF.
*/
DFBResult (*GetImageDescription) (
IDirectFBImageProvider *thiz,
DFBImageDescription *ret_dsc
);
/** Rendering **/
/*
* Render the file contents into the destination contents
* doing automatic scaling and color format conversion.
*
* If the image file has an alpha channel it is rendered
* with alpha channel if the destination surface is of the
* ARGB pixelformat. Otherwise, transparent areas are
* blended over a black background.
*
* If a destination rectangle is specified, the rectangle is
* clipped to the destination surface. If NULL is passed as
* destination rectangle, the whole destination surface is
* taken. The image is stretched to fill the rectangle.
*/
DFBResult (*RenderTo) (
IDirectFBImageProvider *thiz,
IDirectFBSurface *destination,
const DFBRectangle *destination_rect
);
/*
* Registers a callback for progressive image loading.
*
* The function is called each time a chunk of the image is decoded.
*/
DFBResult (*SetRenderCallback) (
IDirectFBImageProvider *thiz,
DIRenderCallback callback,
void *callback_data
);
/** Encoding **/
/*
* Encode a portion of a surface.
*/
DFBResult (*WriteBack) (
IDirectFBImageProvider *thiz,
IDirectFBSurface *surface,
const DFBRectangle *src_rect,
const char *filename
);
)
/*
* Capabilities of an audio/video stream.
*/
typedef enum {
DVSCAPS_NONE = 0x00000000, /* None of these. */
DVSCAPS_VIDEO = 0x00000001, /* Stream contains video. */
DVSCAPS_AUDIO = 0x00000002 /* Stream contains audio. */
/* DVSCAPS_SUBPICTURE ?! */
} DFBStreamCapabilities;
#define DFB_STREAM_DESC_ENCODING_LENGTH 30
#define DFB_STREAM_DESC_TITLE_LENGTH 255
#define DFB_STREAM_DESC_AUTHOR_LENGTH 255
#define DFB_STREAM_DESC_ALBUM_LENGTH 255
#define DFB_STREAM_DESC_GENRE_LENGTH 32
#define DFB_STREAM_DESC_COMMENT_LENGTH 255
/*
* Informations about an audio/video stream.
*/
typedef struct {
DFBStreamCapabilities caps; /* capabilities */
struct {
char encoding[DFB_STREAM_DESC_ENCODING_LENGTH]; /* encoding (e.g. "MPEG4") */
double framerate; /* number of frames per second */
double aspect; /* frame aspect ratio */
int bitrate; /* amount of bits per second */
int afd; /* Active Format Descriptor */
int width; /* Width as reported by Sequence Header */
int height; /* Height as reported by Sequence Header */
} video; /* struct containing the above encoding properties for video */
struct {
char encoding[DFB_STREAM_DESC_ENCODING_LENGTH]; /* encoding (e.g. "AAC") */
int samplerate; /* number of samples per second */
int channels; /* number of channels per sample */
int bitrate; /* amount of bits per second */
} audio; /* struct containing the above four encoding properties for audio */
char title[DFB_STREAM_DESC_TITLE_LENGTH]; /* title */
char author[DFB_STREAM_DESC_AUTHOR_LENGTH]; /* author */
char album[DFB_STREAM_DESC_ALBUM_LENGTH]; /* album */
short year; /* year */
char genre[DFB_STREAM_DESC_GENRE_LENGTH]; /* genre */
char comment[DFB_STREAM_DESC_COMMENT_LENGTH]; /* comment */
} DFBStreamDescription;
/*
* Type of an audio stream.
*/
typedef enum {
DSF_ES = 0x00000000, /* ES. */
DSF_PES = 0x00000001, /* PES. */
} DFBStreamFormat;
/*
* Stream attributes for an audio/video stream.
*/
typedef struct {
struct {
char encoding[DFB_STREAM_DESC_ENCODING_LENGTH]; /* encoding (e.g. "MPEG4") */
DFBStreamFormat format; /* format of the video stream */
} video; /* struct containing the above two encoding properties for video */
struct {
char encoding[DFB_STREAM_DESC_ENCODING_LENGTH]; /* encoding (e.g. "AAC") */
DFBStreamFormat format; /* format of the audio stream */
} audio; /* struct containing the above two encoding properties for audio */
} DFBStreamAttributes;
/*
* Buffer levels and occupancy for Audio/Video input buffers.
*/
typedef struct {
DFBStreamCapabilities valid; /* Which of the Audio / Video sections are valid. */
struct {
unsigned int buffer_size; /* Size in bytes of the input buffer to video decoder */
unsigned int minimum_level; /* The level at which a DVPET_DATALOW event will be generated. */
unsigned int maximum_level; /* The level at which a DVPET_DATAHIGH event will be generated. */
unsigned int current_level; /* Current fill level of video input buffer.*/
} video;
struct {
unsigned int buffer_size; /* Size in bytes of the input buffer to audio decoder */
unsigned int minimum_level; /* The level at which a DVPET_DATALOW event will be generated. */
unsigned int maximum_level; /* The level at which a DVPET_DATAHIGH event will be generated. */
unsigned int current_level; /* Current fill level of audio input buffer.*/
} audio;
} DFBBufferOccupancy;
/*
* Buffer thresholds for Audio and Video.
*/
typedef struct {
DFBStreamCapabilities selection; /* Which of the Audio / Video are we setting? */
struct {
unsigned int minimum_level; /* The level at which a DVPET_DATALOW event will be generated. */
unsigned int maximum_level; /* The level at which a DVPET_DATAHIGH event will be generated. */
unsigned int minimum_time; /* The level at which a DVPET_BUFFERTIMELOW event will be generated. */
unsigned int maximum_time; /* The level at which a DVPET_BUFFERTIMEHIGH event will be generated. */
} video;
struct {
unsigned int minimum_level; /* The level at which a DVPET_DATALOW event will be generated. */
unsigned int maximum_level; /* The level at which a DVPET_DATAHIGH event will be generated. */
unsigned int minimum_time; /* The level at which a DVPET_BUFFERTIMELOW event will be generated. */
unsigned int maximum_time; /* The level at which a DVPET_BUFFERTIMEHIGH event will be generated. */
} audio;
} DFBBufferThresholds;
/*
* Called for each written frame.
*/
typedef void (*DVFrameCallback)(void *ctx);
/**************************
* IDirectFBVideoProvider *
**************************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBVideoProvider,
/** Retrieving information **/
/*
* Retrieve information about the video provider's
* capabilities.
*/
DFBResult (*GetCapabilities) (
IDirectFBVideoProvider *thiz,
DFBVideoProviderCapabilities *ret_caps
);
/*
* Get a surface description that best matches the video
* contained in the file.
*/
DFBResult (*GetSurfaceDescription) (
IDirectFBVideoProvider *thiz,
DFBSurfaceDescription *ret_dsc
);
/*
* Get a description of the video stream.
*/
DFBResult (*GetStreamDescription) (
IDirectFBVideoProvider *thiz,
DFBStreamDescription *ret_dsc
);
/** Playback **/
/*
* Play the video rendering it into the specified rectangle
* of the destination surface.
*
* Optionally a callback can be registered that is called
* for each rendered frame. This is especially important if
* you are playing to a flipping surface. In this case, you
* should flip the destination surface in your callback.
*/
DFBResult (*PlayTo) (
IDirectFBVideoProvider *thiz,
IDirectFBSurface *destination,
const DFBRectangle *destination_rect,
DVFrameCallback callback,
void *ctx
);
/*
* Stop rendering into the destination surface.
*/
DFBResult (*Stop) (
IDirectFBVideoProvider *thiz
);
/*
* Get the status of the playback.
*/
DFBResult (*GetStatus) (
IDirectFBVideoProvider *thiz,
DFBVideoProviderStatus *ret_status
);
/** Media Control **/
/*
* Seeks to a position within the stream.
*/
DFBResult (*SeekTo) (
IDirectFBVideoProvider *thiz,
double seconds
);
/*
* Gets current position within the stream.
*/
DFBResult (*GetPos) (
IDirectFBVideoProvider *thiz,
double *ret_seconds
);
/*
* Gets the length of the stream.
*/
DFBResult (*GetLength) (
IDirectFBVideoProvider *thiz,
double *ret_seconds
);
/** Color Adjustment **/
/*
* Gets the current video color settings.
*/
DFBResult (*GetColorAdjustment) (
IDirectFBVideoProvider *thiz,
DFBColorAdjustment *ret_adj
);
/*
* Adjusts the video colors.
*
* This function only has an effect if the video provider
* supports this operation. Check the providers capabilities
* to find out if this is the case.
*/
DFBResult (*SetColorAdjustment) (
IDirectFBVideoProvider *thiz,
const DFBColorAdjustment *adj
);
/** Interactivity **/
/*
* Send an input or window event.
*
* This method allows to redirect events to an interactive
* video provider. Events must be relative to the specified
* rectangle of the destination surface.
*/
DFBResult (*SendEvent) (
IDirectFBVideoProvider *thiz,
const DFBEvent *event
);
/** Advanced control **/
/*
* Set the flags controlling playback mode.
*/
DFBResult (*SetPlaybackFlags) (
IDirectFBVideoProvider *thiz,
DFBVideoProviderPlaybackFlags flags
);
/*
* Set the speed multiplier.
*
* Values below 1.0 reduce playback speed
* while values over 1.0 increase it.<br>
* Specifying a value of 0.0 has the effect of
* putting the playback in pause mode without
* stopping the video provider.
*/
DFBResult (*SetSpeed) (
IDirectFBVideoProvider *thiz,
double multiplier
);
/*
* Get current speed multiplier.
*/
DFBResult (*GetSpeed) (
IDirectFBVideoProvider *thiz,
double *ret_multiplier
);
/*
* Set volume level.
*
* Values between 0.0f and 1.0f adjust the volume level.
* Values over 1.0f increase the amplification level.
*/
DFBResult (*SetVolume) (
IDirectFBVideoProvider *thiz,
float level
);
/*
* Get volume level.
*/
DFBResult (*GetVolume) (
IDirectFBVideoProvider *thiz,
float *ret_level
);
/*
* Set the stream attributes.
* May have a wrapper with different media types types encapsulated.
* Can use this method to indicate the content type.
*/
DFBResult (*SetStreamAttributes) (
IDirectFBVideoProvider *thiz,
DFBStreamAttributes attr
);
/*
* Set the audio units that are being used for output.
* May have multiple audio outputs and need to configure them on/off
* dynamically.
*/
DFBResult (*SetAudioOutputs) (
IDirectFBVideoProvider *thiz,
DFBVideoProviderAudioUnits *audioUnits
);
/*
* Get the audio units that are being used for output.
*/
DFBResult (*GetAudioOutputs) (
IDirectFBVideoProvider *thiz,
DFBVideoProviderAudioUnits *audioUnits
);
/*
* Set the audio delay
*
* The parameter is in microseconds. Values < 0 make audio earlier, > 0 make audio later.
*/
DFBResult (*SetAudioDelay) (
IDirectFBVideoProvider *thiz,
long delay
);
/** Event buffers **/
/*
* Create an event buffer for this video provider and attach it.
*/
DFBResult (*CreateEventBuffer) (
IDirectFBVideoProvider *thiz,
IDirectFBEventBuffer **ret_buffer
);
/*
* Attach an existing event buffer to this video provider.
*
* NOTE: Attaching multiple times generates multiple events.
*/
DFBResult (*AttachEventBuffer) (
IDirectFBVideoProvider *thiz,
IDirectFBEventBuffer *buffer
);
/*
* Enable specific events to be sent from the video provider.
*
* The argument is a mask of events that will be set in the
* videoproviders's event mask. The default event mask is DVPET_ALL.
*/
DFBResult (*EnableEvents) (
IDirectFBVideoProvider *thiz,
DFBVideoProviderEventType mask
);
/*
* Disable specific events from being sent from the video provider
*
* The argument is a mask of events that will be cleared in
* the video providers's event mask. The default event mask is DWET_ALL.
*/
DFBResult (*DisableEvents) (
IDirectFBVideoProvider *thiz,
DFBVideoProviderEventType mask
);
/*
* Detach an event buffer from this video provider.
*/
DFBResult (*DetachEventBuffer) (
IDirectFBVideoProvider *thiz,
IDirectFBEventBuffer *buffer
);
/** Buffer control **/
/*
* Get buffer occupancy (A/V) when playing this stream.
*/
DFBResult (*GetBufferOccupancy) (
IDirectFBVideoProvider *thiz,
DFBBufferOccupancy *ret_occ
);
/*
* Set buffer thresholds for the Audio / Video playback.
*/
DFBResult (*SetBufferThresholds) (
IDirectFBVideoProvider *thiz,
DFBBufferThresholds thresh
);
/*
* Get buffer thresholds for the Audio / Video playback.
*/
DFBResult (*GetBufferThresholds) (
IDirectFBVideoProvider *thiz,
DFBBufferThresholds *ret_thresh
);
)
/***********************
* IDirectFBDataBuffer *
***********************/
/*
* <i>No summary yet...</i>
*/
DEFINE_INTERFACE( IDirectFBDataBuffer,
/** Buffer handling **/
/*
* Flushes all data in this buffer.
*
* This method only applies to streaming buffers.
*/
DFBResult (*Flush) (
IDirectFBDataBuffer *thiz
);
/*
* Finish writing into a streaming buffer.
*
* Subsequent calls to PutData will fail,
* while attempts to fetch data from the buffer will return EOF
* unless there is still data available.
*/
DFBResult (*Finish) (
IDirectFBDataBuffer *thiz
);
/*
* Seeks to a given byte position.
*
* This method only applies to static buffers.
*/
DFBResult (*SeekTo) (
IDirectFBDataBuffer *thiz,
unsigned int offset
);
/*
* Get the current byte position within a static buffer.
*
* This method only applies to static buffers.
*/
DFBResult (*GetPosition) (
IDirectFBDataBuffer *thiz,
unsigned int *ret_offset
);
/*
* Get the length of a static or streaming buffer in bytes.
*
* The length of a static buffer is its static size.
* A streaming buffer has a variable length reflecting
* the amount of buffered data.
*/
DFBResult (*GetLength) (
IDirectFBDataBuffer *thiz,
unsigned int *ret_length
);
/** Waiting for data **/
/*
* Wait for data to be available.
* Thread is idle in the meantime.
*
* This method blocks until at least the specified number of bytes
* is available.
*/
DFBResult (*WaitForData) (
IDirectFBDataBuffer *thiz,
unsigned int length
);
/*
* Wait for data to be available within an amount of time.
* Thread is idle in the meantime.
*
* This method blocks until at least the specified number of bytes
* is available or the timeout is reached.
*/
DFBResult (*WaitForDataWithTimeout) (
IDirectFBDataBuffer *thiz,
unsigned int length,
unsigned int seconds,
unsigned int milli_seconds
);
/** Retrieving data **/
/*
* Fetch data from a streaming or static buffer.
*
* Static buffers will increase the data pointer.
* Streaming buffers will flush the data portion.
*
* The maximum number of bytes to fetch is specified by "length",
* the actual number of bytes fetched is returned via "read".
*/
DFBResult (*GetData) (
IDirectFBDataBuffer *thiz,
unsigned int length,
void *ret_data,
unsigned int *ret_read
);
/*
* Peek data from a streaming or static buffer.
*
* Unlike GetData() this method won't increase the data
* pointer or flush any portions of the data held.
*
* Additionally an offset relative to the current data pointer
* or beginning of the streaming buffer can be specified.
*
* The maximum number of bytes to peek is specified by "length",
* the actual number of bytes peeked is returned via "read".
*/
DFBResult (*PeekData) (
IDirectFBDataBuffer *thiz,
unsigned int length,
int offset,
void *ret_data,
unsigned int *ret_read
);
/*
* Check if there is data available.
*
* This method returns DFB_OK if there is data available,
* DFB_BUFFER_EMPTY otherwise.
*/
DFBResult (*HasData) (
IDirectFBDataBuffer *thiz
);
/** Providing data **/
/*
* Appends a block of data to a streaming buffer.
*
* This method does not wait until the data got fetched.
*
* Static buffers don't support this method.
*/
DFBResult (*PutData) (
IDirectFBDataBuffer *thiz,
const void *data,
unsigned int length
);
/** Media from data **/
/*
* Creates an image provider using the buffers data.
*/
DFBResult (*CreateImageProvider) (
IDirectFBDataBuffer *thiz,
IDirectFBImageProvider **interface
);
/*
* Creates a video provider using the buffers data.
*/
DFBResult (*CreateVideoProvider) (
IDirectFBDataBuffer *thiz,
IDirectFBVideoProvider **interface
);
/*
* Load a font using the buffer's data, given a description
* of how to load the glyphs.
*/
DFBResult (*CreateFont) (
IDirectFBDataBuffer *thiz,
const DFBFontDescription *desc,
IDirectFBFont **interface
);
)
#ifdef __cplusplus
}
#endif
#endif
| {
"content_hash": "62f76256541cee4bfac515a390db569f",
"timestamp": "",
"source": "github",
"line_count": 6588,
"max_line_length": 126,
"avg_line_length": 35.17972070431087,
"alnum_prop": 0.529706943269878,
"repo_name": "tim-vandecasteele/Philips-Wifi-TV-Remote",
"id": "2f2b2800e633ac5ced38b0dac5343f84f7ab90dd",
"size": "232936",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Libs/DirectFB_Voodoo/include/directfb.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "719592"
},
{
"name": "C++",
"bytes": "121374"
},
{
"name": "Objective-C",
"bytes": "119273"
}
],
"symlink_target": ""
} |
import os
import argparse
from abroad.data_creation import hdf_creation as hdf
from abroad.data_creation import merge_data
def file_walk(hdf_fname, rootDir, create_file=True):
"""
Walk through a directory of files to create the necessary
HDF5 file.
Inputs:
:param hdf_fname: The expected HDF5 file name and location
:type hdf_fname: str
:param rootDir: The directory containing the CSV files.
: type rootDir: str
:param create_file: Argument as to whether the HDF5 file needs creating.
:type create_file: bool
"""
print('Initiating File Walk')
for dirName, subdirList, fileList in os.walk(rootDir):
if 'SUBJECT' in dirName:
print('Found directory: %s' % dirName)
for fname in fileList:
print('\t Processing %s' % fname)
if 'time' in fname:
time_file = os.path.join(dirName, fname)
elif ('conc_7' in fname):
conc_7 = os.path.join(dirName, fname)
elif ('conc_13' in fname):
conc_13 = os.path.join(dirName, fname)
elif ('raw_7' in fname):
raw_7 = os.path.join(dirName, fname)
elif ('raw_13' in fname):
raw_13 = os.path.join(dirName, fname)
else:
pass
HDF = hdf.HDF5_Subject(hdf_fname, int(dirName[-3:]),
raw_7, conc_7, time_file, 7)
if create_file:
try:
open(hdf_fname, 'x')
HDF.file_creation()
print("\n\t File created. \n")
create_file = False
except:
print("\n File already exists.")
HDF.print_file()
HDF.append_time_data()
HDF.append_raw_data()
HDF.append_conc_data()
del HDF
HDF = hdf.HDF5_Subject(hdf_fname, int(dirName[-3:]),
raw_13, conc_13,
time_file, 13)
if create_file:
try:
open(hdf_fname, 'x')
HDF.file_creation()
print("\n\t File created. \n")
create_file = False
except FileExistsError:
print("\n File already exists.")
HDF.print_file()
HDF.append_time_data()
HDF.append_raw_data()
HDF.append_conc_data()
else:
print('No subject data')
pass
def main():
parser = argparse.ArgumentParser(description='Walk files to create HDF5')
parser.add_argument(
'hdf_fname', type=str, help="Path to HDF file", metavar='HDF_FILE')
parser.add_argument(
'rootDir', type=str, help="Root directory to walk", metavar='ROOT_DIR')
args = parser.parse_args()
print('\n%s\n%s' % (args.hdf_fname, args.rootDir))
file_walk(args.hdf_fname, args.rootDir)
for sensor_num in [7,13]:
merge_data.merge_main(sensor_num, hdf_file=args.hdf_fname)
if __name__ == '__main__':
main()
| {
"content_hash": "f431842b81b50dd1f96491544ad71ba5",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 79,
"avg_line_length": 34.0531914893617,
"alnum_prop": 0.5082786629178382,
"repo_name": "buck06191/ABROAD",
"id": "dd0fc26696b2c8aa17109e56ed21167443b3d052",
"size": "3201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "file_walk.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "541927"
},
{
"name": "Python",
"bytes": "46223"
},
{
"name": "Shell",
"bytes": "273"
}
],
"symlink_target": ""
} |
JSONNET_FMT := jsonnetfmt -n 2 --max-blank-lines 2 --string-style s --comment-style s
all: fmt prometheus_alerts.yaml dashboards_out lint
fmt:
find . -name 'vendor' -prune -o -name '*.libsonnet' -print -o -name '*.jsonnet' -print | \
xargs -n 1 -- $(JSONNET_FMT) -i
prometheus_alerts.yaml: mixin.libsonnet config.libsonnet alerts.libsonnet
jsonnet -S alerts.jsonnet > $@
dashboards_out: mixin.libsonnet config.libsonnet dashboards.libsonnet
@mkdir -p dashboards_out
jsonnet -J vendor -m dashboards_out dashboards.jsonnet
lint: prometheus_alerts.yaml
find . -name 'vendor' -prune -o -name '*.libsonnet' -print -o -name '*.jsonnet' -print | \
while read f; do \
$(JSONNET_FMT) "$$f" | diff -u "$$f" -; \
done
promtool check rules prometheus_alerts.yaml
.PHONY: jb_install
jb_install:
jb install
clean:
rm -rf dashboards_out prometheus_alerts.yaml
| {
"content_hash": "b3e2941dcf6bab88cf58cf3a4d835363",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 91,
"avg_line_length": 30,
"alnum_prop": 0.7057471264367816,
"repo_name": "prometheus/prometheus",
"id": "c3023274c823439205bbba2c5459d8fe1ce5798b",
"size": "870",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "documentation/prometheus-mixin/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3721"
},
{
"name": "Dockerfile",
"bytes": "1270"
},
{
"name": "Go",
"bytes": "4893777"
},
{
"name": "HTML",
"bytes": "30454"
},
{
"name": "JavaScript",
"bytes": "28251"
},
{
"name": "Lex",
"bytes": "5982"
},
{
"name": "Makefile",
"bytes": "3930"
},
{
"name": "SCSS",
"bytes": "12847"
},
{
"name": "Shell",
"bytes": "16198"
},
{
"name": "TypeScript",
"bytes": "470223"
},
{
"name": "Yacc",
"bytes": "26012"
}
],
"symlink_target": ""
} |
package cfgclient
import (
"context"
"errors"
"net/http"
"go.chromium.org/luci/config"
"go.chromium.org/luci/config/impl/erroring"
"go.chromium.org/luci/config/impl/filesystem"
"go.chromium.org/luci/config/impl/remote"
"go.chromium.org/luci/config/impl/resolving"
"go.chromium.org/luci/config/vars"
)
// Options describe how to configure a LUCI Config client.
type Options struct {
// Vars define how to substitute ${var} placeholders in config sets and paths.
//
// If nil, vars are not allowed. Pass &vars.Vars explicitly to use the global
// var set.
Vars *vars.VarSet
// ServiceHost is a hostname of a LUCI Config service to use.
//
// If given, indicates configs should be fetched from the LUCI Config service.
// Requires ClientFactory to be provided as well. Not compatible with
// ConfigsDir.
ServiceHost string
// ConfigsDir is a file system directory to fetch configs from instead of
// a LUCI Config service.
//
// See https://godoc.org/go.chromium.org/luci/config/impl/filesystem for the
// expected layout of this directory.
//
// Useful when running locally in development mode. Not compatible with
// ServiceHost.
ConfigsDir string
// ClientFactory initializes an authenticating HTTP client on demand.
//
// It will be used to call LUCI Config service. Must be set if ServiceHost is
// set, ignored otherwise.
ClientFactory func(context.Context) (*http.Client, error)
}
// New instantiates a LUCI Config client based on the given options.
//
// The client fetches configs either from a LUCI Config service or from a local
// directory on disk (e.g. when running locally in development mode), depending
// on values of ServiceHost and ConfigsDir. If neither are set, returns a client
// that fails all calls with an error.
func New(opts Options) (config.Interface, error) {
switch {
case opts.ServiceHost == "" && opts.ConfigsDir == "":
return erroring.New(errors.New("LUCI Config client is not configured")), nil
case opts.ServiceHost != "" && opts.ConfigsDir != "":
return nil, errors.New("either a LUCI Config service or a local config directory should be used, not both")
case opts.ServiceHost != "" && opts.ClientFactory == nil:
return nil, errors.New("need a client factory when using a LUCI Config service")
}
var base config.Interface
switch {
case opts.ServiceHost != "":
base = remote.New(opts.ServiceHost, false, opts.ClientFactory)
case opts.ConfigsDir != "":
var err error
if base, err = filesystem.New(opts.ConfigsDir); err != nil {
return nil, err
}
default:
panic("impossible")
}
varz := opts.Vars
if varz == nil {
varz = &vars.VarSet{} // empty: all var references will result in an error
}
return resolving.New(varz, base), nil
}
| {
"content_hash": "eab52c24540fd8d71f88e7bee5cb5744",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 109,
"avg_line_length": 33.036144578313255,
"alnum_prop": 0.725382932166302,
"repo_name": "luci/luci-go",
"id": "0ff8fa76f45a093d47b23abe3b67e2c419d6114a",
"size": "3338",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "config/cfgclient/client.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25460"
},
{
"name": "Go",
"bytes": "10674259"
},
{
"name": "HTML",
"bytes": "658081"
},
{
"name": "JavaScript",
"bytes": "18433"
},
{
"name": "Makefile",
"bytes": "2862"
},
{
"name": "Python",
"bytes": "49205"
},
{
"name": "Shell",
"bytes": "20986"
},
{
"name": "TypeScript",
"bytes": "110221"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jun 10 10:20:18 MST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.jgroups.Stack (BOM: * : All 2.6.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2020-06-10">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.jgroups.Stack (BOM: * : All 2.6.1.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/jgroups/class-use/Stack.html" target="_top">Frames</a></li>
<li><a href="Stack.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.jgroups.Stack" class="title">Uses of Class<br>org.wildfly.swarm.config.jgroups.Stack</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config">org.wildfly.swarm.config</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.jgroups">org.wildfly.swarm.config.jgroups</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a> in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> that return <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></code></td>
<td class="colLast"><span class="typeNameLabel">JGroups.JGroupsResources.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/JGroups.JGroupsResources.html#stack-java.lang.String-">stack</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> that return types with arguments of type <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a>></code></td>
<td class="colLast"><span class="typeNameLabel">JGroups.JGroupsResources.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/JGroups.JGroupsResources.html#stacks--">stacks</a></span>()</code>
<div class="block">Get the list of Stack resources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/JGroups.html" title="type parameter in JGroups">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">JGroups.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/JGroups.html#stack-org.wildfly.swarm.config.jgroups.Stack-">stack</a></span>(<a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a> value)</code>
<div class="block">Add the Stack object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> with type arguments of type <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/JGroups.html" title="type parameter in JGroups">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">JGroups.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/JGroups.html#stacks-java.util.List-">stacks</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a>> value)</code>
<div class="block">Add all Stack objects to this subresource</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.jgroups">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a> in <a href="../../../../../../org/wildfly/swarm/config/jgroups/package-summary.html">org.wildfly.swarm.config.jgroups</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../org/wildfly/swarm/config/jgroups/package-summary.html">org.wildfly.swarm.config.jgroups</a> with type parameters of type <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a><T extends <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a><T>></span></code>
<div class="block">The configuration of a JGroups protocol stack.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/jgroups/StackConsumer.html" title="interface in org.wildfly.swarm.config.jgroups">StackConsumer</a><T extends <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a><T>></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/jgroups/StackSupplier.html" title="interface in org.wildfly.swarm.config.jgroups">StackSupplier</a><T extends <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a>></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/jgroups/package-summary.html">org.wildfly.swarm.config.jgroups</a> that return <a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Stack</a></code></td>
<td class="colLast"><span class="typeNameLabel">StackSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/jgroups/StackSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of Stack resource</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/jgroups/Stack.html" title="class in org.wildfly.swarm.config.jgroups">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/jgroups/class-use/Stack.html" target="_top">Frames</a></li>
<li><a href="Stack.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "086d4dcd4f40c6b96b1889ba94f9d904",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 500,
"avg_line_length": 56.69230769230769,
"alnum_prop": 0.6586160108548168,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "7b3d7d9c7f97d45a83e4c7d86ef3e41be57dc5fa",
"size": "14740",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.6.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/jgroups/class-use/Stack.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using EvilDICOM.Core.Enums;
using EvilDICOM.Core.Helpers;
using EvilDICOM.Core.Interfaces;
namespace EvilDICOM.Core.Dictionaries
{
/// <summary>
/// General purpose class for working with VRs. It contains methods to convert ASCII string abbreviations into VR type,
/// the reverse,
/// and a few more useful methods when working with VR enums.
/// </summary>
public class VRDictionary
{
/// <summary>
/// Finds the VR type from an DICOM two letter abbreviation.
/// </summary>
/// <param name="vrAbbreviation">an DICOM two letter abbreviation</param>
/// <returns>the VR type</returns>
public static VR GetVRFromAbbreviation(string vrAbbreviation)
{
switch (vrAbbreviation)
{
case "CS":
return VR.CodeString;
case "SH":
return VR.ShortString;
case "LO":
return VR.LongString;
case "ST":
return VR.ShortText;
case "LT":
return VR.LongText;
case "UT":
return VR.UnlimitedText;
case "AE":
return VR.ApplicationEntity;
case "PN":
return VR.PersonName;
case "UI":
return VR.UniqueIdentifier;
case "DA":
return VR.Date;
case "TM":
return VR.Time;
case "DT":
return VR.DateTime;
case "AS":
return VR.AgeString;
case "IS":
return VR.IntegerString;
case "DS":
return VR.DecimalString;
case "SS":
return VR.SignedShort;
case "US":
return VR.UnsignedShort;
case "SL":
return VR.SignedLong;
case "UL":
return VR.UnsignedLong;
case "AT":
return VR.AttributeTag;
case "FL":
return VR.FloatingPointSingle;
case "FD":
return VR.FloatingPointDouble;
case "OB":
return VR.OtherByteString;
case "OW":
return VR.OtherWordString;
case "OF":
return VR.OtherFloatString;
case "SQ":
return VR.Sequence;
case "UN":
return VR.Unknown;
default:
return VR.Null;
}
}
/// <summary>
/// Creates the DICOM two letter abbreviation from a VR type.
/// </summary>
/// <param name="vr">the VR type</param>
/// <returns>the DICOM two letter abbreviation</returns>
public static string GetAbbreviationFromVR(VR vr)
{
switch (vr)
{
case VR.CodeString:
return "CS";
case VR.ShortString:
return "SH";
case VR.LongString:
return "LO";
case VR.ShortText:
return "ST";
case VR.LongText:
return "LT";
case VR.UnlimitedText:
return "UT";
case VR.ApplicationEntity:
return "AE";
case VR.PersonName:
return "PN";
case VR.UniqueIdentifier:
return "UI";
case VR.Date:
return "DA";
case VR.Time:
return "TM";
case VR.DateTime:
return "DT";
case VR.AgeString:
return "AS";
case VR.IntegerString:
return "IS";
case VR.DecimalString:
return "DS";
case VR.SignedShort:
return "SS";
case VR.UnsignedShort:
return "US";
case VR.SignedLong:
return "SL";
case VR.UnsignedLong:
return "UL";
case VR.AttributeTag:
return "AT";
case VR.FloatingPointSingle:
return "FL";
case VR.FloatingPointDouble:
return "FD";
case VR.OtherByteString:
return "OB";
case VR.OtherWordString:
return "OW";
case VR.OtherFloatString:
return "OF";
case VR.Sequence:
return "SQ";
case VR.Unknown:
return "UN";
default:
return string.Empty;
}
}
/// <summary>
/// Finds the VR enum from a specific DICOM element.
/// </summary>
/// <param name="el">the DICOM element</param>
/// <returns>the VR type</returns>
public static VR GetVRFromType(IDICOMElement el)
{
Type t = el.GetType();
return EnumHelper.StringToEnum<VR>(t.Name);
}
/// <summary>
/// Finds the VR enum from a specific DICOM element type.
/// </summary>
/// <param name="el">the DICOM element</param>
/// <returns>the VR type</returns>
public static VR GetVRFromType(Type t)
{
return EnumHelper.StringToEnum<VR>(t.Name);
}
/// <summary>
/// Finds the VR enum from a specific DICOM element.
/// </summary>
/// <param name="el">the DICOM element</param>
/// <returns>the VR abbreviation</returns>
public static string GetAbbreviationFromType(IDICOMElement el)
{
Type t = el.GetType();
var vr = EnumHelper.StringToEnum<VR>(t.Name);
return GetAbbreviationFromVR(vr);
}
/// <summary>
/// Finds the VR enum from a specific DICOM element.
/// </summary>
/// <param name="el">the DICOM element</param>
/// <returns>the VR abbreviation</returns>
public static string GetAbbreviationFromType(Type t)
{
var vr = EnumHelper.StringToEnum<VR>(t.Name);
return GetAbbreviationFromVR(vr);
}
/// <summary>
/// Determines the encoding, meaning how many bytes to write the VR and length parameters, from a VR type.
/// Options are explicit long (8 bytes), explicit short (4 bytes), or implicit (4 bytes). In Evil DICOM, the null
/// VR is used to represent an unknown VR (before dictionary lookup) that is implicitly encoded.
/// </summary>
/// <param name="vr">the VR type</param>
/// <returns>the encoding method for this type</returns>
public static VREncoding GetEncodingFromVR(VR vr)
{
switch (vr)
{
case VR.OtherByteString:
case VR.OtherWordString:
case VR.OtherFloatString:
case VR.Sequence:
case VR.Unknown:
return VREncoding.ExplicitLong;
case VR.Null:
return VREncoding.Implicit;
default:
return VREncoding.ExplicitShort;
}
}
}
} | {
"content_hash": "9ab6a6cfadd8e2b0fca934620415f9c1",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 127,
"avg_line_length": 36.401826484018265,
"alnum_prop": 0.4433015554440542,
"repo_name": "cureos/Evil-DICOM",
"id": "b48dea2dc4d618d875bd6985e90384fecd7b320e",
"size": "7974",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "EvilDICOM/EvilDICOM/Core/Dictionaries/VRDictionary.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "4804895"
}
],
"symlink_target": ""
} |
/*
The u8glib screens were started and later abandoned due to performance issues.
Here for reference should anyone want to take on this task.
Shea Ivey
*/
#include "settings.h"
#ifdef OLED_128x64_U8G_SCREENS
#include "screens.h" // function headers
#include <U8glib.h>
#define BLACK 0
#define WHITE 1
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0|U8G_I2C_OPT_NO_ACK|U8G_I2C_OPT_FAST); // Fast I2C / TWI
screens::screens() {
reset();
}
char screens::begin() {
return 0;
}
void screens::reset() {
u8g.setFont(u8g_font_fixed_v0);
u8g.setFontRefHeightExtendedText();
u8g.setDefaultForegroundColor();
u8g.setFontPosTop();
u8g.setColorIndex(WHITE);
}
void screens::flip() {
u8g.setRot180();
}
void screens::drawTitleBox(const char *title) {
u8g.setColorIndex(WHITE);
u8g.drawFrame(0, 0, u8g.getWidth(), u8g.getHeight());
u8g.drawBox(0, 0, u8g.getWidth(), 11);
u8g.setColorIndex(BLACK);
// center text
u8g.setPrintPos(((u8g.getWidth() - u8g.getStrWidth(title)) / 2),1);
u8g.print(title);
}
void screens::mainMenu(uint8_t menu_id){
u8g.firstPage();
do {
reset(); // start from fresh screen.
drawTitleBox("MODE SELECTION");
u8g.setColorIndex(WHITE);
u8g.drawBox(0, 10*menu_id+12, u8g.getWidth(), 10);
u8g.setColorIndex(menu_id == 0 ? BLACK : WHITE);
u8g.setPrintPos(5,10*0+12);
u8g.print("AUTO SEARCH");
u8g.setColorIndex(menu_id == 1 ? BLACK : WHITE);
u8g.setPrintPos(5,10*1+12);
u8g.print("BAND SCANNER");
u8g.setColorIndex(menu_id == 2 ? BLACK : WHITE);
u8g.setPrintPos(5,10*2+12);
u8g.print("MANUAL MODE");
#ifdef USE_DIVERSITY
u8g.setColorIndex(menu_id == 3 ? BLACK : WHITE);
u8g.setPrintPos(5,10*3+12);
u8g.print("DIVERSITY");
#endif
u8g.setColorIndex(menu_id == 4 ? BLACK : WHITE);
u8g.setPrintPos(5,10*4+12);
u8g.print("SAVE SETUP");
} while( u8g.nextPage() );
}
void screens::seekMode(uint8_t state) {
last_channel = -1;
reset(); // start from fresh screen.
}
void screens::updateSeekMode(uint8_t state, uint8_t channelIndex, uint8_t channel, uint8_t rssi, uint16_t channelFrequency, bool locked) {
last_channel = channel;
}
void screens::bandScanMode(uint8_t state) {
reset(); // start from fresh screen.
best_rssi = 0;
if(state==STATE_SCAN)
{
drawTitleBox("BAND SCANNER");
}
else
{
drawTitleBox("RSSI SETUP");
}
}
void screens::updateBandScanMode(bool in_setup, uint8_t channel, uint8_t rssi, uint8_t channelName, uint16_t channelFrequency, uint16_t rssi_setup_min_a, uint16_t rssi_setup_max_a) {
static uint8_t writePos=SCANNER_LIST_X_POS;
last_channel = channel;
}
void screens::screenSaver(uint8_t channelName, uint16_t channelFrequency) {
screenSaver(-1, channelName, channelFrequency);
}
void screens::screenSaver(uint8_t diversity_mode, uint8_t channelName, uint16_t channelFrequency) {
}
void screens::updateScreenSaver(uint8_t rssi) {
updateScreenSaver(-1, rssi, -1, -1);
}
void screens::updateScreenSaver(char active_receiver, uint8_t rssi, uint8_t rssiA, uint8_t rssiB) {
}
#ifdef USE_DIVERSITY
void screens::diversity(uint8_t diversity_mode) {
reset();
drawTitleBox("DIVERSITY");
}
void screens::updateDiversity(char active_receiver, uint8_t rssiA, uint8_t rssiB){
}
#endif
void screens::save(uint8_t mode, uint8_t channelIndex, uint16_t channelFrequency) {
reset();
drawTitleBox("SAVE SETTINGS");
}
void screens::updateSave(const char * msg) {
}
#endif
| {
"content_hash": "80ab29f81c00516031b6d02934cf8c85",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 182,
"avg_line_length": 26.013793103448275,
"alnum_prop": 0.633881230116649,
"repo_name": "Snebajer1/FPV-receiver-diversity-hack",
"id": "d6fa512c453d4a608990ac277cf49fb7f861a795",
"size": "4909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/rx5808-pro-diversity/oled_128x64_u8g_screens.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "40233"
},
{
"name": "C",
"bytes": "18000"
},
{
"name": "C++",
"bytes": "156662"
},
{
"name": "Processing",
"bytes": "11460"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item>
<question>problèmes,box,pas,internet,connexion,rj45,cables,localhost</question>
<response>Veuillez vérifier si le branchement de vos câbles est correct et si tous les voyants sont allumés sur votre box internet.</response>
</Item>
<Item>
<question>président,republique,française,france</question>
<response>Emmanuel MACRON (En Marche)</response>
</Item>
<Item>
<question>qui,macron,parcours,biographie,carrière,vie</question>
<response>Ancien banquier d'affaires chez Rotschild.</response>
</Item>
<Item>
<question>elu,election,president,république,francaise,date,2017, president de la republique</question>
<response>Le président a été élu le 6 mai 2017.</response>
</Item>
<Item>
<question>date,cree,internet</question>
<response>Internet a été crée en 1994.</response>
</Item>
<Item>
<question>date,cree,creation, jours,année,youtube</question>
<response>Youtube a été crée le 24 Février 2005.</response>
</Item>
<Item>
<question>rj45,couleur,cable,cablage, reseau, filliere, fils</question>
<response>Le RJ45 est le nom usuel du connecteur 8P8C (8 positions et 8 contacts électriques) utilisé couramment pour les connexions Ethernet, et pour les connecteurs téléphoniques. .</response>
</Item>
<Item>
<question>date,version,création,windows, bill, gates, Bill Gates</question>
<response>La première version de Windows date du 20 novembre 1985.</response>
</Item>
<Item>
<question>web, service, web-service, web-services, curl</question>
<response>Ah on parle de web-service, c'est super</response>
</Item>
<Item>
<question>wikipedia, données, wiki, ressource</question>
<response>Ah on parle de Wikipédia qui à été lancée officiellement le 15 janvier 2001 pour soutenir Nupedia</response>
</Item>
<Item>
<question>facebook, réseaux, sociaux, social, book, mark ,zuckerberg, Marc, ZUCKERBERG</question>
<response>Ah facebook et son célèbre créateur mark zuckerberg ! Qu'est que les jeunes ferai sans ça !</response>
</Item>
<Item>
<question>quand, cree, facebook, date, create, création, 2004</question>
<response>Facebook a été créé en 2004</response>
</Item>
<Item>
<question>quand, cree, twitter, twit, bird, oiseaux, création, 2006</question>
<response> Twitter a été créé le 21 mars 2006 par Jack Dorsey, Evan Williams, Biz Stone et Noah Glass</response>
</Item>
<Item>
<question>quand, cree, you, tube, youtube, vidéo, streaming, live, youtubeurs, youtubeuses</question>
<response> YouTube à été créé le 14 février 2005, San Mateo, Californie, États-Unis</response>
</Item>
<Item>
<question>quand, ou, Netflix, film, series, continue, streaming</question>
<response> Netflix à été crée 29 août 1997, Scotts Valley, Californie, États-Unis</response>
</Item>
<Item>
<question>Slack, chat, tchat, IRC, logiciel, gestion, projet</question>
<response> Slack est une plate-forme de communication collaborative propriétaire .En octobre 2014, la startup est valorisée à plus d'un milliard de dollars.</response>
</Item>
<Item>
<question>quand, né, Edouard, Joseph, Snowden, informaticien, celebre, CIA, espions</question>
<response>Edward Joseph Snowden, né le 21 juin 1983 à Elizabeth City, Caroline du Nord, est un informaticien américain1, ancien employé de la(CIA) et de la NSA.</response>
</Item>
<Item>
<question>git, hub, github, versionning, performant, souvent, ink</question>
<response>GitHub est un service web d'hébergement et de gestion de développement de logiciels, utilisant le logiciel de gestion de versions Git. Ce site est développé en Ruby on Rails et Erlang par Chris Wanstrath, PJ Hyett et Tom Preston-Werner.</response>
</Item>
<Item>
<question>git, hub, github, versionning, performant, souvent, ink</question>
<response>GitHub est un service web d'hébergement et de gestion de développement de logiciels, utilisant le logiciel de gestion de versions Git.</response>
</Item>
<Item>
<question>cloud, computing, google, nuages, stockage, performant, internet, sauvegrde, sauvegarder</question>
<response>Le terme Cloud (nuage en anglais), particulièrement dans l'air du temps, recouvre l'ensemble des solutions de stockage distant.</response>
</Item>
<Item>
<question>dell, pc, windows, fondateur, intel</question>
<response>Un bon pc</response>
</Item>
</Items>
| {
"content_hash": "5355a553f398d3bebade7e796c66b662",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 259,
"avg_line_length": 50.206896551724135,
"alnum_prop": 0.7454212454212454,
"repo_name": "corentinmb/interface2037",
"id": "6fcb6a9950cb6a207cb957832b067569ada592c3",
"size": "4444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SystemeExpert/src/main/resources/xmltoparse.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "2299"
},
{
"name": "HTML",
"bytes": "4465"
},
{
"name": "Java",
"bytes": "28973"
}
],
"symlink_target": ""
} |
package org.estatio.module.lease.dom.party;
import javax.inject.Inject;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.Contributed;
import org.apache.isis.applib.annotation.Mixin;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.estatio.module.party.dom.Party;
@Mixin(method = "prop")
public class Party_administrationRecord {
private final Party party;
public Party_administrationRecord(Party party) {
this.party = party;
}
@Action(semantics = SemanticsOf.SAFE)
@ActionLayout(contributed = Contributed.AS_ASSOCIATION)
public TenantAdministrationRecord prop() {
return tenantAdministrationRecordRepository.latestForParty(party);
}
public boolean hideProp(){
return !party.isTenant();
}
@Inject
TenantAdministrationRecordRepository tenantAdministrationRecordRepository;
}
| {
"content_hash": "0372af354137f35c58e6290e6d9e08ff",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 78,
"avg_line_length": 29.12121212121212,
"alnum_prop": 0.7637877211238293,
"repo_name": "estatio/estatio",
"id": "328c6376a803a643459a1ce1565354ab15e228ea",
"size": "961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "estatioapp/app/src/main/java/org/estatio/module/lease/dom/party/Party_administrationRecord.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4016"
},
{
"name": "FreeMarker",
"bytes": "122229"
},
{
"name": "HTML",
"bytes": "61077"
},
{
"name": "Java",
"bytes": "9066306"
},
{
"name": "JavaScript",
"bytes": "1226"
},
{
"name": "Shell",
"bytes": "2202"
},
{
"name": "TSQL",
"bytes": "9363"
}
],
"symlink_target": ""
} |
import os, argparse
from django.core.management.base import CommandError
from django.contrib.auth.models import User
from django.conf import settings
from apps.m2mbench.models import Board, Thread, Post
from ._base_command import _BaseCommand
class Command(_BaseCommand):
help = 'Generate m2mbench fixtures according to command line arguments or settings.'
def get_next_board_pk(self):
try:
return Board.objects.order_by('-id')[0].id + 1
except IndexError:
return 1
except Board.DoesNotExist:
return 1
def get_next_thread_pk(self):
try:
return Thread.objects.order_by('-id')[0].id + 1
except IndexError:
return 1
except Thread.DoesNotExist:
return 1
def get_next_post_pk(self):
try:
return Post.objects.order_by('-id')[0].id + 1
except IndexError:
return 1
except Post.DoesNotExist:
return 1
def add_arguments(self, parser):
parser.add_argument(
'-nb', '--num-boards',
dest='num_boards',
metavar='NUM_BOARDS',
type=self.positive_int,
default=settings.JSONBENCH_NUM_BOARDS,
help=('A positive integer representing the number of boards to generate. '
'Default is {}.'.format(settings.JSONBENCH_NUM_BOARDS))
)
parser.add_argument(
'-nt', '--num-threads',
dest='num_threads',
metavar='NUM_THREADS',
type=self.positive_int,
default=settings.JSONBENCH_NUM_THREADS,
help=('A positive integer representing the number of threads per board to generate. '
'Default is {}.'.format(settings.JSONBENCH_NUM_THREADS))
)
parser.add_argument(
'-np', '--num-posts',
dest='num_posts',
metavar='NUM_POSTS',
type=self.positive_int,
default=settings.JSONBENCH_NUM_POSTS,
help=('A positive integer representing the number of posts per thread to generate. '
'Default is {}.'.format(settings.JSONBENCH_NUM_POSTS))
)
default_board_pk = self.get_next_board_pk()
parser.add_argument(
'-bpk', '--board-pk',
dest='board_pk',
metavar='BOARD_PK',
type=self.positive_int,
default=default_board_pk,
help=('A positive integer representing the starting board primary key. '
'Default is {}.'.format(default_board_pk))
)
default_thread_pk = self.get_next_thread_pk()
parser.add_argument(
'-tpk', '--thread-pk',
dest='thread_pk',
metavar='THREAD_PK',
type=self.positive_int,
default=default_thread_pk,
help=('A positive integer representing the starting thread primary key. '
'Default is {}.'.format(default_thread_pk))
)
default_post_pk = self.get_next_post_pk()
parser.add_argument(
'-ppk', '--post-pk',
dest='post_pk',
metavar='POST_PK',
type=self.positive_int,
default=default_post_pk,
help=('A positive integer representing the starting post primary key. '
'Default is {}.'.format(default_post_pk))
)
to_file_default = os.path.join(
settings.BASE_DIR, 'apps', 'm2mbench', 'fixtures', 'm2mbench.json'
)
parser.add_argument(
'-tf', '--to-file',
dest='fixtures_file',
metavar='FIXTURES_FILE',
type=argparse.FileType('w'),
default=to_file_default,
help=('A path to the file to write out m2mbench fixture data. '
'Default is "{}".'.format(to_file_default))
)
def handle(self, *args, **options):
num_boards = options.get('num_boards')
num_threads = options.get('num_threads')
num_posts = options.get('num_posts')
board_pk = options.get('board_pk')
thread_pk = options.get('thread_pk')
post_pk = options.get('post_pk')
fixtures_file = options.get('fixtures_file')
m2mbench_list = []
self.write_notice('==> num boards = {}'.format(num_boards))
self.write_notice('==> num threads = {}'.format(num_threads))
self.write_notice('==> num posts = {}'.format(num_posts))
self.write_notice('==> start board pk = {}'.format(board_pk))
self.write_notice('==> start thread pk = {}'.format(thread_pk))
self.write_notice('==> start post pk = {}'.format(post_pk))
self.write_notice('==> fixtures file = {}'.format(fixtures_file))
for i in range(1, num_boards+1):
m2mbench_list.append({
"model": "m2mbench.board",
"pk": board_pk,
"fields": {
"name": 'm2mbench Board {}'.format(board_pk)
}
})
self.write_notice('==> Board {}'.format(board_pk))
for j in range(1, num_threads+1):
m2mbench_list.append({
"model": "m2mbench.thread",
"pk": thread_pk,
"fields": {
"name": 'm2mbench Thread {} of Board {}'.format(thread_pk, board_pk),
"board": board_pk
}
})
if j % 10 == 0:
self.write_notice(' `--> Thread {} '.format(thread_pk), ending='', flush=True)
for k in range(1, num_posts+1):
m2mbench_list.append({
"model": "m2mbench.post",
"pk": post_pk,
"fields": {
"name": 'm2mbench Post {} of Thread {} of Board {}'.format(
post_pk, thread_pk, board_pk
),
"thread": thread_pk
}
})
if j % 10 == 0 and k % 100 == 0:
self.write_notice('.', ending='', flush=True)
post_pk += 1
if j % 10 == 0:
self.write('')
thread_pk += 1
board_pk += 1
self.write_to_json_file(fixtures_file, m2mbench_list, json_indent=4)
self.write_success('~~ finished! ~~')
| {
"content_hash": "d96b329e193a18dd940f1704fb1d3e50",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 101,
"avg_line_length": 40.082840236686394,
"alnum_prop": 0.487599645704163,
"repo_name": "jonmsawyer/jsonbench",
"id": "c2e5d6df5c58ba5d217cf63154e82be0fd71ff6f",
"size": "6774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apps/m2mbench/management/commands/m2mbench_generate.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17091"
},
{
"name": "HTML",
"bytes": "17354"
},
{
"name": "Python",
"bytes": "81012"
}
],
"symlink_target": ""
} |
@interface BuyViewController : UIViewController
@property (nonatomic, strong) NSString *labelID;
@end
| {
"content_hash": "d29a9562c24a55e2a14ab2e708de15ca",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 48,
"avg_line_length": 20.8,
"alnum_prop": 0.7980769230769231,
"repo_name": "lan409508/Act",
"id": "b993518a41b404ad6a21f710b8992d0fb4675809",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "China-Act/China-Act/classes/Buy/Controllers/BuyViewController.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "1028995"
},
{
"name": "Ruby",
"bytes": "69"
},
{
"name": "Shell",
"bytes": "7953"
}
],
"symlink_target": ""
} |
struct SimpleVertex
{
DirectX::XMFLOAT3 Point;
};
struct VsConstantBuffer
{
DirectX::XMFLOAT4X4 ViewProj;
DirectX::XMFLOAT4X4 ViewProjInv;
DirectX::XMFLOAT3 CamPos;
float padding;
};
class Cef3DDirect3D12Renderer : public Cef3DSampleRenderer
{
public:
Cef3DDirect3D12Renderer();
// Cef3DSampleRenderer interface methods
virtual bool Init(Cef3DSampleWindow* window) override;
virtual bool InitResources() override;
virtual void Render() override;
virtual void Present() override;
virtual void Shutdown() override;
virtual void UpdateOffscreenTexture(const void* buffer,
int width,
int height) override;
bool Resize(int width, int height) override;
void SetVsync(bool vsync) { Vsync = vsync; }
private:
ID3DBlob* CompileFsTriangleVertexShader(unsigned flags);
ID3DBlob* CompileFsTrianglePixelShader(unsigned flags);
bool CompileShader(ShaderType type, unsigned flags, const char* entryPoint, const std::string& source, ID3D10Blob** outBlob);
private:
IDXGISwapChain3* SwapChain;
ID3D12Device* Device;
ID3D12CommandQueue* CommandQueue;
ID3D12DescriptorHeap* RenderTargetViewHeap;
ID3D12DescriptorHeap* ConstantBufferHeap;
ID3D12DescriptorHeap* OffscreenSrvHeap;
ID3D12Resource* BackBufferRenderTarget[2];
ID3D12Resource* OffscreenTexture;
ID3D12CommandAllocator* CommandAllocator;
ID3D12GraphicsCommandList* CommandList;
ID3D12PipelineState* PipelineState;
ID3D12Fence* Fence;
HANDLE FenceEvent;
unsigned long long FenceValue;
unsigned int BufferIndex;
D3D12_VIEWPORT Viewport;
D3D12_RECT ScissorsRect;
ID3D12RootSignature* RootSig;
ID3D12Resource* VertexBuffer;
D3D12_VERTEX_BUFFER_VIEW VertexBufferView;
//D3D11_VIEWPORT Viewport;
ID3D12Resource* ConstantBuffer;
VsConstantBuffer ConstantBufferData;
bool Vsync;
Cef3DSampleWindow* Window;
}; | {
"content_hash": "167b442c48e2ac3622263eb9a0d69bbc",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 126,
"avg_line_length": 25.714285714285715,
"alnum_prop": 0.8088888888888889,
"repo_name": "arkenthera/cef3d",
"id": "0c56071493add8ca5f4779dd6acab730d0cccaa3",
"size": "2491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Demos/Common/Direct3D12Renderer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1028782"
},
{
"name": "C++",
"bytes": "2887899"
},
{
"name": "CMake",
"bytes": "118535"
},
{
"name": "HLSL",
"bytes": "821"
},
{
"name": "Python",
"bytes": "82527"
}
],
"symlink_target": ""
} |
{{ define "main" }}
<section class="page--outer-container-padding">
<div class="container">
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<p>Department: Treasury Board of Canada Secretariat</p>
<p>Sector: Canadian Digital Service</p>
<p>Position Title: Director of Talent & Internal Operations</p>
<p>Group and Level: EX-01</p>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>Education</h2>
<p>Graduation with a degree from a recognized post-secondary institution or an acceptable combination of education, training and/or experience.</p>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>Experience</h2>
<p>E1 - Significant* and recent** experience applying modern HR practices to improve talent acquisition and employee experience in a digital or transformational*** environment.</p>
<p>E2 - Experience driving strategy and change in a multilayer and complex**** organization.</p>
<p>E3 - Significant* experience in establishing and maintaining effective working relationships with senior officials (Assistant Deputy Minister level or equivalent and higher) in such organizations as: federal departments or agencies, other levels of government, the private sector, not-for-profit organizations/institutions.</p>
<p>E4 - Experience providing strategic analysis and advice to senior management*****.</p>
<p>E5 - Experience in managing human resources and in managing financial resources.</p>
<br>
<p>*Significant is defined as depth and breadth of experience that would normally be acquired over a period of approximately two years.</p>
<p>**Recent is defined as experience that would normally be acquired within the last five years.</p>
<p>*** Transformational is defined as an organization that is in constant movement and change.</p>
<p>****Complex is defined as having two (2) or more of the following characteristics: significant business risks and impacts, multidimensional, sensitive, affecting many partners or stakeholders, precedent setting or with significant public profile.</p>
<p>*****Senior management is defined as Executive Director and above or an executive with decision-making power that influences the whole of the organization.</p>
<br>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>Knowledge</h2>
<p>K1 - Knowledge of modern HR practices in talent acquisition and employee experience.</p>
<p>K2 - Knowledge of how to drive HR strategy in a complex organization.</p>
<p>K3 - Knowledge of diversity, equity, and inclusion strategies and practices.</p>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>Abilities</h2>
<p>A1 – Ability to communicate effectively orally and in writing.</p>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>Key Leadership Competencies</h2>
<p>KLC1 - Create vision and strategy</p>
<p>KLC2 - Mobilize people</p>
<p>KLC3 - Uphold integrity and respect</p>
<p>KLC4 - Collaborate with partners and stakeholders</p>
<p>KLC5 - Promote innovation and guide change</p>
<p>KLC6 - Achieve results</p>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>Official Languages Proficiency</h2>
<p>It is our intent to appoint a bilingual Imperative CBC/CBC (intermediate to advanced French levels) candidate however non-imperative CBC/CBC appointments may be considered.</p>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>EEDI Statement</h2>
<p>In support of achieving a diverse workforce, consideration may be given to candidates self-declare as belonging to one of the following Employment Equity groups: Aboriginal peoples, persons with disabilities, members of visible minorities, and women.</p>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-xs-12">
<h2>Condition of employment</h2>
<p>Secret security clearance</p>
</div>
</div>
</div>
</section>
{{ end }} | {
"content_hash": "e08b746ac7c2572f3570bc31eaa4343a",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 346,
"avg_line_length": 54.857142857142854,
"alnum_prop": 0.6003605769230769,
"repo_name": "cds-snc/digital-canada-ca",
"id": "b06b4ac0199024fb9e069f32a8496d6deda86b85",
"size": "4994",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "layouts/section/statement-of-merit-criteria-ex1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "394104"
},
{
"name": "Dockerfile",
"bytes": "1935"
},
{
"name": "HTML",
"bytes": "605048"
},
{
"name": "JavaScript",
"bytes": "5262751"
},
{
"name": "SCSS",
"bytes": "103113"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../dist/newlifeindavie.gallery.css" />
</head>
<body>
<div class="pure-g-r">
<div class="galleria-menu pure-u-1-4">
<div class="pure-form">
<fieldset>
<legend>Add a Flickr Set</legend>
<input class="add-url" type="text" placeholder="Set URL">
<button class="pure-button pure-button-primary add-set">Add</button>
</fieldset>
</div>
<ul>
<li class="fullscreen"><span class="icon fullscreen"></span><a href="#">Fullscreen</a></li>
<li><span class="icon camera"></span><a href="http://www.flickr.com/photos/101646885@N06/sets/72157635490225820/">Test Set</a></li>
<li><span class="icon camera"></span><a href="http://www.flickr.com/photos/robof07/sets/72157624125160094/">LIVE!</a></li>
</ul>
</div>
<div class="galleria-gallery pure-u-3-4">
</div>
</div>
<script src="../dist/newlifeindavie.gallery.js"></script>
</body>
</html> | {
"content_hash": "942e81a4cab5df174d804be55e8babc7",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 135,
"avg_line_length": 35.142857142857146,
"alnum_prop": 0.6290650406504065,
"repo_name": "kavun/newlifeindavie",
"id": "e99208b5a23c2d6463546a84de68af0e4bda74b4",
"size": "984",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/gallery.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "128151"
},
{
"name": "JavaScript",
"bytes": "2242606"
}
],
"symlink_target": ""
} |
package ch.carve.consul.discovery;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.enterprise.util.Nonbinding;
import javax.inject.Qualifier;
@Qualifier
@Retention(RUNTIME)
@Target({ TYPE, METHOD, FIELD })
public @interface DiscoverableService {
@Nonbinding
String serviceName();
}
| {
"content_hash": "57c7e0370a69d908a6d246f053ede06c",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 59,
"avg_line_length": 26.363636363636363,
"alnum_prop": 0.7758620689655172,
"repo_name": "rikcarve/consul-hystrix",
"id": "4da016f80cac152b6c5c7a7aa510709c4bd873db",
"size": "580",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/ch/carve/consul/discovery/DiscoverableService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "19627"
}
],
"symlink_target": ""
} |
(function(){
"use strict";
angular.module('app.config').config(function($logProvider){
$logProvider.debugEnabled(false);
});
})();
| {
"content_hash": "035d66a5352d41f4d52e6c7fd8e68978",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 63,
"avg_line_length": 19.125,
"alnum_prop": 0.6013071895424836,
"repo_name": "magnolo/23",
"id": "00d3101d4827ff2763199c2dabd90f5987872e79",
"size": "153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "angular/config/leaflet.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "448"
},
{
"name": "HTML",
"bytes": "437786"
},
{
"name": "JavaScript",
"bytes": "2753541"
},
{
"name": "PHP",
"bytes": "281446"
},
{
"name": "Shell",
"bytes": "179"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Sphaeromphale terebrata Mudd
### Remarks
null | {
"content_hash": "c82a0b46265c4724870afef65c9989aa",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 28,
"avg_line_length": 10.153846153846153,
"alnum_prop": 0.7196969696969697,
"repo_name": "mdoering/backbone",
"id": "cc538920e16bcf4e38026019b529f7ad7a1b0aa5",
"size": "191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Eurotiomycetes/Verrucariales/Verrucariaceae/Staurothele/Staurothele rupifraga/ Syn. Verrucaria terebrata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package foundation.softwaredesign.orbi.persistence.repo.game.character;
import foundation.softwaredesign.orbi.persistence.entity.CharacterMessageEntity;
import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.Repository;
/**
* @author Lucas Reeh <[email protected]>
*/
@Repository
public interface CharacterMessageStatisticsRepository extends EntityRepository<CharacterMessageEntity, Long> {
@Query(value = "" +
"select count(e)" +
" from CharacterMessageEntity e" +
" where e.toCharacterId = ?1")
Long countByToCharacterId(Long characterId);
}
| {
"content_hash": "f170d3c6bdc41653c3773d574d37cdd0",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 110,
"avg_line_length": 33.9,
"alnum_prop": 0.7522123893805309,
"repo_name": "sd-f/orbi",
"id": "82e2eab74ac4ddf52ff9c8e769ac56f34110c0cd",
"size": "678",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "Orbi-Server/src/main/java/foundation/softwaredesign/orbi/persistence/repo/game/character/CharacterMessageStatisticsRepository.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1353474"
},
{
"name": "GLSL",
"bytes": "21494"
},
{
"name": "Java",
"bytes": "160471"
},
{
"name": "Mask",
"bytes": "319"
}
],
"symlink_target": ""
} |
title: Contact
---
### _You can find me at_
- [StackOverflow](https://stackoverflow.com/users/3798102/pamu)
- [LinkedIn](https://www.linkedin.com/in/nagarjunapamu)
| {
"content_hash": "af91826e707b3ea9d30c40afee03ddfa",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 63,
"avg_line_length": 23.714285714285715,
"alnum_prop": 0.7108433734939759,
"repo_name": "pamu/blog",
"id": "95e3ae3faf82b68a8475df226fce3667acb1be87",
"size": "170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contact.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2120"
},
{
"name": "HTML",
"bytes": "4323"
},
{
"name": "Haskell",
"bytes": "4178"
},
{
"name": "Nix",
"bytes": "388"
}
],
"symlink_target": ""
} |
<footer>
© {{ site.time | date: '%Y' }} Created by <a href="{{ site.owner.homepage }}" target="_blank">{{ site.owner.name }}</a>.
Powered by <a href="http://jekyllrb.com/" target="_blank">Jekyll</a>
</footer>
| {
"content_hash": "8229e0241617c175a1294ee5419cdc81",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 127,
"avg_line_length": 54.5,
"alnum_prop": 0.6055045871559633,
"repo_name": "monday-factory/nette-tutors",
"id": "9cd7370bf908bd8a23c0f5f71fbfc2a8fae8ac9b",
"size": "218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/footer.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "42448"
},
{
"name": "HTML",
"bytes": "9778"
},
{
"name": "JavaScript",
"bytes": "620"
}
],
"symlink_target": ""
} |
BayesianTouchCriterion
======================

### Bayesian Touch Criterion
*BayesianTouchCriterion* is an Objective-C implementation of the *Bayesian Target Criterion (BTC)* developed by Xiaojun Bi and Shumin Zhai. Given a touch point and some touch targets, it improves the accuracy of selections by finding the touch target with the shortest *Bayesian Touch Distance (BTD)*. This element is the one that the user intended to select. The results of the evaluation of Bi and Zhai show that selection based on *BTC* is much more precise than using the visual boundary of an element. (Visual boundary checking is how most touch frameworks determine if the finger touches a target.)
The image above shows how randomly placed touch points (the smaller, semi-transparent circles) select their corresponding targets (the nine big circles). In the user interface of a mobile app, for example, *BTC* could be used to more accurately determine which menu item the user intended to select. The point of using *BTC* instead of visual boundary checking is: The intended element is *not* necessarily the element where the user's touch lies exactly within the visual boundary of the element (e.g., the touch point might be somewhere slightly outside of the visual boundary). *BTC* has the advantage that it does not require more detailed information about the touch point (finger posture, touch area...). The only required input parameters of the formula are touch location, target center, and target diameter.
If you are interested in the full mathematical details and derivations, here's the full reference:
> Xiaojun Bi and Shumin Zhai. Bayesian touch: A statistical criterion of target selection with finger touch. In Proceedings of the 26th Annual ACM Symposium on User Interface Software and Technology, UIST ’13, pages 51–60, New York, NY, USA, 2013. ACM.
The paper is [freely available on Research at Google](http://research.google.com/pubs/archive/41644.pdf).
### Installation
Just copy the folder `src/BayesianTouchCriterion` into your project.
The demo project shows a simple usage example. The code creates random touch points and determines the color of each touch point based on *BTC* (see image above). It also adds some interactivity: When you touch the screen, *BTC* finds the target layer of the circle menu and sets its background color to black.
### Usage
There are just two simple classes: `BTCCalculator` and `BTCFinder`.
`BTCFinder` is more high-level and implements basic management for targets. Targets are of type `CALayer` (if you want to use views, just use a view's layer via `view.layer`). You can add and remove targets and find the intended target for a touch point.
Internally, `BTCFinder` uses `BTCCalculator` to calculate *BTD*. You can use `BTCCalculator` directly if you wish to implement your own logic for target management.
It's important that you set the PPI (points per inch) value for the target device before using either `BTCFinder` or `BTCCalculator`. Since *BTC* is based on *millimeters*, the PPI value is needed to convert from millimeters to pixels per inch and vice versa. (The demo project contains simple PPI detection for current iPhones and iPads.)
### API
#### `BTCFinder`
You must set the PPI of the target device before using this class.
Use hard-coded values or device detection logic.
```objective-c
+ (CGFloat)pointsPerInch;
+ (void)setPointsPerInch:(CGFloat)newPointsPerInch;
```
Add a `CALayer` as potential touch target, remove a layer, or remove all layers.
```objective-c
- (void)addTarget:(CALayer *)target;
- (void)removeTarget:(CALayer *)target;
- (void)removeAllTargets;
```
Find the target based on a touch point. The touch point must be located in the coordinate system of `view`.
```objective-c
- (CALayer *)findTargetForTouchPoint:(CGPoint)touchPoint
inView:(UIView *)touchView;
```
#### `BTCCalculator`
You must set the PPI of the target device before using this class.
Use hard-coded values or device detection logic.
```objective-c
+ (CGFloat)pointsPerInch;
+ (void)setPointsPerInch:(CGFloat)newPointsPerInch;
```
Calculate *BTD* based on the touch point, the center point of the target and the diameter of the target. The target with the shortest *BTD* is the intended target. (You need to add this logic yourself if you use this class directly.)
```objective-c
+ (CGFloat)bayesianTouchDistanceWithTouchPoint:(CGPoint)touchPoint
targetCenter:(CGPoint)targetCenter
targetDiameter:(CGFloat)targetDiameter;
```
### Important Notes
- *BTC* works for circular target selection. The formula is based on target center and diameter. For objects with different shapes, you might need to check if you can use the diameter as an approximation and still achieve good results.
- *BTC* assumes that each point selects one object on screen (i.e., it does not consider empty space between objects). You might need to add your own logic to select the final target.
| {
"content_hash": "ba8cfe7fcb2ab94c84aafd0665505c86",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 816,
"avg_line_length": 65.35443037974683,
"alnum_prop": 0.7631222157660275,
"repo_name": "fe9lix/BayesianTouchCriterion",
"id": "5a3aa87d60aa216f966ccd300175159ba06fe044",
"size": "5167",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "16281"
}
],
"symlink_target": ""
} |
package org.jivesoftware.smackx.privacy.filter;
import org.jivesoftware.smack.filter.FlexiblePacketTypeFilter;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smackx.privacy.packet.Privacy;
public class SetDefaultListFilter extends FlexiblePacketTypeFilter<Privacy> {
public static final SetDefaultListFilter INSTANCE = new SetDefaultListFilter();
private SetDefaultListFilter() {
}
@Override
protected boolean acceptSpecific(Privacy privacy) {
if (privacy.getType() != Type.set) {
return false;
}
return privacy.getDefaultName() != null || privacy.isDeclineDefaultList();
}
}
| {
"content_hash": "9879c10d0cb1ad05ce7dc0deb57e4fa1",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 83,
"avg_line_length": 28.956521739130434,
"alnum_prop": 0.7357357357357357,
"repo_name": "magnetsystems/message-smack",
"id": "cac7369023a9edf364fe941b8296452e2ce5e9d9",
"size": "1268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/filter/SetDefaultListFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "602"
},
{
"name": "HTML",
"bytes": "58167"
},
{
"name": "Java",
"bytes": "4806012"
},
{
"name": "Shell",
"bytes": "739"
}
],
"symlink_target": ""
} |
body {
background-color: #DDDDFF;
padding: 2em;
}
.genomedrawer {
background-color: white;
border: 1px solid black;
width: 600px;
height: 150px;
} | {
"content_hash": "2de3bebe58a9edbf027c2cb871f681e6",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 29,
"avg_line_length": 15.454545454545455,
"alnum_prop": 0.6294117647058823,
"repo_name": "bernatgel/genomedrawer",
"id": "6c668857ad12b7aa4847b82324a115ca80dffb61",
"size": "170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/manual_testing/css/genomedrawer.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "170"
},
{
"name": "HTML",
"bytes": "1115"
},
{
"name": "JavaScript",
"bytes": "32302"
}
],
"symlink_target": ""
} |
@interface DetailViewController : UIViewController
@property (strong, nonatomic) Badge* detailItem;
@property (weak, nonatomic) IBOutlet UILabel* detailDescriptionLabel;
@property (weak, nonatomic) IBOutlet UIImageView* imageView;
@end
| {
"content_hash": "c0b7def1a5f616c82138d893a87ef783",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 69,
"avg_line_length": 34,
"alnum_prop": 0.8109243697478992,
"repo_name": "nimzi/badge_browser",
"id": "6561222fee5e799e6b45a8551b8e228c35bf564d",
"size": "435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "KhanAcademyBrowser/DetailViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "411689"
}
],
"symlink_target": ""
} |
// This script requires jQuery to operate
function SPPassport ( fnArgs ){
// Setup anything needed
// Option Arguments
// - toolbar 1 or 0
// Make call to passport server to get valid cookie
if(fnArgs.toolbar) {
var elementID = fnArgs.ToolbarID || 'sp_passportToolbar';
var toolbar = globalnav_html();
jQuery('body').prepend(toolbar);
}
jQuery.getJSON("https://passport.sportingpulse.com/PassportSession/?callback=?", function(data) {
if(data.name) {
jQuery('#SPPassportName').text(data.name);
jQuery('.spp_loggedout').hide();
jQuery('.spp_loggedin').show();
}
});
}
function globalnav_html() {
var html = ''
+ ' <style type="text/css"> '
+ ' #globalnav {background: url("https://reg.sportingpulse.com/images/global_nav_sprite.png") repeat-x scroll 0 -33px transparent; float: left; height: 32px; width: 100%;}'
+ ' #globalnav-inner {margin: 0 auto;width: 996px;}'
+ ' .gnav-logo {background: url("https://reg.sportingpulse.com/images/global_nav_sprite.png") no-repeat scroll 0 -3px transparent;cursor: pointer;display: block;float: left;height: 32px;margin: 0;position: relative;width: 159px;}'
+ ' .gnav-splogo {background: url("https://reg.sportingpulse.com/images/global_nav_sprite.png") repeat-x scroll 0 -162px transparent;display: inline;float: left;height: 26px;margin: 2px 10px;width: 104px;}'
+ ' .navoptions {float: right;}'
+ ' .sp-sign-in-out-wrap {float: right;font-size: 12px;line-height: 32px;}'
+ ' .sp-sign-in-out-wrap a {float: left;color: #FFF;height: 32px;padding: 0 10px;display: block;}'
+ ' .sp-sign-in-out-wrap a:hover {background-image: #116faa;background-image: -webkit-linear-gradient(top, #2277b0 50%, #0066a4 50%);background-image: -moz-linear-gradient(top, #2277b0 50%, #0066a4 50%);background-image: -o-linear-gradient(top, #2277b0 50%, #0066a4 50%);background-image: -ms-linear-gradient(top, #2277b0 50%, #0066a4 50%);background-image: linear-gradient(top, #2277b0 50%, #0066a4 50%);}'
+ ' #gnav-arrow-wrap {float: right;display: inline;width: 159px;height: 32px;}'
+ ' #gnav-arrow {background: url("https://reg.sportingpulse.com/images/global_nav_sprite.png") repeat scroll -23px -353px transparent;display: inline;float: left;height: 11px;margin: 11px 9px 0;width: 13px;}'
+ ' .arrowup #gnav-arrow {background-position: -13px -352px;width: 13px;}'
+ ' </style> '
+ ' <div id="pushdown-wrapper" style="display:none;"> </div> '
+ '<div id="globalnav">'
+ ' <div id="globalnav-inner">'
+ ' <div class="gnav-logo"><div id="gnav-arrow-wrap"><div class="gnav-splogo"></div><div id="gnav-arrow"></div></div></div>'
+ ' <div class="sp-sign-in-out-wrap">'
+ ' <div class="spp_loggedout">'
+ ' <a href="http://support.sportingpulse.com/">Support</a>'
+ ' <a href="https://passport.sportingpulse.com/login/">SP Passport</a>'
+ ' </div>'
+ ' <div class="spp_loggedin" style="display:none;">'
+ ' <div class="navoptions">'
+ ' <a href="https://passport.sportingpulse.com/account/?"><span id="SPPassportName"></span></a>'
+ ' <a href="http://support.sportingpulse.com/">Support</a>'
+ ' <a href="https://passport.sportingpulse.com/logout/?">Sign out</a>'
+ ' </div>'
+ ' </div>'
+ ' </div>'
+ ' </div>'
+ '</div>'
+ '';
return html;
}
jQuery(window).load(function(){
jQuery("#gnav-arrow-wrap").click(function () {
loadglobnavdata();
jQuery("#pushdown-wrapper").slideToggle("slow");
jQuery("#globalnav").toggleClass("arrowup");
});
function loadglobnavdata() {
jQuery.ajax({
dataType: "jsonp",
url: "https://reg.sportingpulse.com/v5/js/globalnav.js",
jsonpCallback : 'gncb',
success: function(data) {
jQuery('#pushdown-wrapper').html(data.data || '');
}
});
}
if ( (jQuery.browser.msie && jQuery.browser.version < 9.0) )
{
jQuery('body').addClass('old-ie');
}
});
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (thisfield.value == "") {
thisfield.value = defaulttext;
}
}
| {
"content_hash": "3a723b18d8f0ea0dce08d0175394b5b1",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 407,
"avg_line_length": 44.215053763440864,
"alnum_prop": 0.6532101167315175,
"repo_name": "facascante/slimerp",
"id": "72e8d825e0ce9b1ad03309fb6057f6c6c9d29e2a",
"size": "4196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fifs/web/js/SPPassport.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1104419"
},
{
"name": "CoffeeScript",
"bytes": "4704"
},
{
"name": "Go",
"bytes": "6808"
},
{
"name": "JavaScript",
"bytes": "6279846"
},
{
"name": "PHP",
"bytes": "8370737"
},
{
"name": "Perl",
"bytes": "5007867"
},
{
"name": "Python",
"bytes": "5596"
},
{
"name": "Shell",
"bytes": "2966"
}
],
"symlink_target": ""
} |
package core;
import static core.Constants.*;
import controller.BattleController;
import controller.RenderableBattleController;
import evogame.GameParameters;
import execution.BattleTest;
import utils.Vector2d;
import utils.Util;
import utils.JEasyFrame;
import utils.StatSummary;
import utils.ElapsedCpuTimer;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Vector;
import java.awt.*;
/**
* Created by simon lucas on 10/06/15.
* <p>
* Aim here is to have a simple battle class
* that enables ships to fish with each other
* <p>
* Might start off with just two ships, each with their own types of missile.
*/
public class SimpleBattle {
// play a time limited game with a strict missile budget for
// each player
public static int nTicks = 10;
boolean visible = true;
public static long DURATION_PER_TICK = 20;
public static int nbObstacles = 5;
public static int MISSILE_BUDGET = 10000;
public static double MISSILE_SPEED = MutableConstants.params.missileMinVelocity;
public static int COOLDOWN_TIME = 4;
public static int LIFE = 3;
public static double MIN_SHOOT_RANGE = 60;
public static double maxShootRange = 10000;
public static int[][] p1Statistics = new int[BattleTest.NUM_GAMES_TO_PLAY][5];
public static int[][] p2Statistics = new int[BattleTest.NUM_GAMES_TO_PLAY][5];;
public static int battles = 0;
public static int MISSILE_COST = 0;
public static int fitFunc = 1;
private static final double MAX_SCORE = 1000000;
private static final double MIN_SCORE = -1000000;
ArrayList<GameObject> objects;
public ArrayList<PlayerStats> stats;
//ArrayList<Wall> obstacles;
public NeuroShip s1, s2;
BattleController p1, p2;
BattleView view;
public int currentTick;
public int[][] ship1PositionMatrix = new int[5][5];
public int[][] ship2PositionMatrix = new int[5][5];
public String[] ship1Actions = new String[nTicks+1];
public String[] ship2Actions = new String[nTicks+1];
double score1, score2;
StatSummary ss1 = new StatSummary();
StatSummary ss2 = new StatSummary();
double scoreRecord[];
double score1Record[];
double score2Record[];
int winner = -1;
public SimpleBattle() {
this(true);
scoreRecord = new double[nTicks+1];
score1Record = new double[nTicks+1];
score2Record = new double[nTicks+1];
}
public SimpleBattle(boolean visible, int nTicks) {
this(visible);
this.nTicks = nTicks;
scoreRecord = new double[nTicks+1];
score1Record = new double[nTicks+1];
score2Record = new double[nTicks+1];
}
public SimpleBattle(boolean visible, int nTicks, GameParameters params) {
this(visible);
MutableConstants.setMutableConstants(params);
this.nTicks = nTicks;
ship1Actions = new String[nTicks+1];
ship2Actions = new String[nTicks+1];
scoreRecord = new double[nTicks+1];
score1Record = new double[nTicks+1];
score2Record = new double[nTicks+1];
}
public SimpleBattle(boolean visible) {
this.objects = new ArrayList<>();
this.stats = new ArrayList<>();
//this.obstacles = new ArrayList<>();
this.visible = visible;
this.score1 = 0.0;
this.score2 = 0.0;
if (visible) {
view = new BattleView(this);
new JEasyFrame(view, "battle");
view.repaint();
}
}
public int getTicks() {
return currentTick;
}
public double[] playGame(BattleController p1, BattleController p2) {
this.p1 = p1;
this.p2 = p2;
reset(true);
if (p1 instanceof KeyListener) {
view.addKeyListener((KeyListener)p1);
view.setFocusable(true);
view.requestFocus();
}
if (p2 instanceof KeyListener) {
view.addKeyListener((KeyListener)p2);
view.setFocusable(true);
view.requestFocus();
}
waitTillReady();
while (!isGameOver()) {
update();
//System.out.println("current time: " + currentTick);
//System.out.println("player 1: " + this.stats.get(0).life);
//System.out.println("player 2: " + this.stats.get(1).life);
}
//update();
if(this.winner == -1) {
if (stats.get(0).nPoints > stats.get(1).nPoints) {
this.winner = 0;
}
else if (stats.get(0).nPoints < stats.get(1).nPoints) {
this.winner = 1;
}
}
if(this.winner!=-1) {
if (this.winner == 0) {
p1Statistics[battles][0] = 1;
p1Statistics[battles][1] = currentTick;
p1Statistics[battles][2] = stats.get(this.winner).life;
p1Statistics[battles][3] = stats.get(this.winner).getMissilesFired();
p1Statistics[battles][4] = stats.get(this.winner).nPoints;
p2Statistics[battles][0] = 0;
p2Statistics[battles][1] = currentTick;
p2Statistics[battles][2] = stats.get(1-this.winner).life;
p2Statistics[battles][3] = stats.get(1-this.winner).getMissilesFired();
p2Statistics[battles][4] = stats.get(1-this.winner).nPoints;
}
else {
p2Statistics[battles][0] = 1;
p2Statistics[battles][1] = currentTick;
p2Statistics[battles][2] = stats.get(this.winner).life;
p2Statistics[battles][3] = stats.get(this.winner).getMissilesFired();
p2Statistics[battles][4] = stats.get(this.winner).nPoints;
p1Statistics[battles][0] = 0;
p1Statistics[battles][1] = currentTick;
p1Statistics[battles][2] = stats.get(1-this.winner).life;
p1Statistics[battles][3] = stats.get(1-this.winner).getMissilesFired();
p1Statistics[battles][4] = stats.get(1-this.winner).nPoints;
}
battles++;
System.out.println("GAME: " + battles + " Player " + (this.winner+1) + " wins at " + currentTick + " with life " + stats.get(this.winner).life + " fired " + stats.get(this.winner).getMissilesFired() + " points " + stats.get(this.winner).nPoints);
System.out.println("GAME: " + battles + " Player " + (2-this.winner) + " loss at " + currentTick + " with life " + stats.get(1-this.winner).life + " fired " + stats.get(1-this.winner).getMissilesFired() + " points " + stats.get(1-this.winner).nPoints);
} else {
battles++;
System.out.println("GAME: " + battles + " Player 1 draws at " + currentTick + " with life " + stats.get(0).life + " with life " + stats.get(0).life + " fired " + stats.get(0).getMissilesFired() + " points " + stats.get(0).nPoints);
System.out.println("GAME: " + battles + " Player 2 draws at " + currentTick + " with life " + stats.get(1).life + " with life " + stats.get(1).life + " fired " + stats.get(1).getMissilesFired() + " points " + stats.get(1).nPoints);
}
if (p1 instanceof KeyListener) {
view.removeKeyListener((KeyListener)p1);
}
if (p2 instanceof KeyListener) {
view.removeKeyListener((KeyListener)p2);
}
double[] tmp = Util.combineArray(scoreRecord,score1Record);
double[] allRecord = Util.combineArray(tmp,score2Record);
return allRecord;
}
protected void waitTillReady()
{
if(visible)
{
while(!view.ready) {
view.repaint();
waitStep(1000);
}
}
waitStep(1000);
}
/**
* Waits until the next step.
* @param duration Amount of time to wait for.
*/
protected static void waitStep(int duration) {
try
{
Thread.sleep(duration);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
/**
* Randomly reset the game if randomInit==true
*/
public void reset(boolean randomInit) {
stats.clear();
objects.clear();
if(randomInit) {
Vector<Integer> pos = randomPositionBy4Area();
if(pos.get(0)>=pos.get(2)) {
s1 = buildShip(pos.get(0), pos.get(1), 1, 0, 0);
s2 = buildShip(pos.get(2), pos.get(3), -1, 0, 1);
} else {
s1 = buildShip(pos.get(0), pos.get(1), -1, 0, 0);
s2 = buildShip(pos.get(2), pos.get(3), 1, 0, 1);
}
//for(int i=0; i<nbObstacles; i++) {
// addRandomObstacle();
//}
} else {
s1 = buildShip(200, 250, 1, 0, 0);
s2 = buildShip(300, 250, -1, 0, 1);
}
this.currentTick = 0;
this.winner = -1;
stats.add(new PlayerStats(MISSILE_BUDGET, 0, LIFE, 0, MISSILE_BUDGET));
stats.add(new PlayerStats(MISSILE_BUDGET, 0, LIFE, 0, MISSILE_BUDGET));
objects.add(s1);
objects.add(s2);
}
/**
public void addRandomObstacle() {
obstacles.add(new Wall(Util.randomIntInRange(0,500),Util.randomIntInRange(0,500),Util.randomIntInRange(2,50),Util.randomIntInRange(2,50)));
}
*/
public Vector<Integer> randomPositionBy4Area() {
Vector<Integer> pos = new Vector<Integer>();
Random randomGenerator = new Random();
int area1 = randomGenerator.nextInt(4)+1;
int area2 = randomGenerator.nextInt(4)+1;
while(area2==area1) {
area2 = randomGenerator.nextInt(4)+1;
}
pos.add(Util.randomIntInRange(0,100)+((int)(area1%2)*250)+100);
pos.add(Util.randomIntInRange(0,100)+((int)(area1/2)*250)+100);
pos.add(Util.randomIntInRange(0,100)+((int)(area2%2)*250)+100);
pos.add(Util.randomIntInRange(0,100)+((int)(area2/2)*250)+100);
return pos;
}
protected NeuroShip buildShip(int x, int y, int dx, int dy, int playerId) {
Vector2d position = new Vector2d(x, y, true);
Vector2d speed = new Vector2d(true);
Vector2d direction = new Vector2d(dx, dy, true);
return new NeuroShip(position, speed, direction, playerId );
}
public void update() {
//checkMissiles();
// get the actions from each player
checkMissiles();
// apply them to each player's ship, taking actions as necessary
ElapsedCpuTimer elapsedTimer = new ElapsedCpuTimer();
elapsedTimer.setMaxTimeMillis(this.DURATION_PER_TICK);
Action a1 = p1.getAction(this.clone(), 0, elapsedTimer);
Action a2 = p2.getAction(this.clone(), 1, elapsedTimer);
//System.out.println("Player 0 at time " + currentTick + " life="+this.stats.get(0).life+ " cooldown=" +this.stats.get(0).cooldown+" missiles="+this.stats.get(0).nMissiles);
//System.out.println("Player 1 at time " + currentTick + " life="+this.stats.get(1).life+ " cooldown=" +this.stats.get(1).cooldown+" missiles="+this.stats.get(1).nMissiles);
ship1Actions[currentTick] = String.valueOf((int) a1.thrust) + "," + String.valueOf((int) a1.turn) + "," + String.valueOf(a1.shoot);
ship2Actions[currentTick] = String.valueOf((int) a2.thrust) + "," + String.valueOf((int) a2.turn) + "," + String.valueOf(a2.shoot);
//System.out.println((int) s1.s.y / (Constants.height / 5) + " / " + (int) s1.s.x / (Constants.width / 5));
int positionX;
int positionY;
int positionX2;
int positionY2;
if (s1.s.y > Constants.height) {
positionX = 0;
} else {
positionX = (int) s1.s.y / (Constants.height / 5);
}
if (s1.s.x > Constants.width) {
positionY = 0;
} else {
positionY = (int) s1.s.x / (Constants.width / 5);
}
if (s2.s.y > Constants.height) {
positionX2 = 0;
} else {
positionX2 = (int) s2.s.y / (Constants.height / 5);
}
if (s2.s.x > Constants.width) {
positionY2 = 0;
} else {
positionY2 = (int) s2.s.x / (Constants.width / 5);
}
if (ship1PositionMatrix[positionX][positionY] <= 0) {
ship1PositionMatrix[positionX][positionY] = 1;
} else {
ship1PositionMatrix[positionX][positionY] += 1;
}
if (ship2PositionMatrix[positionX2][positionY2] <= 0) {
ship2PositionMatrix[positionX2][positionY2] = 1;
} else {
ship2PositionMatrix[positionX2][positionY2] += 1;
}
advance(a1, a2);
// update missiles
for (GameObject ob : objects)
if(ob instanceof BattleMissile)
ob.update();
checkCollision(s1);
checkCollision(s2);
checkMissiles();
ss1.add(score(0));
ss2.add(score(1));
}
public void advance(Action a1, Action a2) {
// and fire any missiles as necessary
if (a1.shoot) {
//fireMissile(s1.s, s1.d, 0);
fireMissiles(s1.s, s1.d, 0, MutableConstants.params.missileAngle);
} else {
stats.get(0).cooldown--;
}
if (a2.shoot) {
//fireMissile(s2.s, s2.d, 1);
fireMissiles(s2.s, s2.d, 1, MutableConstants.params.missileAngle);
} else {
stats.get(1).cooldown--;
}
// now apply them to the ships
s1.update(a1);
s2.update(a2);
wrap(s1);
wrap(s2);
/**
for (GameObject object : objects) {
wrap(object);
}
**/
// here need to add the game objects ...
/**
java.util.List<GameObject> killList = new ArrayList<GameObject>();
for (GameObject object : objects) {
object.update();
wrap(object);
if (object.dead()) {
killList.add(object);
}
}
objects.removeAll(killList);
**/
currentTick++;
NeuroShip ss1 = s1;
NeuroShip ss2 = s2;
//if(playerId == 0)
// System.out.println("player 1 currentTick: " +currentTick+"; d: " + dist + "; dp: " + distPoints + "; dot: " + dot + "; TOTAL: " + (dot*distPoints));
//if(playerId == 1)
// System.out.println("player 2 currentTick: " +currentTick+"; d: " + dist + "; dp: " + distPoints + "; dot: " + dot + "; TOTAL: " + (dot*distPoints));
/**
* Check if the two ships are too closed to each other
*/
double dist = ss1.distTo(ss2) - MIN_SHOOT_RANGE;
if(dist<0)
{
Vector2d dir = Vector2d.subtract(ss2.s, ss1.s);
dir.normalise();
s2.addRepulsiveForce(0.5f * MIN_SHOOT_RANGE, MIN_SHOOT_RANGE, dir);
dir.multiply(-1);
s1.addRepulsiveForce(0.5f * MIN_SHOOT_RANGE, MIN_SHOOT_RANGE, dir);
this.stats.get(s1.getId()).life--;
this.stats.get(s2.getId()).life--;
}
updateScores();
if (visible) {
view.repaint();
sleep();
}
if(scoreRecord != null)
scoreRecord[currentTick] = score(0);
if(score1Record != null)
score1Record[currentTick] = score1;
if(score2Record != null)
score2Record[currentTick] = score2;
//System.out.println(currentTick + " " + score(0));
//int a = 0;
}
public void updateScores()
{
score1 = calcScore(0);
score2 = calcScore(1);
}
/**
* TODO: here to modify the heuristic
* This method calculates the score for specific player
* @param playerId
* @return
*/
private double calcScore(int playerId)
{
NeuroShip ss1 = s1;
NeuroShip ss2 = s2;
if(playerId == 1)
{
ss1 = s2;
ss2 = s1;
}
double dist = Math.abs(ss1.distTo(ss2));//-minShootRange);
double dot = ss1.dotTo(ss2);
double dotDirs = ss1.dotDirections(ss2);
double distPoints = 1.0/(1.0+dist/100.0);
/**
* Check if the opponent in the shooting range
*/
double dotAngle= Math.sqrt(1)/2.0;
double firePoints = stats.get(playerId).nPoints/(10);
if(fitFunc==1)
return (dot*distPoints + firePoints);
else
return firePoints;
}
public double score(int playerId)
{
if(stats.get(playerId).life>0 && stats.get(1-playerId).life<=0)
return MAX_SCORE;
if(stats.get(playerId).life<=0 && stats.get(1-playerId).life>0)
return MIN_SCORE;
//if(stats.get(playerId).life==0 && stats.get(1-playerId).life==0)
// return 0;
//double remainedBudget = stats.get(playerId).nMissiles/this.missilesBudget;
//double firePoints = 2*(stats.get(playerId).nPoints/27;
if(fitFunc==1) {
if(playerId == 0)
return score1 - score2;
else
return score2 - score1;
} else {
if(playerId == 0)
return score1;
else
return score2;
}
}
public SimpleBattle clone() {
SimpleBattle state = new SimpleBattle(false);
state.objects = copyObjects();
state.stats = copyStats();
state.currentTick = currentTick;
state.visible = false; //stop MCTS people having all the games :p
state.s1 = s1.copy();
state.s2 = s2.copy();
return state;
}
protected ArrayList<GameObject> copyObjects() {
ArrayList<GameObject> objectClone = new ArrayList<GameObject>();
for (GameObject object : objects) {
objectClone.add(object.copy());
}
return objectClone;
}
protected ArrayList<PlayerStats> copyStats() {
ArrayList<PlayerStats> statsClone = new ArrayList<PlayerStats>();
for (PlayerStats object : stats) {
statsClone.add(new PlayerStats(object.nMissiles, object.cooldown, object.life, object.nPoints, MISSILE_BUDGET));
}
return statsClone;
}
protected void checkCollision(GameObject actor) {
// check with all other game objects
// but use a hack to only consider interesting interactions
// e.g. asteroids do not collide with themselves
if (!actor.dead() &&
(actor instanceof BattleMissile
|| actor instanceof NeuroShip)) {
if (actor instanceof BattleMissile) {
System.out.println("Missile: " + actor);
}
/**
for(Wall wall:obstacles) {
Rectangle2D thisWall = wall.getBound();
boolean crash = thisWall.intersects(actor.getBound());
if(crash) {
actor.hit();
int playerId = (actor == s1 ? 0 : 1);
PlayerStats stats = this.stats.get(playerId);
stats.cooldown++;
return;
}
}
**/
// the actor is a ship
int playerId = (actor == s1 ? 0 : 1);
for (GameObject ob : objects) {
if(ob.getId() != playerId) {
if(ob instanceof NeuroShip) {
//System.out.println("ship " + ob.getId() + " playerId " + playerId);
if (overlap(actor, ob)) {
//actor.hit();
//ob.hit();
System.out.println("Players hit");
this.stats.get(playerId).life=0;
this.stats.get(1-playerId).life=0;
//System.out.println(this.stats.get(1-playerId).life);
return;
}
} else if (ob instanceof BattleMissile) {
//System.out.println("missile " + ob.getId() + " playerId " + playerId);
if (overlap(actor, ob)) {
ob.hit();
this.stats.get(playerId).life--;
Vector2d dir = new Vector2d(ob.v, true);
dir.normalise();
if(playerId==1) {
s2.addForceRotate(NeuroShip.MIN_FORCE, NeuroShip.MAX_FORCE, dir);
this.stats.get(0).nPoints += 10;
} else {
s1.addForceRotate(NeuroShip.MIN_FORCE, NeuroShip.MAX_FORCE, dir);
this.stats.get(1).nPoints += 10;
}
}
}
}
}
removeDead();
}
}
protected void checkMissiles() {
for(int i=objects.size()-1; i>1; i--) {
GameObject ob1 = objects.get(i);
for(int j=i-1; j>1; j--) {
GameObject ob2 = objects.get(j);
if(ob1.getId() != ob2.getId()) {
if(overlap(ob1,ob2)) {
ob1.hit();
ob2.hit();
}
}
}
}
removeDead();
}
protected void removeDead() {
for(int i=objects.size()-1; i>1; i--) {
GameObject ob = objects.get(i);
if(ob.dead())
objects.remove(i);
}
}
private boolean overlap(GameObject actor, GameObject ob) {
// otherwise do the default check
double dist = actor.s.dist(ob.s);
boolean ret = dist < (actor.r() + ob.r());
return ret;
}
public void sleep() {
try {
Thread.sleep(delay);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void fireMissile(Vector2d s, Vector2d d, int playerId) {
// need all the usual missile firing code here
NeuroShip currentShip = playerId == 0 ? s1 : s2;
PlayerStats thisStats = this.stats.get(playerId);
NeuroShip ss1 = s1;
NeuroShip ss2 = s2;
if(playerId == 1)
{
ss1 = s2;
ss2 = s1;
}
double dist = ss1.distTo(ss2);
//if (dist >= minShootRange && dist<=maxShootRange && thisStats.nMissiles > 0 && thisStats.cooldown <=0) {
if (/*dist >= minShootRange && dist<=maxShootRange &&*/ thisStats.nMissiles > 0 && thisStats.cooldown <=0) {
BattleMissile m = new BattleMissile(s, new Vector2d(0, 0, true), playerId);
// the velocity is noisy
//double noiseStrength = 0.05;
double noiseStrength = 0.0;
double releaseVelocity = MISSILE_SPEED * (1+Math.random()*noiseStrength);
//double releaseVelocity =0;
//m.v.add(d, releaseVelocity);
m.v = Vector2d.multiply(d,releaseVelocity);
// make it clear the ship
m.s.add(m.v, (currentShip.r() + missileRadius) * 1.5 / m.v.mag());
// add missile to the object list
objects.add(m);
//System.out.println("Fired: " + m);
//sounds.fire();
//this.stats.get(playerId).nMissiles--;
thisStats.nMissiles--;
thisStats.nPoints -= this.MISSILE_COST;
thisStats.cooldown = this.COOLDOWN_TIME;
//currentShip.addInverseForce(1, 5);
} else {
thisStats.cooldown--;
}
}
protected void fireMissiles(Vector2d s, Vector2d d, int playerId, double theta) {
// need all the usual missile firing code here
NeuroShip currentShip = playerId == 0 ? s1 : s2;
PlayerStats thisStats = this.stats.get(playerId);
NeuroShip ss1 = s1;
NeuroShip ss2 = s2;
if(playerId == 1)
{
ss1 = s2;
ss2 = s1;
}
double dist = ss1.distTo(ss2);
//if (dist >= minShootRange && dist<=maxShootRange && thisStats.nMissiles > 0 && thisStats.cooldown <=0) {
if (/*dist >= minShootRange && dist<=maxShootRange &&*/ thisStats.nMissiles > 0 && thisStats.cooldown <=0) {
BattleMissile m = new BattleMissile(s, new Vector2d(0, 0, true), playerId);
// the velocity is noisy
//double noiseStrength = 0.05;
double noiseStrength = 0.0;
double releaseVelocity = MISSILE_SPEED * (1+Math.random()*noiseStrength);
//double releaseVelocity =0;
//m.v.add(d, releaseVelocity);
m.v = Vector2d.multiply(d,releaseVelocity);
// make it clear the ship
m.s.add(m.v, (currentShip.r() + missileRadius) * 1.5 / m.v.mag());
// add missile to the object list
objects.add(m);
//Create the 3 missiles
BattleMissile m2 = m.copy();
m2.v.rotate(theta);
objects.add(m2);
BattleMissile m3 = m.copy();
m3.v.rotate(-theta);
objects.add(m3);
//System.out.println("Fired: " + m);
//sounds.fire();
//this.stats.get(playerId).nMissiles--;
thisStats.nMissiles--;
thisStats.nPoints -= this.MISSILE_COST;
thisStats.cooldown = this.COOLDOWN_TIME;
//currentShip.addInverseForce(1, 5);
} else {
thisStats.cooldown--;
}
}
public void draw(Graphics2D g) {
// for (Object ob : objects)
if (s1 == null || s2 == null) {
return;
}
// System.out.println("In draw(): " + n);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(bg);
g.fillRect(0, 0, size.width, size.height);
if(!objects.isEmpty()) {
GameObject[] objectsCopy = objects.toArray(new GameObject[objects.size()]);
for (GameObject go : objectsCopy) {
go.draw(g);
}
}
s1.draw(g);
if (p1 instanceof RenderableBattleController) {
RenderableBattleController rbc = (RenderableBattleController)p1;
rbc.render(g, s1.copy());
}
s2.draw(g);
if (p2 instanceof RenderableBattleController) {
RenderableBattleController rbc = (RenderableBattleController)p2;
rbc.render(g, s2.copy());
}
p1.draw(g);
p2.draw(g);
if(BattleTest.SHOW_ROLLOUTS)
{
//waitStep(5000);
}
}
public NeuroShip getShip(int playerId) {
assert playerId < 2;
assert playerId >= 0;
if (playerId == 0) {
return s1.copy();
} else {
return s2.copy();
}
}
public ArrayList<GameObject> getObjects()
{
return new ArrayList<>(objects);
}
public int getCooldown(int playerId) {
assert playerId < 2;
assert playerId >= 0;
return stats.get(playerId).cooldown;
}
public int getMissilesLeft(int playerId) {
//return 0;
assert playerId < 2;
assert playerId >= 0;
return stats.get(playerId).nMissiles;
}
private void wrap(GameObject ob) {
// only wrap objects which are wrappable
if (ob.wrappable()) {
//System.out.println( "before wrap" + ob.s);
ob.s.x = (ob.s.x + width) % width;
ob.s.y = (ob.s.y + height) % height;
//System.out.println( "after wrap" + ob.s);
}
}
public boolean isGameOver() {
if(stats.get(1).life<=0 && stats.get(0).life<=0)
{
return true;
}
if(score1==MAX_SCORE || stats.get(1).life<=0)
{
this.winner = 0;
//System.out.println("green win at " + currentTick+" " +score1 + " " +score2);
return true;
}
if(score2==MAX_SCORE || stats.get(0).life<=0)
{
//System.out.println("blue win at " + currentTick+" " +score1 + " " +score2);
this.winner = 1;
return true;
}
/*if (getMissilesLeft(0) >= 0 && getMissilesLeft(1) >= 0) {
//ensure that there are no bullets left in play
if (objects.isEmpty()) {
return true;
}
}*/
/**
PlayerStats stat = this.stats.get(0);
assert(stat.cooldown<=this.life);
if(stat.cooldown==this.life) {
this.winner = 1;
return true;
}
stat = this.stats.get(1);
assert(stat.cooldown<=this.life);
if(stat.cooldown==this.life) {
this.winner = 0;
return true;
}
**/
return currentTick >= nTicks;
}
public int getGameWinner() {
boolean end = isGameOver();
assert((!end) && (this.winner !=-1));
return this.winner;
}
public double getScore(int playerId)
{
if(playerId == 0)
return score1;
return score2;
}
public static class PlayerStats {
int nMissiles;
int cooldown;
public int life;
int nPoints;
int totalMissiles;
public PlayerStats(int _nMissiles, int _cooldown, int _life, int _nPoints, int _totMissiles) {
this.nMissiles = _nMissiles;
this.cooldown = _cooldown;
this.life = _life;
this.nPoints = _nPoints;
this.totalMissiles = _totMissiles;
}
public int getMissilesFired() {
return (this.totalMissiles-this.nMissiles);
}
public String toString() {
return "M:" + nMissiles + "; C: " + cooldown + "; L: " + life + "; P: " + nPoints + " : ";
}
}
} | {
"content_hash": "caf2466af1c85a1a5bfc149ad3daf5c4",
"timestamp": "",
"source": "github",
"line_count": 894,
"max_line_length": 265,
"avg_line_length": 33.727069351230426,
"alnum_prop": 0.5338286017511277,
"repo_name": "bernardotc/CE810-2",
"id": "d424c8bf079d4937ecf24ac6fb99cb56c64e3854",
"size": "30152",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/core/SimpleBattle.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "97"
},
{
"name": "Java",
"bytes": "281633"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pt">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Mon Jun 22 15:50:37 BRT 2015 -->
<title>Uses of Class org.sdnplatform.sync.internal.AbstractStoreClient</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.sdnplatform.sync.internal.AbstractStoreClient";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/sdnplatform/sync/internal/AbstractStoreClient.html" title="class in org.sdnplatform.sync.internal">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/sdnplatform/sync/internal/class-use/AbstractStoreClient.html" target="_top">Frames</a></li>
<li><a href="AbstractStoreClient.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.sdnplatform.sync.internal.AbstractStoreClient" class="title">Uses of Class<br>org.sdnplatform.sync.internal.AbstractStoreClient</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/sdnplatform/sync/internal/AbstractStoreClient.html" title="class in org.sdnplatform.sync.internal">AbstractStoreClient</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.sdnplatform.sync.internal">org.sdnplatform.sync.internal</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.sdnplatform.sync.internal">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/sdnplatform/sync/internal/AbstractStoreClient.html" title="class in org.sdnplatform.sync.internal">AbstractStoreClient</a> in <a href="../../../../../org/sdnplatform/sync/internal/package-summary.html">org.sdnplatform.sync.internal</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../org/sdnplatform/sync/internal/AbstractStoreClient.html" title="class in org.sdnplatform.sync.internal">AbstractStoreClient</a> in <a href="../../../../../org/sdnplatform/sync/internal/package-summary.html">org.sdnplatform.sync.internal</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/sdnplatform/sync/internal/DefaultStoreClient.html" title="class in org.sdnplatform.sync.internal">DefaultStoreClient</a><K,V></strong></code>
<div class="block">Default implementation of a store client used for accessing a store
locally in process.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/sdnplatform/sync/internal/AbstractStoreClient.html" title="class in org.sdnplatform.sync.internal">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/sdnplatform/sync/internal/class-use/AbstractStoreClient.html" target="_top">Frames</a></li>
<li><a href="AbstractStoreClient.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "6a12035abadb2cea1b42096d1136e271",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 343,
"avg_line_length": 40.24683544303797,
"alnum_prop": 0.6480578707343922,
"repo_name": "paulorvj/sdnvoip",
"id": "6d3cbef19c81b0ed61ce88d34658ea3a8569e12b",
"size": "6359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/org/sdnplatform/sync/internal/class-use/AbstractStoreClient.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "181"
},
{
"name": "HTML",
"bytes": "10186"
},
{
"name": "Java",
"bytes": "3772566"
},
{
"name": "JavaScript",
"bytes": "55112"
},
{
"name": "Makefile",
"bytes": "426"
},
{
"name": "Python",
"bytes": "32743"
},
{
"name": "Shell",
"bytes": "5610"
},
{
"name": "Thrift",
"bytes": "7114"
}
],
"symlink_target": ""
} |
class PartnerHelp < ActiveRecord::Migration
def self.up
end
def self.down
end
end | {
"content_hash": "be613a02d6853cf616897b4d74ca1ede",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 43,
"avg_line_length": 12.857142857142858,
"alnum_prop": 0.7333333333333333,
"repo_name": "man2d/idvi_ru",
"id": "d02444963cb2ba4c2a826bfaa2c8820fedff82f4",
"size": "90",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/extensions/partner/db/migrate/20100603010219_partner_help.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "1294623"
},
{
"name": "PHP",
"bytes": "1052"
},
{
"name": "Ruby",
"bytes": "60733"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System;
using BDLib.BDLibInfo;
namespace BDLib.Resorces
{
public struct Resorce
{
object Item;
Type ItemType;
}
public static class ResorceManager
{
private static Dictionary<string, Resorce> Resorces;
/// <summary>
/// the total amount of resources i have
/// </summary>
public static int TotalResorce { get { return Resorces.Count; } }
/// <summary>
/// an empty resource
/// </summary>
public static Resorce EmptyResorceEntity;
/// <summary>
/// initulizes for use
/// </summary>
public static void INIT()
{
if (!Info.Moduls.Contains("Resorces/ResorceManager.cs"))
Info.Moduls.Add("Resorces/ResorceManager.cs");
Resorces = new Dictionary<string, Resorce>();
}
/// <summary>
/// returns a resource based on name
/// </summary>
/// <param name="ResorceName">the resource name</param>
/// <returns>resource</returns>
public static Resorce GetResorce(string ResorceName)
{
if (Resorces.ContainsKey(ResorceName))
{
return Resorces[ResorceName];
}
else return EmptyResorceEntity;
}
/// <summary>
/// adds a resource
/// </summary>
/// <param name="ResorceName">the name of the resource</param>
/// <param name="Res">the resource</param>
public static void AddResorce(string ResorceName, Resorce Res)
{
if (Resorces.ContainsKey(ResorceName))
throw new InvalidOperationException("Item Exists");
else
{
Resorces.Add(ResorceName, Res);
}
}
/// <summary>
/// removes a resource based on name
/// </summary>
/// <param name="ResorceName">name of resource</param>
public static void RemoveResorce(string ResorceName)
{
if (!Resorces.ContainsKey(ResorceName))
throw new IndexOutOfRangeException("Item doesn't existed");
Resorces.Remove(ResorceName);
}
}
}
| {
"content_hash": "a2ef3d34c938b43d9d873d35627cb4e4",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 75,
"avg_line_length": 30.75,
"alnum_prop": 0.5323063756953359,
"repo_name": "dedady157/blackwidow",
"id": "2b6965cf4658ff0c8c9c5e52f736cae0ab599745",
"size": "2339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BDLib/BDLib/Resorces/ResorceManager.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "265374"
}
],
"symlink_target": ""
} |
System.register(["tslib", "../aurelia"], function (exports_1, context_1) {
"use strict";
var tslib_1, au, MdWaitCursorCustomAttribute;
var __moduleName = context_1 && context_1.id;
return {
setters: [
function (tslib_1_1) {
tslib_1 = tslib_1_1;
},
function (au_1) {
au = au_1;
}
],
execute: function () {
MdWaitCursorCustomAttribute = /** @class */ (function () {
function MdWaitCursorCustomAttribute(element, templatingEngine) {
this.element = element;
this.templatingEngine = templatingEngine;
}
MdWaitCursorCustomAttribute.prototype.valueChanged = function (newVal) {
if (newVal && this.trResizeDelegate) {
this.trResizeDelegate();
}
};
MdWaitCursorCustomAttribute.prototype.attached = function () {
switch (this.element.tagName) {
case "MD-INPUT":
this.attachedMdInput();
break;
case "BUTTON":
this.attachedButton();
break;
case "LI":
this.attachedLi();
break;
case "TR":
this.attachedTr();
break;
}
};
MdWaitCursorCustomAttribute.prototype.attachedMdInput = function () {
var inputField = this.element.querySelector(".input-field");
if (!inputField) {
return;
}
this.progress = document.createElement("div");
this.progress.innerHTML = "<md-progress type='circular' size='small' show.bind='value' style='position: absolute; left: 100%; transform: translateX(-100%);'></md-progress>";
this.progress = this.progress.firstElementChild;
inputField.insertAdjacentElement("afterbegin", this.progress);
var view = this.templatingEngine.enhance(this.progress);
view.bind(this);
view.attached();
};
MdWaitCursorCustomAttribute.prototype.attachedButton = function () {
this.progress = document.createElement("div");
this.progress.innerHTML =
"<div show.bind='value' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0.7; background: white; z-index: 98;'></div>" +
"<md-progress type='circular' size='small' show.bind='value' style='position: absolute; left: 50%; top: 50%; height: 36px; transform: translateX(-50%) translateY(-50%); z-index: 99;'></md-progress>";
this.progress.style.position = "relative";
this.progress.style.display = "inline-block";
this.progress.classList.add("button-wait-cursor-wrapper");
this.element.insertAdjacentElement("beforebegin", this.progress);
var view = this.templatingEngine.enhance(this.progress);
view.bind(this);
view.attached();
this.progress.appendChild(this.element);
};
MdWaitCursorCustomAttribute.prototype.attachedLi = function () {
this.progress = document.createElement("div");
this.progress.innerHTML =
"<div show.bind='value' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0.7; background: white; z-index: 98; overflow: hidden;'>" +
"<md-progress type='circular' size='small' show.bind='value' style='position: absolute; left: 50%; top: 50%; height: 36px; transform: translateX(-50%) translateY(-50%); z-index: 99;'></md-progress>" +
"</div>";
this.progress = this.progress.firstElementChild;
var view = this.templatingEngine.enhance(this.progress);
view.bind(this);
view.attached();
this.element.appendChild(this.progress);
};
MdWaitCursorCustomAttribute.prototype.attachedTr = function () {
var _this = this;
var tr = this.element;
var firstTd = this.element.firstElementChild;
this.progress = document.createElement("div");
this.progress.innerHTML =
"<div show.bind='value'>" +
"<div style='opacity: 0.7; background: white; width: 100%; height: 100%;'></div>" +
"<md-progress type='circular' size='small' style='position: absolute; left: 50%; top: 50%; height: 36px; transform: translateX(-50%) translateY(-50%);'></md-progress>" +
"</div>";
this.progress = this.progress.firstChild;
this.trResizeDelegate = function () {
if (!_this.value) {
return;
}
_this.progress.style.position = "absolute";
_this.progress.style.top = tr.offsetTop + "px";
_this.progress.style.left = tr.offsetLeft + tr.parentElement.scrollLeft + "px";
_this.progress.style.width = tr.offsetWidth + "px";
_this.progress.style.height = tr.offsetHeight + "px";
};
var view = this.templatingEngine.enhance(this.progress);
view.bind(this);
view.attached();
this.trResizeDelegate();
window.addEventListener("resize", this.trResizeDelegate);
this.progress.onclick = function (ev) { ev.cancelBubble = true; };
firstTd.appendChild(this.progress);
};
MdWaitCursorCustomAttribute.prototype.detached = function () {
if (this.progress) {
if (this.element.tagName === "BUTTON") {
this.progress.insertAdjacentElement("beforebegin", this.element);
this.progress.remove();
}
else {
this.progress.remove();
}
}
if (this.trResizeDelegate) {
window.removeEventListener("resize", this.trResizeDelegate);
this.trResizeDelegate = null;
}
};
MdWaitCursorCustomAttribute = tslib_1.__decorate([
au.customAttribute("md-wait-cursor"),
au.autoinject,
tslib_1.__metadata("design:paramtypes", [Element, au.TemplatingEngine])
], MdWaitCursorCustomAttribute);
return MdWaitCursorCustomAttribute;
}());
exports_1("MdWaitCursorCustomAttribute", MdWaitCursorCustomAttribute);
}
};
});
//# sourceMappingURL=wait-cursor.js.map | {
"content_hash": "c80dfd64007a73a51c744d13ed8cb18d",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 228,
"avg_line_length": 57.08888888888889,
"alnum_prop": 0.4758012196704295,
"repo_name": "aurelia-ui-toolkits/aurelia-materialize-bridge",
"id": "d88c26aba2f7caadcc73c7b0b50eb6604400d25b",
"size": "7707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/system/wait-cursor/wait-cursor.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2296"
},
{
"name": "HTML",
"bytes": "155279"
},
{
"name": "JavaScript",
"bytes": "17720"
},
{
"name": "TypeScript",
"bytes": "124941"
}
],
"symlink_target": ""
} |
package org.leikind.verbs.dutch;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TextView;
import java.util.Locale;
import static org.leikind.verbs.dutch.Constants.*;
public class DetailedInfoActivity extends Activity {
ImageButton button;
Verb verb;
TextView infinitive;
TextView pastSingular;
TextView pastPlural;
TextView pastParticiple;
TextView translation;
boolean showTranslation;
final private int copyInfinitiveContextMenuItem = 0;
final private int copyPastSingularContextMenuItem = 1;
final private int copyPastPluralContextMenuItem = 2;
final private int copyPastParticipleContextMenuItem = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_info);
initVerb();
initUI();
}
private void initVerb() {
Bundle b = getIntent().getExtras();
long id = b.getLong(KEY_FOR_DETAILED_INFO_ACTIVITY_INTENT);
String locale = Locale.getDefault().getLanguage();
showTranslation = locale.equals(EN) || locale.equals(DE) || locale.equals(FR);
if (!showTranslation) locale = null;
VerbsList verbsList = new VerbsList(this);
verb = verbsList.findVerbForId(id, locale);
verbsList.close();
}
private void initUI() {
TableLayout table = (TableLayout) findViewById(R.id.detailed);
infinitive = (TextView) findViewById(R.id.infinitive);
pastSingular = (TextView) findViewById(R.id.past_singular);
pastPlural = (TextView) findViewById(R.id.past_plural);
pastParticiple = (TextView) findViewById(R.id.past_participle);
translation = (TextView) findViewById(R.id.translation);
if (showTranslation) {
translation.setText("(" + verb.getTranslation() + ")");
}
setTitle(verb.getInfinitive().substring(0, 1).toUpperCase() + verb.getInfinitive().substring(1));
infinitive.setText(verb.getInfinitive());
pastSingular.setText(verb.getPastSingular());
pastPlural.setText(verb.getPastPlural());
String auxiliaryAndParticiple = verb.getAuxiliaryAndParticiple();
pastParticiple.setText(auxiliaryAndParticiple);
registerForContextMenu(table);
button = (ImageButton) findViewById(R.id.close_info);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
finish();
}
});
}
// Context Menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
String copy = getResources().getString(R.string.Copy);
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(ContextMenu.NONE,
copyInfinitiveContextMenuItem, copyInfinitiveContextMenuItem, copy + " \"" + verb.getInfinitive() + "\"");
menu.add(ContextMenu.NONE,
copyPastSingularContextMenuItem, copyPastSingularContextMenuItem, copy + " \"" + verb.getPastSingular() + "\"");
menu.add(ContextMenu.NONE,
copyPastPluralContextMenuItem, copyPastPluralContextMenuItem, copy + " \"" + verb.getPastPlural() + "\"");
menu.add(ContextMenu.NONE,
copyPastParticipleContextMenuItem, copyPastParticipleContextMenuItem, copy + " \"" + verb.getParticiple() + "\"");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
String toCopy = null;
switch (item.getItemId()) {
case copyInfinitiveContextMenuItem:
toCopy = verb.getInfinitive();
break;
case copyPastSingularContextMenuItem:
toCopy = verb.getPastSingular();
break;
case copyPastPluralContextMenuItem:
toCopy = verb.getPastPlural();
break;
case copyPastParticipleContextMenuItem:
toCopy = verb.getParticiple();
break;
default:
// Log.wtf(TAG, "Unrecognized context menu!!!");
// Log.e(TAG, "Unrecognized context menu!!!");
}
if (toCopy != null) {
Tools.copyToClipboard(this, toCopy);
return true;
} else {
return super.onContextItemSelected(item);
}
}
// Options Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.detailed_info_activity_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.wiktionary_lookup:
Tools.wiktionaryLookup(this, verb);
return true;
case R.id.copy_to_clipboard:
Tools.copyToClipboard(this, verb.toString());
return true;
case R.id.about:
Tools.displayAbout(this);
return true;
}
return false;
}
}
| {
"content_hash": "46e8a1abf2774be1ad070a8ac8bf6370",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 122,
"avg_line_length": 28.265895953757227,
"alnum_prop": 0.6918200408997955,
"repo_name": "leikind/onregelmatige_werkwoorden",
"id": "79497fb0d9d7cdcc4b38cc0ad98f561379dd9d6c",
"size": "4890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "org.leikind.verbs.dutch/src/org/leikind/verbs/dutch/DetailedInfoActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "25035"
},
{
"name": "Ruby",
"bytes": "6086"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "deddf23d641f7384591c1e85e97a32aa",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "a402e5b27e9b80918eead3b0db8ac23fdf5b983f",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Cucurbitales/Cucurbitaceae/Coccinia/Coccinia moghadd/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace media {
// The number of shared memory buffer segments indicated to browser process
// in order to avoid data overwriting. This number can be any positive number,
// dependent how fast the renderer process can pick up captured data from
// shared memory.
// TODO(henrika): figure out a suitable size of this ring buffer.
// We have seen reports in Chrome where segments of repeated input audio has
// damaged AEC performance in WebRTC clients. By setting its value to 1, we
// reduce the number of places in Chrome where such a patteren could possibly
// be created. The original value of kRequestedSharedMemoryCount was 10.
// See b/13976602 for details.
static const int kRequestedSharedMemoryCount = 1;
// Takes care of invoking the capture callback on the audio thread.
// An instance of this class is created for each capture stream in
// OnLowLatencyCreated().
class AudioInputDevice::AudioThreadCallback
: public AudioDeviceThread::Callback {
public:
AudioThreadCallback(const AudioParameters& audio_parameters,
base::SharedMemoryHandle memory,
int memory_length,
int total_segments,
CaptureCallback* capture_callback);
~AudioThreadCallback() override;
void MapSharedMemory() override;
// Called whenever we receive notifications about pending data.
void Process(uint32 pending_data) override;
private:
int current_segment_id_;
ScopedVector<media::AudioBus> audio_buses_;
CaptureCallback* capture_callback_;
DISALLOW_COPY_AND_ASSIGN(AudioThreadCallback);
};
AudioInputDevice::AudioInputDevice(
scoped_ptr<AudioInputIPC> ipc,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
: ScopedTaskRunnerObserver(io_task_runner),
callback_(NULL),
ipc_(ipc.Pass()),
state_(IDLE),
session_id_(0),
agc_is_enabled_(false),
stopping_hack_(false) {
CHECK(ipc_);
// The correctness of the code depends on the relative values assigned in the
// State enum.
static_assert(IPC_CLOSED < IDLE, "invalid enum value assignment 0");
static_assert(IDLE < CREATING_STREAM, "invalid enum value assignment 1");
static_assert(CREATING_STREAM < RECORDING, "invalid enum value assignment 2");
}
void AudioInputDevice::Initialize(const AudioParameters& params,
CaptureCallback* callback,
int session_id) {
DCHECK(params.IsValid());
DCHECK(!callback_);
DCHECK_EQ(0, session_id_);
audio_parameters_ = params;
callback_ = callback;
session_id_ = session_id;
}
void AudioInputDevice::Start() {
DCHECK(callback_) << "Initialize hasn't been called";
DVLOG(1) << "Start()";
task_runner()->PostTask(FROM_HERE,
base::Bind(&AudioInputDevice::StartUpOnIOThread, this));
}
void AudioInputDevice::Stop() {
DVLOG(1) << "Stop()";
{
base::AutoLock auto_lock(audio_thread_lock_);
audio_thread_.Stop(base::MessageLoop::current());
stopping_hack_ = true;
}
task_runner()->PostTask(FROM_HERE,
base::Bind(&AudioInputDevice::ShutDownOnIOThread, this));
}
void AudioInputDevice::SetVolume(double volume) {
if (volume < 0 || volume > 1.0) {
DLOG(ERROR) << "Invalid volume value specified";
return;
}
task_runner()->PostTask(FROM_HERE,
base::Bind(&AudioInputDevice::SetVolumeOnIOThread, this, volume));
}
void AudioInputDevice::SetAutomaticGainControl(bool enabled) {
DVLOG(1) << "SetAutomaticGainControl(enabled=" << enabled << ")";
task_runner()->PostTask(FROM_HERE,
base::Bind(&AudioInputDevice::SetAutomaticGainControlOnIOThread,
this, enabled));
}
void AudioInputDevice::OnStreamCreated(
base::SharedMemoryHandle handle,
base::SyncSocket::Handle socket_handle,
int length,
int total_segments) {
DCHECK(task_runner()->BelongsToCurrentThread());
DCHECK(base::SharedMemory::IsHandleValid(handle));
#if defined(OS_WIN)
DCHECK(socket_handle);
#else
DCHECK_GE(socket_handle, 0);
#endif
DCHECK_GT(length, 0);
if (state_ != CREATING_STREAM)
return;
base::AutoLock auto_lock(audio_thread_lock_);
// TODO(miu): See TODO in OnStreamCreated method for AudioOutputDevice.
// Interface changes need to be made; likely, after AudioInputDevice is merged
// into AudioOutputDevice (http://crbug.com/179597).
if (stopping_hack_)
return;
DCHECK(audio_thread_.IsStopped());
audio_callback_.reset(new AudioInputDevice::AudioThreadCallback(
audio_parameters_, handle, length, total_segments, callback_));
audio_thread_.Start(
audio_callback_.get(), socket_handle, "AudioInputDevice", false);
state_ = RECORDING;
ipc_->RecordStream();
}
void AudioInputDevice::OnVolume(double volume) {
NOTIMPLEMENTED();
}
void AudioInputDevice::OnStateChanged(
AudioInputIPCDelegateState state) {
DCHECK(task_runner()->BelongsToCurrentThread());
// Do nothing if the stream has been closed.
if (state_ < CREATING_STREAM)
return;
// TODO(miu): Clean-up inconsistent and incomplete handling here.
// http://crbug.com/180640
switch (state) {
case AUDIO_INPUT_IPC_DELEGATE_STATE_STOPPED:
ShutDownOnIOThread();
break;
case AUDIO_INPUT_IPC_DELEGATE_STATE_RECORDING:
NOTIMPLEMENTED();
break;
case AUDIO_INPUT_IPC_DELEGATE_STATE_ERROR:
DLOG(WARNING) << "AudioInputDevice::OnStateChanged(ERROR)";
// Don't dereference the callback object if the audio thread
// is stopped or stopping. That could mean that the callback
// object has been deleted.
// TODO(tommi): Add an explicit contract for clearing the callback
// object. Possibly require calling Initialize again or provide
// a callback object via Start() and clear it in Stop().
if (!audio_thread_.IsStopped())
callback_->OnCaptureError();
break;
default:
NOTREACHED();
break;
}
}
void AudioInputDevice::OnIPCClosed() {
DCHECK(task_runner()->BelongsToCurrentThread());
state_ = IPC_CLOSED;
ipc_.reset();
}
AudioInputDevice::~AudioInputDevice() {
// TODO(henrika): The current design requires that the user calls
// Stop before deleting this class.
DCHECK(audio_thread_.IsStopped());
}
void AudioInputDevice::StartUpOnIOThread() {
DCHECK(task_runner()->BelongsToCurrentThread());
// Make sure we don't call Start() more than once.
if (state_ != IDLE)
return;
if (session_id_ <= 0) {
DLOG(WARNING) << "Invalid session id for the input stream " << session_id_;
return;
}
state_ = CREATING_STREAM;
ipc_->CreateStream(this, session_id_, audio_parameters_,
agc_is_enabled_, kRequestedSharedMemoryCount);
}
void AudioInputDevice::ShutDownOnIOThread() {
DCHECK(task_runner()->BelongsToCurrentThread());
// Close the stream, if we haven't already.
if (state_ >= CREATING_STREAM) {
ipc_->CloseStream();
state_ = IDLE;
agc_is_enabled_ = false;
}
// We can run into an issue where ShutDownOnIOThread is called right after
// OnStreamCreated is called in cases where Start/Stop are called before we
// get the OnStreamCreated callback. To handle that corner case, we call
// Stop(). In most cases, the thread will already be stopped.
//
// Another situation is when the IO thread goes away before Stop() is called
// in which case, we cannot use the message loop to close the thread handle
// and can't not rely on the main thread existing either.
base::AutoLock auto_lock_(audio_thread_lock_);
base::ThreadRestrictions::ScopedAllowIO allow_io;
audio_thread_.Stop(NULL);
audio_callback_.reset();
stopping_hack_ = false;
}
void AudioInputDevice::SetVolumeOnIOThread(double volume) {
DCHECK(task_runner()->BelongsToCurrentThread());
if (state_ >= CREATING_STREAM)
ipc_->SetVolume(volume);
}
void AudioInputDevice::SetAutomaticGainControlOnIOThread(bool enabled) {
DCHECK(task_runner()->BelongsToCurrentThread());
if (state_ >= CREATING_STREAM) {
DLOG(WARNING) << "The AGC state can not be modified after starting.";
return;
}
// We simply store the new AGC setting here. This value will be used when
// a new stream is initialized and by GetAutomaticGainControl().
agc_is_enabled_ = enabled;
}
void AudioInputDevice::WillDestroyCurrentMessageLoop() {
LOG(ERROR) << "IO loop going away before the input device has been stopped";
ShutDownOnIOThread();
}
// AudioInputDevice::AudioThreadCallback
AudioInputDevice::AudioThreadCallback::AudioThreadCallback(
const AudioParameters& audio_parameters,
base::SharedMemoryHandle memory,
int memory_length,
int total_segments,
CaptureCallback* capture_callback)
: AudioDeviceThread::Callback(audio_parameters, memory, memory_length,
total_segments),
current_segment_id_(0),
capture_callback_(capture_callback) {
}
AudioInputDevice::AudioThreadCallback::~AudioThreadCallback() {
}
void AudioInputDevice::AudioThreadCallback::MapSharedMemory() {
shared_memory_.Map(memory_length_);
// Create vector of audio buses by wrapping existing blocks of memory.
uint8* ptr = static_cast<uint8*>(shared_memory_.memory());
for (int i = 0; i < total_segments_; ++i) {
media::AudioInputBuffer* buffer =
reinterpret_cast<media::AudioInputBuffer*>(ptr);
scoped_ptr<media::AudioBus> audio_bus =
media::AudioBus::WrapMemory(audio_parameters_, buffer->audio);
audio_buses_.push_back(audio_bus.Pass());
ptr += segment_length_;
}
}
void AudioInputDevice::AudioThreadCallback::Process(uint32 pending_data) {
// The shared memory represents parameters, size of the data buffer and the
// actual data buffer containing audio data. Map the memory into this
// structure and parse out parameters and the data area.
uint8* ptr = static_cast<uint8*>(shared_memory_.memory());
ptr += current_segment_id_ * segment_length_;
AudioInputBuffer* buffer = reinterpret_cast<AudioInputBuffer*>(ptr);
// Usually this will be equal but in the case of low sample rate (e.g. 8kHz,
// the buffer may be bigger (on mac at least)).
DCHECK_GE(buffer->params.size,
segment_length_ - sizeof(AudioInputBufferParameters));
double volume = buffer->params.volume;
bool key_pressed = buffer->params.key_pressed;
// Use pre-allocated audio bus wrapping existing block of shared memory.
media::AudioBus* audio_bus = audio_buses_[current_segment_id_];
// Deliver captured data to the client in floating point format
// and update the audio-delay measurement.
int audio_delay_milliseconds = pending_data / bytes_per_ms_;
capture_callback_->Capture(
audio_bus, audio_delay_milliseconds, volume, key_pressed);
if (++current_segment_id_ >= total_segments_)
current_segment_id_ = 0;
}
} // namespace media
| {
"content_hash": "2e8db13caab3ad0dd6558e7d0ee61668",
"timestamp": "",
"source": "github",
"line_count": 316,
"max_line_length": 80,
"avg_line_length": 34.34177215189873,
"alnum_prop": 0.7007003317360855,
"repo_name": "lihui7115/ChromiumGStreamerBackend",
"id": "07eb11c2b77b16c2ba02efda82c5c7491b87693c",
"size": "11284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "media/audio/audio_input_device.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "37073"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9508834"
},
{
"name": "C++",
"bytes": "242598549"
},
{
"name": "CSS",
"bytes": "943747"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "27281878"
},
{
"name": "Java",
"bytes": "14561064"
},
{
"name": "JavaScript",
"bytes": "20540839"
},
{
"name": "Makefile",
"bytes": "70864"
},
{
"name": "Objective-C",
"bytes": "1745880"
},
{
"name": "Objective-C++",
"bytes": "10008668"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "178732"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "482954"
},
{
"name": "Python",
"bytes": "8626890"
},
{
"name": "Shell",
"bytes": "481888"
},
{
"name": "Standard ML",
"bytes": "5106"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
from django.conf import settings
AUTODISCOVER = getattr(settings, 'RESTOSAUR_AUTODISCOVER', True)
AUTODISCOVER_MODULE = getattr(
settings, 'RESTOSAUR_AUTODISCOVER_MODULE', 'restapi')
| {
"content_hash": "cd0af8270b59dc1cf423810fcefd0005",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 64,
"avg_line_length": 38.4,
"alnum_prop": 0.765625,
"repo_name": "marcinn/restosaur",
"id": "5a0fab1672b229d142dd271eb4e000a9475c8824",
"size": "192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "restosaur/settings.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "73635"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_40) on Wed Apr 13 18:09:43 UTC 2016 -->
<title>Uses of Class org.apache.cassandra.thrift.Cassandra.AsyncProcessor (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.thrift.Cassandra.AsyncProcessor (apache-cassandra API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.AsyncProcessor.html" title="class in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.AsyncProcessor.html" target="_top">Frames</a></li>
<li><a href="Cassandra.AsyncProcessor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.thrift.Cassandra.AsyncProcessor" class="title">Uses of Class<br>org.apache.cassandra.thrift.Cassandra.AsyncProcessor</h2>
</div>
<div class="classUseContainer">No usage of org.apache.cassandra.thrift.Cassandra.AsyncProcessor</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.AsyncProcessor.html" title="class in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.AsyncProcessor.html" target="_top">Frames</a></li>
<li><a href="Cassandra.AsyncProcessor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "e4fa50edb18b93c1412b0edda4d175e5",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 167,
"avg_line_length": 37.576,
"alnum_prop": 0.6227379178198851,
"repo_name": "elisska/cloudera-cassandra",
"id": "5493c37fd217eb2c34763c3770e06cc16a3d45dc",
"size": "4697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DATASTAX_CASSANDRA-3.5.0/javadoc/org/apache/cassandra/thrift/class-use/Cassandra.AsyncProcessor.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "75145"
},
{
"name": "CSS",
"bytes": "4112"
},
{
"name": "HTML",
"bytes": "331372"
},
{
"name": "PowerShell",
"bytes": "77673"
},
{
"name": "Python",
"bytes": "979128"
},
{
"name": "Shell",
"bytes": "143685"
},
{
"name": "Thrift",
"bytes": "80564"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Dashboard Admin We Tour Organizer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="shortcut icon" href="assets/images/ico/logoWe.jpg">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/images/ico/logoWe.jpg">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/images/ico/logoWe.jpg">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/images/ico/logoWe.jpg">
<link rel="apple-touch-icon-precomposed" href="assets/images/ico/logoWe.jpg">
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="<?php echo site_url('admin/c_admin/dashboardawl')?>">Dashboard Admin</a>
</div>
<br>
<br>
<ul class="nav navbar-nav">
<li class="active"><a href="<?php echo site_url('admin/c_admin/dashboardawl')?>">Dashboard</a></li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Paket<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="<?php echo site_url('admin/c_admin/tabelpaket')?>">List Paket</a></li>
<li><a href="<?php echo site_url('admin/c_admin/tmbhpaket')?>">Tambah Paket</a></li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Artikel<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="<?php echo site_url('admin/c_admin/tabelartikel')?>">List Artikel</a></li>
<li><a href="<?php echo site_url('admin/c_admin/tmbhartikel')?>">Tambah Artikel</a></li>
</ul>
</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Gallery<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="<?php echo site_url('admin/c_admin/tabelfoto')?>">List Foto</a></li>
<li><a href="<?php echo site_url('admin/c_admin/tmbhfoto')?>">Tambah Foto</a></li>
</ul>
</li>
<li><a href="<?php echo site_url('admin/c_admin/tabelpesan')?>">Pesan</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown"><a class="dropdown-toggle glyphicon glyphicon-user" data-toggle="dropdown" href="#"> Admin We Tour<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="<?php echo site_url('admin/login/logout')?>">Logout</a></li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="container" id="dashboard">
<h3>Selamat Datang di Dashboard Admin</h3>
<h4>We Tour Organizer</h4>
<p>Anda adalah admin. Anda diberikan layanan tambahan untuk mengatur dan mengupdate website We Tour Organizer.</p>
</div>
</body>
</html> | {
"content_hash": "af79b0a2f2da881858ae303dadf7cb46",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 156,
"avg_line_length": 50.12307692307692,
"alnum_prop": 0.6135666052793125,
"repo_name": "alilahnur/websitewetourorganizer",
"id": "6d592e4631cf23664ed879768632691df94c56a0",
"size": "3258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/cobaadmin.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "102073"
},
{
"name": "HTML",
"bytes": "8408413"
},
{
"name": "JavaScript",
"bytes": "24551"
},
{
"name": "PHP",
"bytes": "1826768"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<doc>
<assembly>
<name>
export_bumiputera
</name>
</assembly>
<members>
<member name="P:export_bumiputera.My.Resources.Resources.ResourceManager">
<summary>
Returns the cached ResourceManager instance used by this class.
</summary>
</member><member name="P:export_bumiputera.My.Resources.Resources.Culture">
<summary>
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
</summary>
</member><member name="T:export_bumiputera.My.Resources.Resources">
<summary>
A strongly-typed resource class, for looking up localized strings, etc.
</summary>
</member>
</members>
</doc> | {
"content_hash": "e206c5ee56e8856ae1f502e522eb5d66",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 75,
"avg_line_length": 28.125,
"alnum_prop": 0.76,
"repo_name": "waykanza/fasilitas",
"id": "e7ae7f925eab9cc4142eb3b28299d439927db9a4",
"size": "677",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vb/project/export_bumiputera/bin/Release/export_bumiputera.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "431"
},
{
"name": "CSS",
"bytes": "82885"
},
{
"name": "HTML",
"bytes": "643985"
},
{
"name": "JavaScript",
"bytes": "99306"
},
{
"name": "PHP",
"bytes": "5550953"
},
{
"name": "PLSQL",
"bytes": "3215"
},
{
"name": "SQLPL",
"bytes": "7389"
},
{
"name": "Visual Basic",
"bytes": "126378"
},
{
"name": "XSLT",
"bytes": "28086"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.fms.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum FirewallDeploymentModel {
CENTRALIZED("CENTRALIZED"),
DISTRIBUTED("DISTRIBUTED");
private String value;
private FirewallDeploymentModel(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return FirewallDeploymentModel corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static FirewallDeploymentModel fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (FirewallDeploymentModel enumEntry : FirewallDeploymentModel.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| {
"content_hash": "dea77981de69a729081de447d95d95d2",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 91,
"avg_line_length": 25.775510204081634,
"alnum_prop": 0.6254948535233571,
"repo_name": "aws/aws-sdk-java",
"id": "a5347bbe19bba73b3b9bf35938ec1b1be4907627",
"size": "1843",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-fms/src/main/java/com/amazonaws/services/fms/model/FirewallDeploymentModel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\EntityType;
class EntityTypeTest extends TestCase
{
/**
* Test relations of an entity type (id=4)
*
* @return void
*/
public function testRelations()
{
$type = EntityType::with(['layer', 'entities', 'attributes', 'sub_entity_types', 'thesaurus_concept'])->find(4);
$this->assertEquals(5, $type->layer->id);
$this->assertEquals(1, $type->entities->count());
$this->assertEquals(2, $type->entities[0]->id);
$this->assertEquals(5, $type->attributes->count());
$this->assertEquals(14, $type->attributes[0]->id);
$this->assertEquals(1, $type->attributes[0]->pivot->position);
$this->assertEquals(16, $type->attributes[1]->id);
$this->assertEquals(2, $type->attributes[1]->pivot->position);
$this->assertEquals(17, $type->attributes[2]->id);
$this->assertEquals(3, $type->attributes[2]->pivot->position);
$this->assertEquals(10, $type->attributes[3]->id);
$this->assertEquals(4, $type->attributes[3]->pivot->position);
$this->assertEquals(13, $type->attributes[4]->id);
$this->assertEquals(5, $type->attributes[4]->pivot->position);
$this->assertEquals(0, $type->sub_entity_types->count());
$this->assertEquals(2, $type->thesaurus_concept->id);
}
}
| {
"content_hash": "fb5ddbb3dd197731cbc95f3a8cd4b476",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 120,
"avg_line_length": 37.743589743589745,
"alnum_prop": 0.6270380434782609,
"repo_name": "eScienceCenter/Spacialist",
"id": "5cab958fea1036ca103585bab044004676153ccd",
"size": "1472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Unit/EntityTypeTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "15152"
},
{
"name": "PHP",
"bytes": "920627"
},
{
"name": "TeX",
"bytes": "1653"
},
{
"name": "Vue",
"bytes": "902923"
}
],
"symlink_target": ""
} |
using namespace llvm;
namespace {
// Tests on ARM, PowerPC and SystemZ disabled as we're running the old jit
#if !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__)
Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
std::vector<Type*> params;
FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
params, false);
Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
IRBuilder<> builder(Entry);
Value *Load = builder.CreateLoad(G);
Type *GTy = G->getType()->getElementType();
Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
builder.CreateStore(Add, G);
builder.CreateRet(Add);
return F;
}
std::string DumpFunction(const Function *F) {
std::string Result;
raw_string_ostream(Result) << "" << *F;
return Result;
}
class RecordingJITMemoryManager : public JITMemoryManager {
const OwningPtr<JITMemoryManager> Base;
public:
RecordingJITMemoryManager()
: Base(JITMemoryManager::CreateDefaultMemManager()) {
stubsAllocated = 0;
}
virtual void *getPointerToNamedFunction(const std::string &Name,
bool AbortOnFailure = true) {
return Base->getPointerToNamedFunction(Name, AbortOnFailure);
}
virtual void setMemoryWritable() { Base->setMemoryWritable(); }
virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
virtual void AllocateGOT() { Base->AllocateGOT(); }
virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
struct StartFunctionBodyCall {
StartFunctionBodyCall(uint8_t *Result, const Function *F,
uintptr_t ActualSize, uintptr_t ActualSizeResult)
: Result(Result), F(F), F_dump(DumpFunction(F)),
ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
uint8_t *Result;
const Function *F;
std::string F_dump;
uintptr_t ActualSize;
uintptr_t ActualSizeResult;
};
std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
virtual uint8_t *startFunctionBody(const Function *F,
uintptr_t &ActualSize) {
uintptr_t InitialActualSize = ActualSize;
uint8_t *Result = Base->startFunctionBody(F, ActualSize);
startFunctionBodyCalls.push_back(
StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
return Result;
}
int stubsAllocated;
virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
unsigned Alignment) {
stubsAllocated++;
return Base->allocateStub(F, StubSize, Alignment);
}
struct EndFunctionBodyCall {
EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
uint8_t *FunctionEnd)
: F(F), F_dump(DumpFunction(F)),
FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
const Function *F;
std::string F_dump;
uint8_t *FunctionStart;
uint8_t *FunctionEnd;
};
std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
uint8_t *FunctionEnd) {
endFunctionBodyCalls.push_back(
EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
Base->endFunctionBody(F, FunctionStart, FunctionEnd);
}
virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, bool IsReadOnly) {
return Base->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
}
virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID) {
return Base->allocateCodeSection(Size, Alignment, SectionID);
}
virtual bool applyPermissions(std::string *ErrMsg) { return false; }
virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
return Base->allocateSpace(Size, Alignment);
}
virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
return Base->allocateGlobal(Size, Alignment);
}
struct DeallocateFunctionBodyCall {
DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
const void *Body;
};
std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
virtual void deallocateFunctionBody(void *Body) {
deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
Base->deallocateFunctionBody(Body);
}
struct DeallocateExceptionTableCall {
DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
const void *ET;
};
std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
virtual void deallocateExceptionTable(void *ET) {
deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
Base->deallocateExceptionTable(ET);
}
struct StartExceptionTableCall {
StartExceptionTableCall(uint8_t *Result, const Function *F,
uintptr_t ActualSize, uintptr_t ActualSizeResult)
: Result(Result), F(F), F_dump(DumpFunction(F)),
ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
uint8_t *Result;
const Function *F;
std::string F_dump;
uintptr_t ActualSize;
uintptr_t ActualSizeResult;
};
std::vector<StartExceptionTableCall> startExceptionTableCalls;
virtual uint8_t *startExceptionTable(const Function *F,
uintptr_t &ActualSize) {
uintptr_t InitialActualSize = ActualSize;
uint8_t *Result = Base->startExceptionTable(F, ActualSize);
startExceptionTableCalls.push_back(
StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
return Result;
}
struct EndExceptionTableCall {
EndExceptionTableCall(const Function *F, uint8_t *TableStart,
uint8_t *TableEnd, uint8_t* FrameRegister)
: F(F), F_dump(DumpFunction(F)),
TableStart(TableStart), TableEnd(TableEnd),
FrameRegister(FrameRegister) {}
const Function *F;
std::string F_dump;
uint8_t *TableStart;
uint8_t *TableEnd;
uint8_t *FrameRegister;
};
std::vector<EndExceptionTableCall> endExceptionTableCalls;
virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
uint8_t *TableEnd, uint8_t* FrameRegister) {
endExceptionTableCalls.push_back(
EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
}
};
bool LoadAssemblyInto(Module *M, const char *assembly) {
SMDiagnostic Error;
bool success =
NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
std::string errMsg;
raw_string_ostream os(errMsg);
Error.print("", os);
EXPECT_TRUE(success) << os.str();
return success;
}
class JITTest : public testing::Test {
protected:
virtual RecordingJITMemoryManager *createMemoryManager() {
return new RecordingJITMemoryManager;
}
virtual void SetUp() {
M = new Module("<main>", Context);
RJMM = createMemoryManager();
RJMM->setPoisonMemory(true);
std::string Error;
TargetOptions Options;
Options.JITExceptionHandling = true;
TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
.setJITMemoryManager(RJMM)
.setErrorStr(&Error)
.setTargetOptions(Options).create());
ASSERT_TRUE(TheJIT.get() != NULL) << Error;
}
void LoadAssembly(const char *assembly) {
LoadAssemblyInto(M, assembly);
}
LLVMContext Context;
Module *M; // Owned by ExecutionEngine.
RecordingJITMemoryManager *RJMM;
OwningPtr<ExecutionEngine> TheJIT;
};
// Regression test for a bug. The JIT used to allocate globals inside the same
// memory block used for the function, and when the function code was freed,
// the global was left in the same place. This test allocates a function
// that uses and global, deallocates it, and then makes sure that the global
// stays alive after that.
TEST(JIT, GlobalInFunction) {
LLVMContext context;
Module *M = new Module("<main>", context);
JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
// Tell the memory manager to poison freed memory so that accessing freed
// memory is more easily tested.
MemMgr->setPoisonMemory(true);
std::string Error;
OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
.setEngineKind(EngineKind::JIT)
.setErrorStr(&Error)
.setJITMemoryManager(MemMgr)
// The next line enables the fix:
.setAllocateGVsWithCode(false)
.create());
ASSERT_EQ(Error, "");
// Create a global variable.
Type *GTy = Type::getInt32Ty(context);
GlobalVariable *G = new GlobalVariable(
*M,
GTy,
false, // Not constant.
GlobalValue::InternalLinkage,
Constant::getNullValue(GTy),
"myglobal");
// Make a function that points to a global.
Function *F1 = makeReturnGlobal("F1", G, M);
// Get the pointer to the native code to force it to JIT the function and
// allocate space for the global.
void (*F1Ptr)() =
reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
// Since F1 was codegen'd, a pointer to G should be available.
int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
ASSERT_NE((int32_t*)NULL, GPtr);
EXPECT_EQ(0, *GPtr);
// F1() should increment G.
F1Ptr();
EXPECT_EQ(1, *GPtr);
// Make a second function identical to the first, referring to the same
// global.
Function *F2 = makeReturnGlobal("F2", G, M);
void (*F2Ptr)() =
reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
// F2() should increment G.
F2Ptr();
EXPECT_EQ(2, *GPtr);
// Deallocate F1.
JIT->freeMachineCodeForFunction(F1);
// F2() should *still* increment G.
F2Ptr();
EXPECT_EQ(3, *GPtr);
}
// Regression test for a bug. The JITEmitter wasn't checking to verify that
// it hadn't run out of space while generating the DWARF exception information
// for an emitted function.
class ExceptionMemoryManagerMock : public RecordingJITMemoryManager {
public:
virtual uint8_t *startExceptionTable(const Function *F,
uintptr_t &ActualSize) {
// force an insufficient size the first time through.
bool ChangeActualSize = false;
if (ActualSize == 0)
ChangeActualSize = true;;
uint8_t *result =
RecordingJITMemoryManager::startExceptionTable(F, ActualSize);
if (ChangeActualSize)
ActualSize = 1;
return result;
}
};
class JITExceptionMemoryTest : public JITTest {
protected:
virtual RecordingJITMemoryManager *createMemoryManager() {
return new ExceptionMemoryManagerMock;
}
};
TEST_F(JITExceptionMemoryTest, ExceptionTableOverflow) {
Function *F = Function::Create(TypeBuilder<void(void), false>::get(Context),
Function::ExternalLinkage,
"func1", M);
BasicBlock *Block = BasicBlock::Create(Context, "block", F);
IRBuilder<> Builder(Block);
Builder.CreateRetVoid();
TheJIT->getPointerToFunction(F);
ASSERT_TRUE(RJMM->startExceptionTableCalls.size() == 2);
ASSERT_TRUE(RJMM->deallocateExceptionTableCalls.size() == 1);
ASSERT_TRUE(RJMM->endExceptionTableCalls.size() == 1);
}
int PlusOne(int arg) {
return arg + 1;
}
TEST_F(JITTest, FarCallToKnownFunction) {
// x86-64 can only make direct calls to functions within 32 bits of
// the current PC. To call anything farther away, we have to load
// the address into a register and call through the register. The
// current JIT does this by allocating a stub for any far call.
// There was a bug in which the JIT tried to emit a direct call when
// the target was already in the JIT's global mappings and lazy
// compilation was disabled.
Function *KnownFunction = Function::Create(
TypeBuilder<int(int), false>::get(Context),
GlobalValue::ExternalLinkage, "known", M);
TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
// int test() { return known(7); }
Function *TestFunction = Function::Create(
TypeBuilder<int(), false>::get(Context),
GlobalValue::ExternalLinkage, "test", M);
BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
IRBuilder<> Builder(Entry);
Value *result = Builder.CreateCall(
KnownFunction,
ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
Builder.CreateRet(result);
TheJIT->DisableLazyCompilation(true);
int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
(intptr_t)TheJIT->getPointerToFunction(TestFunction));
// This used to crash in trying to call PlusOne().
EXPECT_EQ(8, TestFunctionPtr());
}
// Test a function C which calls A and B which call each other.
TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
TheJIT->DisableLazyCompilation(true);
FunctionType *Func1Ty =
cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
std::vector<Type*> arg_types;
arg_types.push_back(Type::getInt1Ty(Context));
FunctionType *FuncTy = FunctionType::get(
Type::getVoidTy(Context), arg_types, false);
Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
"func1", M);
Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
"func2", M);
Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
"func3", M);
BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
// Make Func1 call Func2(0) and Func3(0).
IRBuilder<> Builder(Block1);
Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
Builder.CreateRetVoid();
// void Func2(bool b) { if (b) { Func3(false); return; } return; }
Builder.SetInsertPoint(Block2);
Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
Builder.SetInsertPoint(True2);
Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
Builder.CreateRetVoid();
Builder.SetInsertPoint(False2);
Builder.CreateRetVoid();
// void Func3(bool b) { if (b) { Func2(false); return; } return; }
Builder.SetInsertPoint(Block3);
Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
Builder.SetInsertPoint(True3);
Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
Builder.CreateRetVoid();
Builder.SetInsertPoint(False3);
Builder.CreateRetVoid();
// Compile the function to native code
void (*F1Ptr)() =
reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
F1Ptr();
}
// Regression test for PR5162. This used to trigger an AssertingVH inside the
// JIT's Function to stub mapping.
TEST_F(JITTest, NonLazyLeaksNoStubs) {
TheJIT->DisableLazyCompilation(true);
// Create two functions with a single basic block each.
FunctionType *FuncTy =
cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
"func1", M);
Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
"func2", M);
BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
// The first function calls the second and returns the result
IRBuilder<> Builder(Block1);
Value *Result = Builder.CreateCall(Func2);
Builder.CreateRet(Result);
// The second function just returns a constant
Builder.SetInsertPoint(Block2);
Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
// Compile the function to native code
(void)TheJIT->getPointerToFunction(Func1);
// Free the JIT state for the functions
TheJIT->freeMachineCodeForFunction(Func1);
TheJIT->freeMachineCodeForFunction(Func2);
// Delete the first function (and show that is has no users)
EXPECT_EQ(Func1->getNumUses(), 0u);
Func1->eraseFromParent();
// Delete the second function (and show that it has no users - it had one,
// func1 but that's gone now)
EXPECT_EQ(Func2->getNumUses(), 0u);
Func2->eraseFromParent();
}
TEST_F(JITTest, ModuleDeletion) {
TheJIT->DisableLazyCompilation(false);
LoadAssembly("define void @main() { "
" call i32 @computeVal() "
" ret void "
"} "
" "
"define internal i32 @computeVal() { "
" ret i32 0 "
"} ");
Function *func = M->getFunction("main");
TheJIT->getPointerToFunction(func);
TheJIT->removeModule(M);
delete M;
SmallPtrSet<const void*, 2> FunctionsDeallocated;
for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
i != e; ++i) {
FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
}
for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
EXPECT_TRUE(FunctionsDeallocated.count(
RJMM->startFunctionBodyCalls[i].Result))
<< "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
}
EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
RJMM->deallocateFunctionBodyCalls.size());
SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
unsigned NumTablesDeallocated = 0;
for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
i != e; ++i) {
ExceptionTablesDeallocated.insert(
RJMM->deallocateExceptionTableCalls[i].ET);
if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
// If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
// appear in startExceptionTableCalls.
NumTablesDeallocated++;
}
}
for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
EXPECT_TRUE(ExceptionTablesDeallocated.count(
RJMM->startExceptionTableCalls[i].Result))
<< "Function's exception table leaked: \n"
<< RJMM->startExceptionTableCalls[i].F_dump;
}
EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
NumTablesDeallocated);
}
// ARM, MIPS and PPC still emit stubs for calls since the target may be
// too far away to call directly. This #if can probably be removed when
// http://llvm.org/PR5201 is fixed.
#if !defined(__arm__) && !defined(__mips__) && \
!defined(__powerpc__) && !defined(__ppc__)
typedef int (*FooPtr) ();
TEST_F(JITTest, NoStubs) {
LoadAssembly("define void @bar() {"
"entry: "
"ret void"
"}"
" "
"define i32 @foo() {"
"entry:"
"call void @bar()"
"ret i32 undef"
"}"
" "
"define i32 @main() {"
"entry:"
"%0 = call i32 @foo()"
"call void @bar()"
"ret i32 undef"
"}");
Function *foo = M->getFunction("foo");
uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
FooPtr ptr = (FooPtr)(tmp);
(ptr)();
// We should now allocate no more stubs, we have the code to foo
// and the existing stub for bar.
int stubsBefore = RJMM->stubsAllocated;
Function *func = M->getFunction("main");
TheJIT->getPointerToFunction(func);
Function *bar = M->getFunction("bar");
TheJIT->getPointerToFunction(bar);
ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
}
#endif // !ARM && !PPC
TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
TheJIT->DisableLazyCompilation(true);
LoadAssembly("define i8()* @get_foo_addr() { "
" ret i8()* @foo "
"} "
" "
"define i8 @foo() { "
" ret i8 42 "
"} ");
Function *F_get_foo_addr = M->getFunction("get_foo_addr");
typedef char(*fooT)();
fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
(intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
fooT foo_addr = get_foo_addr();
// Now free get_foo_addr. This should not free the machine code for foo or
// any call stub returned as foo's canonical address.
TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
// Check by calling the reported address of foo.
EXPECT_EQ(42, foo_addr());
// The reported address should also be the same as the result of a subsequent
// getPointerToFunction(foo).
#if 0
// Fails until PR5126 is fixed:
Function *F_foo = M->getFunction("foo");
fooT foo = reinterpret_cast<fooT>(
(intptr_t)TheJIT->getPointerToFunction(F_foo));
EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
#endif
}
// ARM does not have an implementation of replaceMachineCodeForFunction(),
// so recompileAndRelinkFunction doesn't work.
#if !defined(__arm__)
TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
GlobalValue::ExternalLinkage, "test", M);
BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
IRBuilder<> Builder(Entry);
Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
Builder.CreateRet(Val);
TheJIT->DisableLazyCompilation(true);
// Compile the function once, and make sure it works.
int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
(intptr_t)TheJIT->recompileAndRelinkFunction(F));
EXPECT_EQ(1, OrigFPtr());
// Now change the function to return a different value.
Entry->eraseFromParent();
BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
Builder.SetInsertPoint(NewEntry);
Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
Builder.CreateRet(Val);
// Recompile it, which should produce a new function pointer _and_ update the
// old one.
int (*NewFPtr)() = reinterpret_cast<int(*)()>(
(intptr_t)TheJIT->recompileAndRelinkFunction(F));
EXPECT_EQ(2, NewFPtr())
<< "The new pointer should call the new version of the function";
EXPECT_EQ(2, OrigFPtr())
<< "The old pointer's target should now jump to the new version";
}
#endif // !defined(__arm__)
} // anonymous namespace
// This variable is intentionally defined differently in the statically-compiled
// program from the IR input to the JIT to assert that the JIT doesn't use its
// definition.
extern "C" int32_t JITTest_AvailableExternallyGlobal;
int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
namespace {
TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
TheJIT->DisableLazyCompilation(true);
LoadAssembly("@JITTest_AvailableExternallyGlobal = "
" available_externally global i32 7 "
" "
"define i32 @loader() { "
" %result = load i32* @JITTest_AvailableExternallyGlobal "
" ret i32 %result "
"} ");
Function *loaderIR = M->getFunction("loader");
int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
(intptr_t)TheJIT->getPointerToFunction(loaderIR));
EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
<< " not 7 from the IR version.";
}
} // anonymous namespace
// This function is intentionally defined differently in the statically-compiled
// program from the IR input to the JIT to assert that the JIT doesn't use its
// definition.
extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
extern "C" int32_t JITTest_AvailableExternallyFunction() {
return 42;
}
namespace {
TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
TheJIT->DisableLazyCompilation(true);
LoadAssembly("define available_externally i32 "
" @JITTest_AvailableExternallyFunction() { "
" ret i32 7 "
"} "
" "
"define i32 @func() { "
" %result = tail call i32 "
" @JITTest_AvailableExternallyFunction() "
" ret i32 %result "
"} ");
Function *funcIR = M->getFunction("func");
int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
(intptr_t)TheJIT->getPointerToFunction(funcIR));
EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
<< " not 7 from the IR version.";
}
TEST_F(JITTest, EscapedLazyStubStillCallable) {
TheJIT->DisableLazyCompilation(false);
LoadAssembly("define internal i32 @stubbed() { "
" ret i32 42 "
"} "
" "
"define i32()* @get_stub() { "
" ret i32()* @stubbed "
"} ");
typedef int32_t(*StubTy)();
// Call get_stub() to get the address of @stubbed without actually JITting it.
Function *get_stubIR = M->getFunction("get_stub");
StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
(intptr_t)TheJIT->getPointerToFunction(get_stubIR));
StubTy stubbed = get_stub();
// Now get_stubIR is the only reference to stubbed's stub.
get_stubIR->eraseFromParent();
// Now there are no references inside the JIT, but we've got a pointer outside
// it. The stub should be callable and return the right value.
EXPECT_EQ(42, stubbed());
}
// Converts the LLVM assembly to bitcode and returns it in a std::string. An
// empty string indicates an error.
std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
Module TempModule("TempModule", Context);
if (!LoadAssemblyInto(&TempModule, Assembly)) {
return "";
}
std::string Result;
raw_string_ostream OS(Result);
WriteBitcodeToFile(&TempModule, OS);
OS.flush();
return Result;
}
// Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
// lazily. The associated Module (owned by the ExecutionEngine) is returned in
// M. Both will be NULL on an error. Bitcode must live at least as long as the
// ExecutionEngine.
ExecutionEngine *getJITFromBitcode(
LLVMContext &Context, const std::string &Bitcode, Module *&M) {
// c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
MemoryBuffer *BitcodeBuffer =
MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
std::string errMsg;
M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
if (M == NULL) {
ADD_FAILURE() << errMsg;
delete BitcodeBuffer;
return NULL;
}
ExecutionEngine *TheJIT = EngineBuilder(M)
.setEngineKind(EngineKind::JIT)
.setErrorStr(&errMsg)
.create();
if (TheJIT == NULL) {
ADD_FAILURE() << errMsg;
delete M;
M = NULL;
return NULL;
}
return TheJIT;
}
TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
LLVMContext Context;
const std::string Bitcode =
AssembleToBitcode(Context,
"define available_externally i32 "
" @JITTest_AvailableExternallyFunction() { "
" ret i32 7 "
"} "
" "
"define i32 @func() { "
" %result = tail call i32 "
" @JITTest_AvailableExternallyFunction() "
" ret i32 %result "
"} ");
ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
Module *M;
OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
TheJIT->DisableLazyCompilation(true);
Function *funcIR = M->getFunction("func");
Function *availableFunctionIR =
M->getFunction("JITTest_AvailableExternallyFunction");
// Double-check that the available_externally function is still unmaterialized
// when getPointerToFunction needs to find out if it's available_externally.
EXPECT_TRUE(availableFunctionIR->isMaterializable());
int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
(intptr_t)TheJIT->getPointerToFunction(funcIR));
EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
<< " not 7 from the IR version.";
}
TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
LLVMContext Context;
const std::string Bitcode =
AssembleToBitcode(Context,
"define i32 @recur1(i32 %a) { "
" %zero = icmp eq i32 %a, 0 "
" br i1 %zero, label %done, label %notdone "
"done: "
" ret i32 3 "
"notdone: "
" %am1 = sub i32 %a, 1 "
" %result = call i32 @recur2(i32 %am1) "
" ret i32 %result "
"} "
" "
"define i32 @recur2(i32 %b) { "
" %result = call i32 @recur1(i32 %b) "
" ret i32 %result "
"} ");
ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
Module *M;
OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
TheJIT->DisableLazyCompilation(true);
Function *recur1IR = M->getFunction("recur1");
Function *recur2IR = M->getFunction("recur2");
EXPECT_TRUE(recur1IR->isMaterializable());
EXPECT_TRUE(recur2IR->isMaterializable());
int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
(intptr_t)TheJIT->getPointerToFunction(recur1IR));
EXPECT_EQ(3, recur1(4));
}
#endif // !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__)
// This code is copied from JITEventListenerTest, but it only runs once for all
// the tests in this directory. Everything seems fine, but that's strange
// behavior.
class JITEnvironment : public testing::Environment {
virtual void SetUp() {
// Required to create a JIT.
InitializeNativeTarget();
}
};
testing::Environment* const jit_env =
testing::AddGlobalTestEnvironment(new JITEnvironment);
}
| {
"content_hash": "709aaea4eb9f53e93471821648cebbfc",
"timestamp": "",
"source": "github",
"line_count": 810,
"max_line_length": 80,
"avg_line_length": 37.89012345679012,
"alnum_prop": 0.6544263790687824,
"repo_name": "dbrumley/recfi",
"id": "e6f4cb9af25f58d6f4aeeddf98282a2cef2acc33",
"size": "31796",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "llvm-3.3/unittests/ExecutionEngine/JIT/JITTest.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "1429"
},
{
"name": "Assembly",
"bytes": "122962"
},
{
"name": "C",
"bytes": "4967979"
},
{
"name": "C++",
"bytes": "66281851"
},
{
"name": "CMake",
"bytes": "256087"
},
{
"name": "CSS",
"bytes": "32870"
},
{
"name": "Cuda",
"bytes": "6807"
},
{
"name": "Elixir",
"bytes": "1032"
},
{
"name": "Emacs Lisp",
"bytes": "22022"
},
{
"name": "Gnuplot",
"bytes": "1991"
},
{
"name": "Groff",
"bytes": "542387"
},
{
"name": "HTML",
"bytes": "487005"
},
{
"name": "JavaScript",
"bytes": "17391"
},
{
"name": "LLVM",
"bytes": "563544"
},
{
"name": "M",
"bytes": "219"
},
{
"name": "Makefile",
"bytes": "661838"
},
{
"name": "Mathematica",
"bytes": "523"
},
{
"name": "Matlab",
"bytes": "25465"
},
{
"name": "Mercury",
"bytes": "1222"
},
{
"name": "OCaml",
"bytes": "274618"
},
{
"name": "Objective-C",
"bytes": "3813281"
},
{
"name": "Objective-C++",
"bytes": "475843"
},
{
"name": "Perl",
"bytes": "186023"
},
{
"name": "Python",
"bytes": "738736"
},
{
"name": "Ruby",
"bytes": "1496"
},
{
"name": "Scala",
"bytes": "363"
},
{
"name": "Shell",
"bytes": "997012"
},
{
"name": "Standard ML",
"bytes": "2841"
},
{
"name": "TeX",
"bytes": "16173"
},
{
"name": "VimL",
"bytes": "13186"
}
],
"symlink_target": ""
} |
extern char *title, *genBaseBuf; //src file info
extern int **Indexarray, *IndexarrayNum, HashStrlen, IndexPosiCount, BaseCount, *IndexPosition,VALUELEN;//index info
extern char IndexPreKey[];
extern float E;
extern int *ref_index, refunit, Readlen,CONSIDERLEN,cp;
//associate function
int base_hash(unsigned char a, int b);
int stringcmp(char *str1, char *str2);
char Caps(char a);
char REV(char a);
//genProcess
char * genProcess(char *genFileName, char *genBaseBuf, char *PreKey);
//map function
int map(char *readFileName, char*buf, char *outFileName, char *argv[]);
//int output_test( chp filename, chp base_title ); //test
| {
"content_hash": "a0c3364290c82e36001cbfa69c1731a5",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 118,
"avg_line_length": 30.857142857142858,
"alnum_prop": 0.7283950617283951,
"repo_name": "Zhuzxlab/LW-FQZip2",
"id": "11e8be4838d5873fd7fcf1abec6b54bbcdb0253a",
"size": "897",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "head.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "100863"
},
{
"name": "C++",
"bytes": "30662"
},
{
"name": "Makefile",
"bytes": "711"
}
],
"symlink_target": ""
} |
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.sass']
})
export class HeaderComponent implements OnInit {
codsys:any;
constructor(private router: Router) {
this.codsys = sessionStorage.getItem('codsys');
}
ngOnInit() {
}
salir(){
sessionStorage.removeItem('codsys');
this.codsys = null;
this.router.navigate(['/']);
}
}
| {
"content_hash": "93da198ddc3e1e7e7680fbfa39852d67",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 55,
"avg_line_length": 22.08,
"alnum_prop": 0.6195652173913043,
"repo_name": "irvin373/ElectroInscripciones",
"id": "2fb5f9b15d73a47180caa732c2814a6079a3eafe",
"size": "552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/common/header/header.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "971"
},
{
"name": "HTML",
"bytes": "5189"
},
{
"name": "JavaScript",
"bytes": "2570"
},
{
"name": "Ruby",
"bytes": "6161"
},
{
"name": "TypeScript",
"bytes": "22565"
}
],
"symlink_target": ""
} |
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{ url_for('public.home') }}">
To-Do
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="{{ url_for('public.home') }}">Home</a></li>
<li><a href="{{ url_for('public.about') }}">About</a></li>
</ul>
{% if current_user and current_user.is_authenticated %}
<ul class="nav navbar-nav navbar-right">
<li>
<p class="navbar-text"><a class="navbar-link" href="{{ url_for('user.members') }}">Logged in as {{ current_user.username }}</a></p>
</li>
<li><a class="navbar-link" href="{{ url_for('public.logout') }}"><i class="fa fa-sign-out"></i></a></li>
</ul>
{% endif %}
</div><!-- /.navbar-collapse -->
</div><!-- /.container -->
</nav>
| {
"content_hash": "84d68dc3631fd1ebbebbd0f01d4643f7",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 143,
"avg_line_length": 36.972972972972975,
"alnum_prop": 0.5855263157894737,
"repo_name": "terryjbates/test-driven-development-with-python",
"id": "d96f403c47a95eac2a601ada482d754bcf0729ab",
"size": "1369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "myflaskapp/myflaskapp/templates/partials/nav.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3411"
},
{
"name": "HTML",
"bytes": "68616"
},
{
"name": "JavaScript",
"bytes": "142"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "PHP",
"bytes": "5444"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Python",
"bytes": "54220"
},
{
"name": "Ruby",
"bytes": "1030"
}
],
"symlink_target": ""
} |
if(NOT generated_file)
message(FATAL_ERROR "You must specify generated_file on the command line")
endif()
# Set these up as variables to make reading the generated file easier
set(CMAKE_COMMAND "/usr/bin/cmake") # path
set(source_file "/home/yhtsai/caffe-cedn-dev/src/caffe/layers/bnll_layer.cu") # path
set(NVCC_generated_dependency_file "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/caffe_cu_generated_bnll_layer.cu.o.NVCC-depend") # path
set(cmake_dependency_file "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/caffe_cu_generated_bnll_layer.cu.o.depend") # path
set(CUDA_make2cmake "/usr/share/cmake-2.8/Modules/FindCUDA/make2cmake.cmake") # path
set(CUDA_parse_cubin "/usr/share/cmake-2.8/Modules/FindCUDA/parse_cubin.cmake") # path
set(build_cubin OFF) # bool
set(CUDA_HOST_COMPILER "/usr/bin/cc") # bool
# We won't actually use these variables for now, but we need to set this, in
# order to force this file to be run again if it changes.
set(generated_file_path "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/.") # path
set(generated_file_internal "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/./caffe_cu_generated_bnll_layer.cu.o") # path
set(generated_cubin_file_internal "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/./caffe_cu_generated_bnll_layer.cu.o.cubin.txt") # path
set(CUDA_NVCC_EXECUTABLE "/usr/local/cuda/bin/nvcc") # path
set(CUDA_NVCC_FLAGS -gencode;arch=compute_20,code=sm_20;-gencode;arch=compute_20,code=sm_21;-gencode;arch=compute_30,code=sm_30;-gencode;arch=compute_35,code=sm_35 ;; ) # list
# Build specific configuration flags
set(CUDA_NVCC_FLAGS_DEBUG ; )
set(CUDA_NVCC_FLAGS_MINSIZEREL ; )
set(CUDA_NVCC_FLAGS_RELEASE ; )
set(CUDA_NVCC_FLAGS_RELWITHDEBINFO ; )
set(nvcc_flags -m64) # list
set(CUDA_NVCC_INCLUDE_ARGS "-I/usr/local/cuda/include;-I/home/yhtsai/caffe-cedn-dev/include;-I/home/yhtsai/caffe-cedn-dev/src;-I/usr/local/cuda/include;-I/usr/include;-I/usr/include/atlas;-I/usr/local/include/opencv;-I/usr/local/include") # list (needs to be in quotes to handle spaces properly).
set(format_flag "-c") # string
if(build_cubin AND NOT generated_cubin_file)
message(FATAL_ERROR "You must specify generated_cubin_file on the command line")
endif()
# This is the list of host compilation flags. It C or CXX should already have
# been chosen by FindCUDA.cmake.
set(CMAKE_HOST_FLAGS -fPIC )
set(CMAKE_HOST_FLAGS_DEBUG -g)
set(CMAKE_HOST_FLAGS_MINSIZEREL -Os -DNDEBUG)
set(CMAKE_HOST_FLAGS_RELEASE -O3 -DNDEBUG)
set(CMAKE_HOST_FLAGS_RELWITHDEBINFO -O2 -g -DNDEBUG)
# Take the compiler flags and package them up to be sent to the compiler via -Xcompiler
set(nvcc_host_compiler_flags "")
# If we weren't given a build_configuration, use Debug.
if(NOT build_configuration)
set(build_configuration Debug)
endif()
string(TOUPPER "${build_configuration}" build_configuration)
#message("CUDA_NVCC_HOST_COMPILER_FLAGS = ${CUDA_NVCC_HOST_COMPILER_FLAGS}")
foreach(flag ${CMAKE_HOST_FLAGS} ${CMAKE_HOST_FLAGS_${build_configuration}})
# Extra quotes are added around each flag to help nvcc parse out flags with spaces.
set(nvcc_host_compiler_flags "${nvcc_host_compiler_flags},\"${flag}\"")
endforeach()
if (nvcc_host_compiler_flags)
set(nvcc_host_compiler_flags "-Xcompiler" ${nvcc_host_compiler_flags})
endif()
#message("nvcc_host_compiler_flags = \"${nvcc_host_compiler_flags}\"")
# Add the build specific configuration flags
list(APPEND CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS_${build_configuration}})
# Any -ccbin existing in CUDA_NVCC_FLAGS gets highest priority
list( FIND CUDA_NVCC_FLAGS "-ccbin" ccbin_found0 )
list( FIND CUDA_NVCC_FLAGS "--compiler-bindir" ccbin_found1 )
if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 )
if (CUDA_HOST_COMPILER STREQUAL "$(VCInstallDir)bin" AND DEFINED CCBIN)
set(CCBIN -ccbin "${CCBIN}")
else()
set(CCBIN -ccbin "${CUDA_HOST_COMPILER}")
endif()
endif()
# cuda_execute_process - Executes a command with optional command echo and status message.
#
# status - Status message to print if verbose is true
# command - COMMAND argument from the usual execute_process argument structure
# ARGN - Remaining arguments are the command with arguments
#
# CUDA_result - return value from running the command
#
# Make this a macro instead of a function, so that things like RESULT_VARIABLE
# and other return variables are present after executing the process.
macro(cuda_execute_process status command)
set(_command ${command})
if(NOT _command STREQUAL "COMMAND")
message(FATAL_ERROR "Malformed call to cuda_execute_process. Missing COMMAND as second argument. (command = ${command})")
endif()
if(verbose)
execute_process(COMMAND "${CMAKE_COMMAND}" -E echo -- ${status})
# Now we need to build up our command string. We are accounting for quotes
# and spaces, anything else is left up to the user to fix if they want to
# copy and paste a runnable command line.
set(cuda_execute_process_string)
foreach(arg ${ARGN})
# If there are quotes, excape them, so they come through.
string(REPLACE "\"" "\\\"" arg ${arg})
# Args with spaces need quotes around them to get them to be parsed as a single argument.
if(arg MATCHES " ")
list(APPEND cuda_execute_process_string "\"${arg}\"")
else()
list(APPEND cuda_execute_process_string ${arg})
endif()
endforeach()
# Echo the command
execute_process(COMMAND ${CMAKE_COMMAND} -E echo ${cuda_execute_process_string})
endif()
# Run the command
execute_process(COMMAND ${ARGN} RESULT_VARIABLE CUDA_result )
endmacro()
# Delete the target file
cuda_execute_process(
"Removing ${generated_file}"
COMMAND "${CMAKE_COMMAND}" -E remove "${generated_file}"
)
# For CUDA 2.3 and below, -G -M doesn't work, so remove the -G flag
# for dependency generation and hope for the best.
set(depends_CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS}")
set(CUDA_VERSION 7.0)
if(CUDA_VERSION VERSION_LESS "3.0")
cmake_policy(PUSH)
# CMake policy 0007 NEW states that empty list elements are not
# ignored. I'm just setting it to avoid the warning that's printed.
cmake_policy(SET CMP0007 NEW)
# Note that this will remove all occurances of -G.
list(REMOVE_ITEM depends_CUDA_NVCC_FLAGS "-G")
cmake_policy(POP)
endif()
# nvcc doesn't define __CUDACC__ for some reason when generating dependency files. This
# can cause incorrect dependencies when #including files based on this macro which is
# defined in the generating passes of nvcc invokation. We will go ahead and manually
# define this for now until a future version fixes this bug.
set(CUDACC_DEFINE -D__CUDACC__)
# Generate the dependency file
cuda_execute_process(
"Generating dependency file: ${NVCC_generated_dependency_file}"
COMMAND "${CUDA_NVCC_EXECUTABLE}"
-M
${CUDACC_DEFINE}
"${source_file}"
-o "${NVCC_generated_dependency_file}"
${CCBIN}
${nvcc_flags}
${nvcc_host_compiler_flags}
${depends_CUDA_NVCC_FLAGS}
-DNVCC
${CUDA_NVCC_INCLUDE_ARGS}
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
# Generate the cmake readable dependency file to a temp file. Don't put the
# quotes just around the filenames for the input_file and output_file variables.
# CMake will pass the quotes through and not be able to find the file.
cuda_execute_process(
"Generating temporary cmake readable file: ${cmake_dependency_file}.tmp"
COMMAND "${CMAKE_COMMAND}"
-D "input_file:FILEPATH=${NVCC_generated_dependency_file}"
-D "output_file:FILEPATH=${cmake_dependency_file}.tmp"
-P "${CUDA_make2cmake}"
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
# Copy the file if it is different
cuda_execute_process(
"Copy if different ${cmake_dependency_file}.tmp to ${cmake_dependency_file}"
COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${cmake_dependency_file}.tmp" "${cmake_dependency_file}"
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
# Delete the temporary file
cuda_execute_process(
"Removing ${cmake_dependency_file}.tmp and ${NVCC_generated_dependency_file}"
COMMAND "${CMAKE_COMMAND}" -E remove "${cmake_dependency_file}.tmp" "${NVCC_generated_dependency_file}"
)
if(CUDA_result)
message(FATAL_ERROR "Error generating ${generated_file}")
endif()
# Generate the code
cuda_execute_process(
"Generating ${generated_file}"
COMMAND "${CUDA_NVCC_EXECUTABLE}"
"${source_file}"
${format_flag} -o "${generated_file}"
${CCBIN}
${nvcc_flags}
${nvcc_host_compiler_flags}
${CUDA_NVCC_FLAGS}
-DNVCC
${CUDA_NVCC_INCLUDE_ARGS}
)
if(CUDA_result)
# Since nvcc can sometimes leave half done files make sure that we delete the output file.
cuda_execute_process(
"Removing ${generated_file}"
COMMAND "${CMAKE_COMMAND}" -E remove "${generated_file}"
)
message(FATAL_ERROR "Error generating file ${generated_file}")
else()
if(verbose)
message("Generated ${generated_file} successfully.")
endif()
endif()
# Cubin resource report commands.
if( build_cubin )
# Run with -cubin to produce resource usage report.
cuda_execute_process(
"Generating ${generated_cubin_file}"
COMMAND "${CUDA_NVCC_EXECUTABLE}"
"${source_file}"
${CUDA_NVCC_FLAGS}
${nvcc_flags}
${CCBIN}
${nvcc_host_compiler_flags}
-DNVCC
-cubin
-o "${generated_cubin_file}"
${CUDA_NVCC_INCLUDE_ARGS}
)
# Execute the parser script.
cuda_execute_process(
"Executing the parser script"
COMMAND "${CMAKE_COMMAND}"
-D "input_file:STRING=${generated_cubin_file}"
-P "${CUDA_parse_cubin}"
)
endif()
| {
"content_hash": "f80410d3e7e39f5e74115d301860c17f",
"timestamp": "",
"source": "github",
"line_count": 244,
"max_line_length": 296,
"avg_line_length": 40.17622950819672,
"alnum_prop": 0.722329899010507,
"repo_name": "wasidennis/ObjectFlow",
"id": "ae709d328cc97a735ac6d8072b512ae499aea522",
"size": "12358",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/caffe_cu_generated_bnll_layer.cu.o.cmake",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "169454"
},
{
"name": "C++",
"bytes": "2850567"
},
{
"name": "CMake",
"bytes": "618989"
},
{
"name": "CSS",
"bytes": "11159"
},
{
"name": "Cuda",
"bytes": "153904"
},
{
"name": "HTML",
"bytes": "1395248"
},
{
"name": "M",
"bytes": "2500"
},
{
"name": "Makefile",
"bytes": "27486"
},
{
"name": "Matlab",
"bytes": "1965241"
},
{
"name": "Mercury",
"bytes": "66"
},
{
"name": "Objective-C",
"bytes": "835"
},
{
"name": "Python",
"bytes": "289758"
},
{
"name": "Shell",
"bytes": "12728"
},
{
"name": "TeX",
"bytes": "17617"
}
],
"symlink_target": ""
} |
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include "CDragDrop_Windows.hpp"
# include "CDragDrop_macOS.hpp"
# include "CDragDrop_Linux.hpp"
namespace s3d
{
ISiv3DDragDrop* ISiv3DDragDrop::Create()
{
# if defined(SIV3D_TARGET_WINDOWS)
return new CDragDrop_Windows;
# elif defined(SIV3D_TARGET_MACOS)
return new CDragDrop_macOS;
# elif defined(SIV3D_TARGET_LINUX)
return new CDragDrop_Linux;
# endif
}
}
| {
"content_hash": "38962bc08fbdb7f346402d775055702c",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 50,
"avg_line_length": 18.942857142857143,
"alnum_prop": 0.5942684766214178,
"repo_name": "azaika/OpenSiv3D",
"id": "b2c191885bb827a486645523cff2aea44795980e",
"size": "665",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Siv3D/src/Siv3D/DragDrop/DragDropFactory.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5323769"
},
{
"name": "C++",
"bytes": "6296248"
},
{
"name": "CMake",
"bytes": "19797"
},
{
"name": "HLSL",
"bytes": "1912"
},
{
"name": "Mathematica",
"bytes": "15411"
},
{
"name": "Objective-C",
"bytes": "145242"
},
{
"name": "Objective-C++",
"bytes": "17002"
},
{
"name": "Shell",
"bytes": "1039"
},
{
"name": "SourcePawn",
"bytes": "3977"
}
],
"symlink_target": ""
} |
import 'whatwg-fetch'
export default function (file, api) {
const resource = file ? `/${file}` : api
return fetch(resource) // eslint-disable-line
.then(response => {
if (file) {
const fileSplit = file.split('.')
if (fileSplit[fileSplit.length - 1] === 'json') {
return response.json()
} else {
return response.text()
}
} else {
return response.json()
}
}).then(res => {
return res
})
}
| {
"content_hash": "8f8cef1f58b82ba48899f74b0cdaabd0",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 57,
"avg_line_length": 24.4,
"alnum_prop": 0.5225409836065574,
"repo_name": "swirlycheetah/radiate",
"id": "6e172f08314591ac31d47a2eff6f6f070f5601a1",
"size": "488",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/fetch.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "772"
},
{
"name": "JavaScript",
"bytes": "28161"
}
],
"symlink_target": ""
} |
"""
netvisor.schemas.sales_invoices.get
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013-2016 by Fast Monkeys Oy.
:license: MIT, see LICENSE for more details.
"""
from marshmallow import Schema, fields, post_load
from ..common import DateSchema, DecimalSchema, StringSchema
from ..fields import Boolean, Decimal, List
class VatPercentageSchema(Schema):
percentage = Decimal(required=True, load_from='#text')
code = fields.String(required=True, load_from='@vatcode')
class SalesInvoiceProductLineSchema(Schema):
name = fields.String(load_from='product_name')
identifier = fields.Nested(
StringSchema,
load_from='productidentifier'
)
unit_price = Decimal(load_from='product_unit_price')
quantity = Decimal(load_from='sales_invoice_product_line_quantity')
discount_percentage = Decimal(
load_from='sales_invoice_product_line_discount_percentage'
)
free_text = fields.String(
allow_none=True,
load_from='sales_invoice_product_line_free_text'
)
accounting_account_suggestion = fields.String(allow_none=True)
sum = Decimal(load_from='sales_invoice_product_line_sum')
vat_percentage = fields.Nested(
VatPercentageSchema,
load_from='product_vat_percentage'
)
vat_sum = Decimal(load_from='sales_invoice_product_line_vat_sum')
class InvoiceLineSchema(Schema):
product_lines = List(
fields.Nested(SalesInvoiceProductLineSchema),
load_from='sales_invoice_product_line'
)
@post_load
def preprocess_invoice_line(self, input_data):
if input_data:
return input_data['product_lines']
class InvoiceLinesSchema(Schema):
invoice_line = fields.Nested(InvoiceLineSchema)
@post_load
def preprocess_invoice_lines(self, input_data):
if input_data:
return input_data['invoice_line']
class GetSalesInvoiceSchema(Schema):
number = fields.Integer(
required=True,
load_from='sales_invoice_number'
)
date = fields.Nested(
DateSchema,
required=True,
load_from='sales_invoice_date'
)
delivery_date = fields.Nested(
DateSchema,
required=True,
load_from='sales_invoice_delivery_date'
)
due_date = fields.Nested(
DateSchema,
required=True,
load_from='sales_invoice_due_date'
)
reference_number = fields.String(
required=True,
load_from='sales_invoice_referencenumber'
)
amount = fields.Nested(
DecimalSchema(),
required=True,
load_from='sales_invoice_amount'
)
delivery_method = fields.String(
required=True,
allow_none=True
)
delivery_term = fields.String(
required=True,
allow_none=True
)
free_text_after_lines = fields.String(
required=True,
allow_none=True,
load_from='sales_invoice_free_text_after_lines'
)
free_text_before_lines = fields.String(
required=True,
allow_none=True,
load_from='sales_invoice_free_text_before_lines'
)
payment_term_cash_discount = fields.Nested(DecimalSchema)
payment_term_cash_discount_days = fields.Integer(allow_none=True)
payment_term_net_days = fields.Integer(allow_none=True)
invoicing_customer_name = fields.String(required=True)
invoicing_customer_address_line = fields.String(
allow_none=True,
required=True,
load_from='invoicing_customer_addressline'
)
invoicing_customer_post_number = fields.String(
allow_none=True,
required=True,
load_from='invoicing_customer_postnumber'
)
invoicing_customer_town = fields.String(allow_none=True, required=True)
invoicing_customer_country_code = fields.String(required=True)
delivery_address_name = fields.String(allow_none=True, required=True)
delivery_address_line = fields.String(allow_none=True, required=True)
delivery_address_post_number = fields.String(
allow_none=True,
required=True,
load_from='delivery_address_postnumber'
)
delivery_address_town = fields.String(allow_none=True, required=True)
delivery_address_country_code = fields.String(
allow_none=True,
required=True
)
our_reference = fields.String(
allow_none=True,
load_from='sales_invoice_our_reference'
)
your_reference = fields.String(
allow_none=True,
load_from='sales_invoice_your_reference'
)
private_comment = fields.String(
allow_none=True,
load_from='sales_invoice_private_comment'
)
seller_identifier = fields.Nested(StringSchema)
invoice_status = fields.String(required=True)
invoice_lines = fields.Nested(InvoiceLinesSchema)
match_partial_payments_by_default = Boolean(true='Yes', false='No')
| {
"content_hash": "bef6ad5387ca1352d9e5866a65cdf78c",
"timestamp": "",
"source": "github",
"line_count": 154,
"max_line_length": 75,
"avg_line_length": 31.75974025974026,
"alnum_prop": 0.6577387037415662,
"repo_name": "fastmonkeys/netvisor.py",
"id": "12b8abda6e26a3028a6eae9e04b2f06149c85d71",
"size": "4915",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "netvisor/schemas/sales_invoices/get.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "100072"
}
],
"symlink_target": ""
} |
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.04.19 um 09:36:45 AM CEST
//
package de.immobilienscout24.rest.schema.common._1;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse fr CommercializationType.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
* <p>
* <pre>
* <simpleType name="CommercializationType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="BUY"/>
* <enumeration value="RENT"/>
* <enumeration value="LEASE"/>
* <enumeration value="LEASEHOLD"/>
* <enumeration value="COMPULSORY_AUCTION"/>
* <enumeration value="RENT_AND_BUY"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CommercializationType")
@XmlEnum
public enum CommercializationType {
/**
* Kauf
*
*/
BUY,
/**
* Miete
*
*/
RENT,
/**
* Pacht
*
*/
LEASE,
/**
* Erbpacht
*
*/
LEASEHOLD,
/**
* Zwangsversteigerung
*
*/
COMPULSORY_AUCTION,
/**
* Miete und Kauf
*
*/
RENT_AND_BUY;
public String value() {
return name();
}
public static CommercializationType fromValue(String v) {
return valueOf(v);
}
}
| {
"content_hash": "4538579d5eceffdb240b0c0bebad90e4",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 114,
"avg_line_length": 21.08433734939759,
"alnum_prop": 0.5777142857142857,
"repo_name": "ImmobilienScout24/restapi-java-sdk",
"id": "f87296d132abc2a892064d83e535d37b89f7328e",
"size": "1750",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/generated-sources/de/immobilienscout24/rest/schema/common/_1/CommercializationType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1551100"
},
{
"name": "Shell",
"bytes": "199"
},
{
"name": "XSLT",
"bytes": "617"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Grid with memory</title>
<link rel="stylesheet" type="text/css" href="../../../ext/ext-4.2.1/resources/ext-theme-classic/ext-theme-classic-all.css" />
<script type="text/javascript" src="../../../ext/ext-4.2.1/ext-all.js"></script>
<script src="main.js"></script>
</head>
<body>
</body>
</html> | {
"content_hash": "2813090d001ae43b57d61465397a609a",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 126,
"avg_line_length": 29.142857142857142,
"alnum_prop": 0.6348039215686274,
"repo_name": "MikhailTatsky/ExtJS-samples",
"id": "a007392df9863a8e116e9a7c212b07412bfa94e0",
"size": "408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/grid/memory/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6291327"
},
{
"name": "JavaScript",
"bytes": "9722669"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>relation-algebra: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.2 / relation-algebra - 1.7.4</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
relation-algebra
<small>
1.7.4
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-12 10:00:58 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-12 10:00:58 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
synopsis: "Relation Algebra and KAT in Coq"
maintainer: "Damien Pous <[email protected]>"
version: "1.7.4"
homepage: "http://perso.ens-lyon.fr/damien.pous/ra/"
dev-repo: "git+https://github.com/damien-pous/relation-algebra.git"
bug-reports: "https://github.com/damien-pous/relation-algebra/issues"
license: "LGPL-3.0-or-later"
depends: [
"ocaml"
"coq" {>= "8.11" & < "8.13~"}
]
depopts: [ "coq-mathcomp-ssreflect" "coq-aac-tactics" ]
build: [
["sh" "-exc" "./configure --%{coq-mathcomp-ssreflect:enable}%-ssr --%{coq-aac-tactics:enable}%-aac"]
[make "-j%{jobs}%"]
]
install: [make "install"]
tags: [
"keyword:relation algebra"
"keyword:Kleene algebra with tests"
"keyword:KAT"
"keyword:allegories"
"keyword:residuated structures"
"keyword:automata"
"keyword:regular expressions"
"keyword:matrices"
"category:Mathematics/Algebra"
"logpath:RelationAlgebra"
]
authors: [
"Damien Pous <[email protected]>"
"Christian Doczkal <[email protected]>"
]
url {
src:
"https://github.com/damien-pous/relation-algebra/archive/v1.7.4.tar.gz"
checksum: "md5=cae395ca1cb31bd4508992e1a7392d31"
}
</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-relation-algebra.1.7.4 coq.8.7.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.2).
The following dependencies couldn't be met:
- coq-relation-algebra -> coq >= 8.11 -> ocaml >= 4.09.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-relation-algebra.1.7.4</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": "c80b15ab57955e093576472d831531d8",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 40.469613259668506,
"alnum_prop": 0.5501706484641639,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "83eef7f4e7696c3ae1f1bf5cec1d554b2a1b75c6",
"size": "7350",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.2/relation-algebra/1.7.4.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/temples/monticello-utah#monticello-temple-766559" xml:lang="eng" locale="eng" status="publish">
<search-meta>
<uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">monticello-temple-766559</uri-title>
<source>monticello-temple-766559</source>
<publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
<media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
<publication value="ldsorg">LDS.org</publication>
<publication-date value="2012-04-09">2012-04-09</publication-date>
<title/>
<description/>
<collections>
<collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
<collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
<collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
</collections>
<subjects>
<subject>Monticello</subject>
<subject>Utah</subject>
<subject>Temple</subject>
<subject>Exterior</subject>
</subjects>
</search-meta>
<no-search>
<path>http://media.ldscdn.org/images/media-library/temples/monticello-utah/monticello-temple-766559-gallery.jpg</path>
<images>
<small its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">http://media.ldscdn.org/images/media-library/temples/monticello-utah/monticello-temple-766559-thumbnail.jpg</small>
</images>
<download-urls>
<download-url>
<label>Mobile</label>
<size>161 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/monticello-utah/monticello-temple-766559-mobile.jpg</path>
</download-url>
<download-url>
<label>Tablet</label>
<size>211 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/monticello-utah/monticello-temple-766559-tablet.jpg</path>
</download-url>
<download-url>
<label>Print</label>
<size>465 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/monticello-utah/monticello-temple-766559-print.jpg</path>
</download-url>
<download-url>
<label>Wallpaper</label>
<size>793 KB</size>
<path>http://media.ldscdn.org/images/media-library/temples/monticello-utah/monticello-temple-766559-wallpaper.jpg</path>
</download-url>
</download-urls>
</no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="monticello-temple-766559" locale="eng" uri="/media-library/images/temples/monticello-utah#monticello-temple-766559" status="publish" site="ldsorg" source="chq" words="123" tgp="0.4301"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:12.550235-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>
| {
"content_hash": "be89ad604ef703cb87b1c4e33257e49a",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 458,
"avg_line_length": 63.07692307692308,
"alnum_prop": 0.6332317073170731,
"repo_name": "freshie/ml-taxonomies",
"id": "982817f5d8859952d1e9e56d2b0115f218663dd1",
"size": "3280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "roxy/data/gospel-topical-explorer-v2/content/images/monticello-temple-766559.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4422"
},
{
"name": "CSS",
"bytes": "38665"
},
{
"name": "HTML",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "411651"
},
{
"name": "Ruby",
"bytes": "259121"
},
{
"name": "Shell",
"bytes": "7329"
},
{
"name": "XQuery",
"bytes": "857170"
},
{
"name": "XSLT",
"bytes": "13753"
}
],
"symlink_target": ""
} |
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {DraftsComponent} from 'app/task-list/drafts/drafts.component';
describe('DraftsComponent', () => {
let component: DraftsComponent;
let fixture: ComponentFixture<DraftsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [DraftsComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DraftsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"content_hash": "ed27a485a2227f9063322462b7fe991c",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 71,
"avg_line_length": 24.074074074074073,
"alnum_prop": 0.6738461538461539,
"repo_name": "SpineEventEngine/todo-list",
"id": "e54e8d11b47a5c4e70cefd616179d1d56efacc8c",
"size": "1661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/angular/test/app/task-list/drafts/drafts.component.spec.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "322"
},
{
"name": "CSS",
"bytes": "12277"
},
{
"name": "Dockerfile",
"bytes": "321"
},
{
"name": "HTML",
"bytes": "27467"
},
{
"name": "Java",
"bytes": "980919"
},
{
"name": "JavaScript",
"bytes": "11034"
},
{
"name": "Kotlin",
"bytes": "11686"
},
{
"name": "Shell",
"bytes": "1819"
},
{
"name": "TypeScript",
"bytes": "246265"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template operator<=</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../utilities.html#header.boost.log.utility.value_ref_hpp" title="Header <boost/log/utility/value_ref.hpp>">
<link rel="prev" href="operator___idp47175344.html" title="Function template operator<=">
<link rel="next" href="operator___idp47184304.html" title="Function template operator<=">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="operator___idp47175344.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.value_ref_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator___idp47184304.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.log.operator_=_idp47179824"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template operator<=</span></h2>
<p>boost::log::operator<=</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../utilities.html#header.boost.log.utility.value_ref_hpp" title="Header <boost/log/utility/value_ref.hpp>">boost/log/utility/value_ref.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> U<span class="special">,</span> <span class="keyword">typename</span> T<span class="special">,</span> <span class="keyword">typename</span> TagT<span class="special">></span>
<span class="keyword">bool</span> <span class="keyword">operator</span><span class="special"><=</span><span class="special">(</span><span class="identifier">U</span> <span class="keyword">const</span> <span class="special">&</span> left<span class="special">,</span> <a class="link" href="value_ref.html" title="Class template value_ref">value_ref</a><span class="special"><</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">TagT</span> <span class="special">></span> <span class="keyword">const</span> <span class="special">&</span> right<span class="special">)</span><span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007-2015 Andrey
Semashev<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>).
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="operator___idp47175344.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.value_ref_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator___idp47184304.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "4823d0e3783733efc253c07057412661",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 676,
"avg_line_length": 93.02222222222223,
"alnum_prop": 0.6586239847109412,
"repo_name": "huoxudong125/poedit",
"id": "b179337f4998980026428b8f8ac9a31efa051169",
"size": "4186",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "deps/boost/libs/log/doc/html/boost/log/operator___idp47179824.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "24909"
},
{
"name": "C++",
"bytes": "883320"
},
{
"name": "Inno Setup",
"bytes": "10952"
},
{
"name": "Objective-C",
"bytes": "4458"
},
{
"name": "Objective-C++",
"bytes": "14760"
},
{
"name": "Python",
"bytes": "3040"
},
{
"name": "Ruby",
"bytes": "232"
},
{
"name": "Shell",
"bytes": "10489"
}
],
"symlink_target": ""
} |
Activity count algorithm is implemented to convert the raw acceleration data to activity count. The activity count results are comparable to those in Actigraph software.
Usage
-----
```ShellSession
[Hadoop Path] [jar] [Jar File Name] [Class Path for Algorithm in Jar] [-c] [Cross Participants] [-f] [File System] [-j] [Runnable Jar File Path] [-a] [Class Path for Algorithm in Jar] [-i] [Data Input Path]
```
* [Local directory to jar file]: The local directory for jar file
* Example: output/SpadesAnalytics.jar (here SpadesAnalytics.jar is a runnable jar file in the local computer)
* [com.qmedic.spades.task.SpadesSubmit]: the class to submit the job to EMR
* [s3n directory to jar file]: The cloud directory for jar file
* Example: spades-data/development/user/SpadesAnalytics.jar (SpadesAnalytics.jar is stored in the directory “spades-data/development/user” of s3)
* [class name in jar file of s3n]: The runnable class in the jar file in S3
* Example: com.qmedic.spades.task.examples.mapreduce.ActivityCount.ActivityCountClean(The class to run for converting raw acceleration data to activity count)
* [data input path]: Cloud directory for source data
* Note: Its format will be discussed in the section “Data Input Format”
* Example: spades-data/development/stanford/2/StanfordStudyYouth2/1/MasterSynced/*
* [key value assigned by AWS]: Key value assigned by AWS
* Note: 20 alphabeta
* Example: "yourAccessKey"
* [secret value assigned by AWS]: secret value assigned by AWS
* Note: 40 char
* Example: "yourSecretKey"
* [parameters to be passed to runnable class]: parameters to be passed to runnable class
* Note: Its format will be discussed in the section “Parameter Input Format”
Input
-----
In our framework, the input format for processing data is restricted to the following, a future work item would be to extend it and allow for a variety of flexible formats…
* Input Path Folder Format
* Must be terminated with a wild card /*
* The path consists of the following required entries:
* Bucket Name: (alphanumeric, ‘-’)... e.g. spade-data
* Release Type: development, production
* Institution: Stanford
* Study ID: numeric value for the user within the institution
* Study Name: StanfordStudyYouth2
* Participant ID: acceptable values include (can also be specified as a wild card *)
* Data source: Alphanumeric + ‘-’...e.g. MasterSynced
* Optional components of the path that follow include:
* Year: 4 character representation
* Month: 2 character representation that goes from 01 to 12
* Day: 2 character representation that goes from 01 to 31
* Hour: 2 character representation that goes from 00 to 23
* Allowed paths include the following formats:
spades-data/development/stanford/2/StanfordStudyYouth2/1/MasterSynced/*
Parameter Input
----------------------
The parameter input format for passing parameters to runnable class is restricted to the following, a future work item would be extended and allow for a variety of flexible formats.
**Format**
```ShellSession
-c [false] -f [s3n] -j [s3n directory to jar file] -a [class name in jar file of s3n] -i [data input path]
```
**Example**
```ShellSession
-c false -f s3n -j spades-data/development/user/SpadesAnalytics.jar -a com.qmedic.spades.task.examples.mapreduce.ActivityCount.ActivityCountClean -i spades-data/development/stanford/2/StanfordStudyYouth2/1/MasterSynced/*
```
* [false]: Input value for [-c] command which doesn’t allow cross participants
* Example: false/true
* [s3n]: Input value for [-f] command which runs in s3n file system
* Example: s3n/hdfs
* [s3n directory to jar file]: Input jar directory in s3n for [-j] command which specifies the runnable jar file
* Example: spades-data/development/user/SpadesAnalytics.jar
* [class name in jar file of s3n]: Input s3 class for [-a] command which specifies the runnable class
* Example: com.qmedic.spades.task.examples.mapreduce.ActivityCount.ActivityCountClean
* [data input path]: Input source data for [-i] command which specifies the source data
* Example: spades-data/development/stanford/2/StanfordStudyYouth2/1/MasterSynced/*
Command Line Example
--------------------
```ShellSession
java -cp output/SpadesAnalytics.jar com.qmedic.spades.task.SpadesSubmit -cluster MapReduce -mode Once -speed 32x -filesystem s3n -jar spades-data/development/user/SpadesAnalytics.jar -classpath com.qmedic.spades.task.examples.mapreduce.ActivityCount.ActivityCountClean -input spades-data/development/stanford/2/StanfordStudyYouth2/1/MasterSynced/* -key "yourAccessKey" -secret "yourSecretKey" -duration 4 -cost 20 -p "-c false -f s3n -j spades-data/development/user/SpadesAnalytics.jar -a com.qmedic.spades.task.examples.mapreduce.ActivityCount.ActivityCountClean -i spades-data/development/stanford/2/StanfordStudyYouth2/1/MasterSynced/*
```
Output
------
Typically the feature data file will be stored in the metadata directories and will include processed data that can be recomputed from the raw data. The structure of the filename is:
```ShellSession
[ALGORITHM].[FEATURE NAME].[YYYY]-[MM]-[DD]-[hh]-[mm]-[ss]-[mmm]-[P/M][hhmm].csv.gz
```
* [ALGORITHM]: Prefix of the file name
* [FEATURE NAME]: Feature name
* Example: MetaData-ActivityCountClean-2015-10-29-10-50-21-021
**Output Content**
For example, the first two lines in the activity count.csv file could look like this:
```ShellSession
HEADER_TIME_STAMP, X_ACTIVITY_COUNT,Y_ACTIVITY_COUNT,Z_ACTIVITY_COUNT,VM_ACTIVITY_COUNT
2013/11/20 00:00:00.000, 0, 0, 0, 0
```
* [HEADER_TIME_STAMP]: The start timestamp for activity count (here activity count is calculated in 1 minute)
* [X_ACTIVITY_COUNT]: Value of activity count based on the x-axis acceleration data
* [Y_ACTIVITY_COUNT]: Value of activity count based on the y-axis acceleration data
* [Z_ACTIVITY_COUNT]: Value of activity count based on the z-axis acceleration data
* [VM_ACTIVITY_COUNT]: Vector Magnitude of x,y,z activity count
* Note: VM_ACTIVITY_COUNT = sqrt(X_ACTIVITY_COUNT^2 + Y_ACTIVITY_COUNT^2 + Z_ACTIVITY_COUNT^2)
Notes
-----
Here it is assumed that the accelerometer has three axis accelerations.
| {
"content_hash": "3d2fa9cd22092ec78f52ba913e700b51",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 640,
"avg_line_length": 58.68867924528302,
"alnum_prop": 0.7476289985532872,
"repo_name": "SPADES-PUBLIC/spadesAnalytics-activityCount",
"id": "abf54e677260068dddfaf0384ba554b2883f3930",
"size": "6277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
define([
'jquery',
'underscore',
'scripts/models/events/event'
], function($, _, Event) {
return Event.extend({
//
// attributes
//
event_type: undefined,
project_uid: undefined,
project_full_name: undefined,
project_short_name: undefined
});
}); | {
"content_hash": "4cc010e16fccc2b5ea85cdfc365a7295",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 31,
"avg_line_length": 13.5,
"alnum_prop": 0.6370370370370371,
"repo_name": "OWASP/open-swamp",
"id": "c0b9b750e4905f3df0d7b76fdb994a9ce3f33646",
"size": "1160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "registry-web-server/var/www/html/scripts/models/events/project-event.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "767"
},
{
"name": "C",
"bytes": "35196"
},
{
"name": "CSS",
"bytes": "273103"
},
{
"name": "HTML",
"bytes": "218109"
},
{
"name": "JavaScript",
"bytes": "2487314"
},
{
"name": "Makefile",
"bytes": "5684"
},
{
"name": "PHP",
"bytes": "2269165"
},
{
"name": "PLSQL",
"bytes": "28817"
},
{
"name": "Perl",
"bytes": "834173"
},
{
"name": "Ruby",
"bytes": "34"
},
{
"name": "SQLPL",
"bytes": "370145"
},
{
"name": "Shell",
"bytes": "5523"
},
{
"name": "Smarty",
"bytes": "351236"
},
{
"name": "XSLT",
"bytes": "213693"
}
],
"symlink_target": ""
} |
<img src="/common/gctlogo.png?raw=true" width="350px" height="350px" hspace="70">
[](https://github.com/thrasher-corp/gocryptotrader/actions/workflows/tests.yml)
[](https://github.com/thrasher-corp/gocryptotrader/blob/master/LICENSE)
[](https://godoc.org/github.com/thrasher-corp/gocryptotrader/engine/websocketroutine_manager)
[](http://codecov.io/github/thrasher-corp/gocryptotrader?branch=master)
[](https://goreportcard.com/report/github.com/thrasher-corp/gocryptotrader)
This websocketroutine_manager package is part of the GoCryptoTrader codebase.
## This is still in active development
You can track ideas, planned features and what's in progress on this Trello board: [https://trello.com/b/ZAhMhpOy/gocryptotrader](https://trello.com/b/ZAhMhpOy/gocryptotrader).
Join our slack to discuss all things related to GoCryptoTrader! [GoCryptoTrader Slack](https://join.slack.com/t/gocryptotrader/shared_invite/enQtNTQ5NDAxMjA2Mjc5LTc5ZDE1ZTNiOGM3ZGMyMmY1NTAxYWZhODE0MWM5N2JlZDk1NDU0YTViYzk4NTk3OTRiMDQzNGQ1YTc4YmRlMTk)
## Current Features for Websocketroutine manager
+ The websocket routine manager subsystem is used process websocket data in a unified manner across enabled exchanges with websocket support
+ It can help process orders to the order manager subsystem when it receives new data
+ Logs output of ticker and orderbook updates
+ The websocket routine manager subsystem can be enabled or disabled via runtime command `-websocketroutine=false` defaulting to true
+ Logs can be customised to display values the config value `fiatDisplayCurrency` under `currencyConfig`
### Please click GoDocs chevron above to view current GoDoc information for this package
## Contribution
Please feel free to submit any pull requests or suggest any desired features to be added.
When submitting a PR, please abide by our coding guidelines:
+ Code must adhere to the official Go [formatting](https://golang.org/doc/effective_go.html#formatting) guidelines (i.e. uses [gofmt](https://golang.org/cmd/gofmt/)).
+ Code must be documented adhering to the official Go [commentary](https://golang.org/doc/effective_go.html#commentary) guidelines.
+ Code must adhere to our [coding style](https://github.com/thrasher-corp/gocryptotrader/blob/master/doc/coding_style.md).
+ Pull requests need to be based on and opened against the `master` branch.
## Donations
<img src="https://github.com/thrasher-corp/gocryptotrader/blob/master/web/src/assets/donate.png?raw=true" hspace="70">
If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:
***bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc***
| {
"content_hash": "5914872d383ab2cb37fa73e66f249084",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 249,
"avg_line_length": 68.1086956521739,
"alnum_prop": 0.8014682413022662,
"repo_name": "thrasher-/gocryptotrader",
"id": "de4585e296e985d563358a8b0227420d338cd23b",
"size": "3184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/websocketroutine_manager.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "409"
},
{
"name": "CSS",
"bytes": "14073"
},
{
"name": "Dockerfile",
"bytes": "1139"
},
{
"name": "Go",
"bytes": "7687592"
},
{
"name": "HTML",
"bytes": "35213"
},
{
"name": "JavaScript",
"bytes": "10542"
},
{
"name": "Makefile",
"bytes": "1762"
},
{
"name": "PowerShell",
"bytes": "627"
},
{
"name": "SCSS",
"bytes": "20001"
},
{
"name": "Shell",
"bytes": "726"
},
{
"name": "Smarty",
"bytes": "509"
},
{
"name": "TypeScript",
"bytes": "90056"
}
],
"symlink_target": ""
} |
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
user: null,
meta: null,
permit: function (privileges) {
return true
}
},
mutations: {
user: function (state, payload) {
state.user = payload
},
meta: function (state, payload) {
state.meta = payload
}
}
})
export default store
| {
"content_hash": "220581220614719bfeeeb0a7989ff708",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 37,
"avg_line_length": 16.166666666666668,
"alnum_prop": 0.5876288659793815,
"repo_name": "easorucoa94/ayuteca",
"id": "7fd9b712537611c09bb4b4b4da6624de1b2d7156",
"size": "388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/store.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2764"
},
{
"name": "HTML",
"bytes": "1143"
},
{
"name": "JavaScript",
"bytes": "23050"
},
{
"name": "PHP",
"bytes": "37281"
},
{
"name": "Vue",
"bytes": "45443"
}
],
"symlink_target": ""
} |
import Route from '@ember/routing/route';
export default Route.extend({
model: function(params) {
var event = this.modelFor('event');
return event.getLeg(params['leg_id']).then(function(leg) {
if (!leg) {
this.transitionTo('event.legs');
}
return leg;
});
}
});
| {
"content_hash": "204fd873b3ccb3f31c1d92bb93c4cb26",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 62,
"avg_line_length": 21.4,
"alnum_prop": 0.5669781931464174,
"repo_name": "rasifix/olana",
"id": "3f981f06493222dd56f4d906f431ef7b54b80526",
"size": "321",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/routes/leg.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5761"
},
{
"name": "HTML",
"bytes": "22068"
},
{
"name": "JavaScript",
"bytes": "92527"
},
{
"name": "Shell",
"bytes": "156"
}
],
"symlink_target": ""
} |
namespace base {
File::Info::Info() = default;
File::Info::~Info() = default;
File::File() = default;
#if !defined(OS_NACL)
File::File(const FilePath& path, uint32_t flags) : error_details_(FILE_OK) {
Initialize(path, flags);
}
#endif
File::File(ScopedPlatformFile platform_file)
: File(std::move(platform_file), false) {}
File::File(PlatformFile platform_file) : File(platform_file, false) {}
File::File(ScopedPlatformFile platform_file, bool async)
: file_(std::move(platform_file)), error_details_(FILE_OK), async_(async) {
#if defined(OS_POSIX) || defined(OS_FUCHSIA)
DCHECK_GE(file_.get(), -1);
#endif
}
File::File(PlatformFile platform_file, bool async)
: file_(platform_file),
error_details_(FILE_OK),
async_(async) {
#if defined(OS_POSIX) || defined(OS_FUCHSIA)
DCHECK_GE(platform_file, -1);
#endif
}
File::File(Error error_details) : error_details_(error_details) {}
File::File(File&& other)
: file_(other.TakePlatformFile()),
tracing_path_(other.tracing_path_),
error_details_(other.error_details()),
created_(other.created()),
async_(other.async_) {}
File::~File() {
// Go through the AssertIOAllowed logic.
Close();
}
File& File::operator=(File&& other) {
Close();
SetPlatformFile(other.TakePlatformFile());
tracing_path_ = other.tracing_path_;
error_details_ = other.error_details();
created_ = other.created();
async_ = other.async_;
return *this;
}
#if !defined(OS_NACL)
void File::Initialize(const FilePath& path, uint32_t flags) {
if (path.ReferencesParent()) {
#if defined(OS_WIN)
::SetLastError(ERROR_ACCESS_DENIED);
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
errno = EACCES;
#else
#error Unsupported platform
#endif
error_details_ = FILE_ERROR_ACCESS_DENIED;
return;
}
if (FileTracing::IsCategoryEnabled())
tracing_path_ = path;
SCOPED_FILE_TRACE("Initialize");
DoInitialize(path, flags);
}
#endif
bool File::ReadAndCheck(int64_t offset, span<uint8_t> data) {
int size = checked_cast<int>(data.size());
return Read(offset, reinterpret_cast<char*>(data.data()), size) == size;
}
bool File::ReadAtCurrentPosAndCheck(span<uint8_t> data) {
int size = checked_cast<int>(data.size());
return ReadAtCurrentPos(reinterpret_cast<char*>(data.data()), size) == size;
}
bool File::WriteAndCheck(int64_t offset, span<const uint8_t> data) {
int size = checked_cast<int>(data.size());
return Write(offset, reinterpret_cast<const char*>(data.data()), size) ==
size;
}
bool File::WriteAtCurrentPosAndCheck(span<const uint8_t> data) {
int size = checked_cast<int>(data.size());
return WriteAtCurrentPos(reinterpret_cast<const char*>(data.data()), size) ==
size;
}
// static
std::string File::ErrorToString(Error error) {
switch (error) {
case FILE_OK:
return "FILE_OK";
case FILE_ERROR_FAILED:
return "FILE_ERROR_FAILED";
case FILE_ERROR_IN_USE:
return "FILE_ERROR_IN_USE";
case FILE_ERROR_EXISTS:
return "FILE_ERROR_EXISTS";
case FILE_ERROR_NOT_FOUND:
return "FILE_ERROR_NOT_FOUND";
case FILE_ERROR_ACCESS_DENIED:
return "FILE_ERROR_ACCESS_DENIED";
case FILE_ERROR_TOO_MANY_OPENED:
return "FILE_ERROR_TOO_MANY_OPENED";
case FILE_ERROR_NO_MEMORY:
return "FILE_ERROR_NO_MEMORY";
case FILE_ERROR_NO_SPACE:
return "FILE_ERROR_NO_SPACE";
case FILE_ERROR_NOT_A_DIRECTORY:
return "FILE_ERROR_NOT_A_DIRECTORY";
case FILE_ERROR_INVALID_OPERATION:
return "FILE_ERROR_INVALID_OPERATION";
case FILE_ERROR_SECURITY:
return "FILE_ERROR_SECURITY";
case FILE_ERROR_ABORT:
return "FILE_ERROR_ABORT";
case FILE_ERROR_NOT_A_FILE:
return "FILE_ERROR_NOT_A_FILE";
case FILE_ERROR_NOT_EMPTY:
return "FILE_ERROR_NOT_EMPTY";
case FILE_ERROR_INVALID_URL:
return "FILE_ERROR_INVALID_URL";
case FILE_ERROR_IO:
return "FILE_ERROR_IO";
case FILE_ERROR_MAX:
break;
}
NOTREACHED();
return "";
}
} // namespace base
| {
"content_hash": "00ef9336d03a920a0c4ec96270400248",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 79,
"avg_line_length": 27.482993197278912,
"alnum_prop": 0.6653465346534654,
"repo_name": "endlessm/chromium-browser",
"id": "22057eddefc3f94ce0e456a4f9c0913bf4eb4a1d",
"size": "4610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "base/files/file.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([GSKAppDelegate class]));
}
}
| {
"content_hash": "60f41ffa35f4fbd8081d142940441d37",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 93,
"avg_line_length": 26.833333333333332,
"alnum_prop": 0.6645962732919255,
"repo_name": "gskbyte/UICollectionView-SectionBackground",
"id": "26bbd0cc26eb511dfd67e6f6e0ba14684eb79193",
"size": "358",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sectionBackground/main.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "13305"
}
],
"symlink_target": ""
} |
package com.opera.core.systems.scope.services.desktop;
import com.opera.core.systems.QuickMenu;
import com.opera.core.systems.QuickMenuItem;
import com.opera.core.systems.QuickWidget;
import com.opera.core.systems.QuickWindow;
import com.opera.core.systems.scope.Service;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType;
import java.util.List;
public interface DesktopWindowManager extends Service {
static final String SERVICE_NAME = "desktop-window-manager";
/**
* Does initialization necessary to set up the service.
*/
void init();
/**
* Gets id of active window.
*
* @return id of active window
*/
int getActiveQuickWindowId();
/**
* Gets number of open windows.
*
* @return number of open windows
*/
int getOpenQuickWindowCount();
/**
* Gets list of all QuickWidgets in the window.
*
* @param windowId id of window
* @return list of QuickWidgets in the window given by id id
*/
List<QuickWidget> getQuickWidgetList(int windowId);
/**
* Gets window id of window with the given name.
*
* @param name window name
* @return id of window with the given name
*/
int getQuickWindowID(String name);
/**
* Gets a list of all open windows.
*
* @return list of all open windows
*/
List<QuickWindow> getQuickWindowList();
/**
* Gets the name of the window with windowId.
*
* @param windowId id of window
* @return name of the window
*/
String getQuickWindowName(int windowId);
/**
* Gets a QuickWidget based on a specific property.
*
* @param type what type
* @param windowId window id of the window containing the widget
* @param property property specified for the search
* @param value value of property given
* @return QuickWidget matching the property, or null if no such widget
*/
QuickWidget getQuickWidget(QuickWidgetType type, int windowId, QuickWidgetSearchType property,
String value);
/**
* Gets the quick widget in a specified window based on a specific property and its parent widgets
* name.
*
* @param type what type
* @param windowId window id of the window containing the widget
* @param property property specified for the search
* @param value value of property given
* @param parentName Name of the widgets parent widget
* @return QuickWidget matching the property, or null if no such widget
*/
QuickWidget getQuickWidget(QuickWidgetType type, int windowId, QuickWidgetSearchType property,
String value, String parentName);
/**
* Gets the quick widget based on its position.
*
* @param type what type
* @param windowId window id of the window containing the widget
* @param row row of the widget
* @param column column of the widget
* @return QuickWidget matching the parameters, or null if no such widget
*/
QuickWidget getQuickWidgetByPos(QuickWidgetType type, int windowId, int row, int column);
/**
* Gets the quick widget based on its position and its parent widgets name.
*
* @param type what type
* @param windowId window id of the window containing the widget
* @param row row of the widget
* @param column column of the widget
* @param parentName Name of the widgets parent widget
* @return QuickWidget matching the parameters, or null if no such widget
*/
QuickWidget getQuickWidgetByPos(QuickWidgetType type, int windowId, int row, int column,
String parentName);
/**
* Gets the quick window based on a specific property.
*
* @param property - property to search by
* @param value - value of property given
* @return QuickWindow matching the parameters, or null if no such widget
*/
QuickWindow getQuickWindow(QuickWidgetSearchType property, String value);
/**
* Gets the quick window with the given window id.
*
* @param windowId id of the window
* @return QuickWindow with id windowId, if any, else null.
*/
QuickWindow getQuickWindowById(int windowId);
/**
* Gets the window with name name.
*
* @param name window name
* @return QuickWindow
*/
QuickWindow getQuickWindowByName(String name);
void pressQuickMenuItem(String menuItemText, boolean popMenu);
/**
* Gets the menu with name name.
*
* @param menuName the menu's name
* @return QuickMenu
*/
QuickMenu getQuickMenu(String menuName);
/**
* Gets the menu with the action specified, if any.
*
* @param action of the menu item to search for
* @return QuickMenuItem with action, or null if the item doesn't exist
*/
QuickMenuItem getQuickMenuItemByAction(String action);
/**
* Gets the menu with the text specified, if any.
*
* @param text of the menu item to search for
* @return QuickMenuItem with the given text, or null if no such item exists
*/
QuickMenuItem getQuickMenuItemByText(String text);
/**
* Gets the menu item with the given position in the menu with name menuName.
*
* @param row the row of the item, counting from zero, and including both normal items and
* menu separators
* @param menuName name of the menu to lookup the menu item in
* @return QuickMenuItem, or null if the item doesn't exist
*/
QuickMenuItem getQuickMenuItemByPosition(int row, String menuName);
/**
* Gets the menu item with the given accelerator key in the menu with name menuName.
*
* @param key the shortcut key of the menu item to search for (the character that's
* underlined/marked in the menu item text)
* @param menuName name of the menu of the menu item
* @return QuickMenuItem or null if the item doesn't exist
*/
QuickMenuItem getQuickMenuItemByAccKey(String key, String menuName);
/**
* Gets the Menu item with the given shortcut.
*
* @param shortcut string representation of the shortcut of the menuitem (i.e. "Ctrl+O")
* @return QuickMenuItem, or null if the item doesnt exist
*/
QuickMenuItem getQuickMenuItemByShortcut(String shortcut);
/**
* Gets the menu item that opens the sub-menu.
*
* @param submenu the name of the sub-menu the menu item opens when its selected/clicked
* @return QuickMenuItem or null if the item doesn't exist
*/
QuickMenuItem getQuickMenuItemBySubmenu(String submenu);
/**
* @return list of all menus that are open (including menu bar(s))
*/
List<QuickMenu> getQuickMenuList();
/**
* @return list containing all menu items in open menus (including menu bar(s))
*/
List<QuickMenuItem> getQuickMenuItemList();
/**
* @param name name of the item. This is either the name of the action the item executes when
* selected The name of the sub-menu the item opens when selected "Separator" for
* items that are separators
* @return the menu item
*/
QuickMenuItem getQuickMenuItemByName(String name);
/**
* @param menuName name of the menu (as specified in standard_menu.ini)
* @param windowId id of the window the menu is attached to (note: only makes sense for menu bar)
* @return QuickMenu with name menuName in windowId if it exists, else null
*/
QuickMenu getQuickMenu(String menuName, int windowId);
/**
* @param name Name of the menuItem
* @param window_id windowId of the window the menu of the item is in (note: only makes sense for
* menu bar items)
* @return the menu item
*/
QuickMenuItem getQuickMenuItemByName(String name, int window_id);
} | {
"content_hash": "1786a4ef9b7b9c318f09ddf1730efecc",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 100,
"avg_line_length": 32.58577405857741,
"alnum_prop": 0.6896507447354905,
"repo_name": "operasoftware/operaprestodriver",
"id": "487178c48f2fb2f33980884976ede5a0fde6a1b6",
"size": "8358",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/opera/core/systems/scope/services/desktop/DesktopWindowManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1617538"
},
{
"name": "JavaScript",
"bytes": "201"
},
{
"name": "Python",
"bytes": "6021"
}
],
"symlink_target": ""
} |
<?php
namespace Payment\Common\Weixin\Data;
use Payment\Utils\StrUtil;
/**
* Class BackAppChargeData
*
* @property string $device_info 设备号
* @property string $trade_type 交易类型
* @property string $prepay_id 预支付交易会话标识
*
* @package Payment\Common\Weixin\Data
* anthor helei
*
* @link https://www.gitbook.com/book/helei112g1/payment-sdk/details
* @link https://helei112g.github.io/
*/
class BackAppChargeData extends WxBaseData
{
protected function buildData()
{
$this->retData = [
'appid' => $this->appId,
'partnerid' => $this->mchId,
'prepayid' => $this->prepay_id,
'package' => 'Sign=WXPay',
'noncestr' => StrUtil::getNonceStr(),
'timestamp' => time(),
];
}
protected function checkDataParam()
{
// 对于返回数据不做检查检查
}
}
| {
"content_hash": "fa5db6637a628a9b636e1e0e7a91afb5",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 73,
"avg_line_length": 22.86842105263158,
"alnum_prop": 0.5868814729574223,
"repo_name": "kitlabs-cn/KitPHP",
"id": "7b5e9aac8f8d8119c17a11e3b265abc4a69d697c",
"size": "925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/riverslei/payment/src/Common/Weixin/Data/BackAppChargeData.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3687"
},
{
"name": "CSS",
"bytes": "72750"
},
{
"name": "HTML",
"bytes": "302847"
},
{
"name": "JavaScript",
"bytes": "516430"
},
{
"name": "PHP",
"bytes": "321553"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.