text stringlengths 2 1.04M | meta dict |
|---|---|
require 'eventmachine'
require 'faye/websocket'
require 'MrMurano/http'
require 'MrMurano/verbosing'
module MrMurano
module Logs
class Follow
def run_event_loop(sol, &block)
# block_given?
@message_handler = block
EM.run do
uri = ws_logs_uri(sol)
MrMurano::Http.curldebug_log(uri)
run_client_websocket(uri)
end
end
def ws_logs_uri(sol)
protocol = ($cfg['net.protocol'] == 'https') && 'wss' || 'ws'
# There are multiple endpoints: api:1/log/<sid>/[events|all|logs]
# FIXME/2017-12-12 (landonb): Which endpoint do we want?
# /events, or /all, or /logs??
uri = [
protocol + ':/', $cfg['net.host'], 'api:1', 'log', sol.api_id, 'logs',
].join('/')
uri += %(?token=#{sol.token})
uri += %(&query={})
uri += %(&projection={})
# FIXME: (landonb): Would we want to add limit=?
#uri += %(&limit=20)
uri
end
def run_client_websocket(uri)
protocols = nil
@ws = Faye::WebSocket::Client.new(uri, protocols, ping: 1)
# (landonb): The ws.on method expects a class instance object. If we
# were to pass a plain procedural method (i.e., a normal method defined
# outside of a class), then Faye calls the function back with the first
# parameter -- event -- as the 'self' of the callback! Furthermore, we
# have to explicitly set `public :method`, which I didn't even think
# you could do outside of a class! Ruby is so weird sometimes.
@ws.on :open, &method(:ws_on_open)
@ws.on :message, &method(:ws_on_message)
@ws.on :close, &method(:ws_on_close)
end
def ws_on_open(event)
MrMurano::Verbose.verbose("WebSocket opened: #{event}")
end
def ws_on_message(event)
event.data.split("\n").each do |msg|
if @message_handler
@message_handler.call(msg)
else
puts "message: #{msg}"
end
end
$stdout.flush
end
def ws_on_close(event)
# Returns:
# event.code # From RFC
# event.reason # Not always set
# For a list of close event codes, see:
# https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
# https://www.iana.org/assignments/websocket/websocket.xml#close-code-number
# https://tools.ietf.org/html/rfc6455#section-7.4.1
@ws = nil
MrMurano::Verbose.warning("WebSocket closed [#{event.code}]")
EM.stop_event_loop
end
end
end
end
| {
"content_hash": "1c8bf1d0f4c7f8b77434dea11450c9c8",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 86,
"avg_line_length": 33.0125,
"alnum_prop": 0.5622870124952669,
"repo_name": "exosite/MrMurano",
"id": "dd525b641e91e0b21a8bf0560ea6f788556694e4",
"size": "2859",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/MrMurano/Logs.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3930"
},
{
"name": "Inno Setup",
"bytes": "1639"
},
{
"name": "Ruby",
"bytes": "354068"
}
],
"symlink_target": ""
} |
package com.devicehive.json.adapters;
import com.devicehive.configuration.Messages;
import com.devicehive.model.enums.UserRole;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
public class UserRoleAdapter extends TypeAdapter<UserRole> {
@Override
public void write(JsonWriter out, UserRole value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value.getValue());
}
}
@Override
public UserRole read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
if (jsonToken == JsonToken.NULL) {
in.nextNull();
return null;
} else {
try {
return UserRole.values()[in.nextInt()];
} catch (RuntimeException e) {
throw new IOException(Messages.INVALID_USER_ROLE, e);
}
}
}
}
| {
"content_hash": "65fb672b7839895efe77ca30be1fbe25",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 74,
"avg_line_length": 28.405405405405407,
"alnum_prop": 0.6241674595623216,
"repo_name": "lekster/devicehive-java-server",
"id": "a9f7dceb940e43d4c7da8fb8550ac15474f38bab",
"size": "1051",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "src/main/java/com/devicehive/json/adapters/UserRoleAdapter.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23637"
},
{
"name": "HTML",
"bytes": "23344"
},
{
"name": "Java",
"bytes": "1021826"
},
{
"name": "JavaScript",
"bytes": "2025"
},
{
"name": "PLpgSQL",
"bytes": "7978"
}
],
"symlink_target": ""
} |
from hypr import Provider, request, filter
import json
class BaseProvider(Provider):
def get(self):
return request.m_filters
class Provider0(BaseProvider):
propagation_rules = {
'rule0': (BaseProvider, '/bar')
}
@filter
def my_filter(self):
return 'ok'
class TestFilter:
providers = {
Provider0: '/foo',
}
def test_sanity(self, app):
with app.test_client() as client:
resp = client.get('/foo')
assert resp.status == 200
assert json.loads(resp.text) == {}
def test_filter_is_applied(self, app):
with app.test_client() as client:
resp = client.get('/foo/bar')
assert resp.status == 200
assert json.loads(resp.text) == {'my_filter': 'ok'}
| {
"content_hash": "d98121e5de458678cb5fa01c8da31097",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 63,
"avg_line_length": 21.157894736842106,
"alnum_prop": 0.5671641791044776,
"repo_name": "project-hypr/hypr",
"id": "2e3c7cd3e88353ac73a3793a88b1537cccf41a8b",
"size": "804",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/security/filters/test_simple_filter.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "144944"
}
],
"symlink_target": ""
} |
layout: page
title: "Michelle Nichol Belleau"
comments: true
description: "blanks"
keywords: "Michelle Nichol Belleau,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
font-family: "Bebas Neue";
src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
}
h1.Bebas {
font-family: "Bebas Neue", Verdana, Tahoma;
}
</style>
</head>
#### TEACHING INFORMATION
**College**: School of Education
**Classes taught**: EDUC 1580
#### EDUC 1580: Energy and Interactions
**Terms taught**: Fall 2014, Spring 2015, Spring 2016, Fall 2016
**Instructor rating**: 5.75
**Standard deviation in instructor rating**: 0.27
**Average grade** (4.0 scale): 3.29
**Standard deviation in grades** (4.0 scale): 0.55
**Average workload** (raw): 2.37
**Standard deviation in workload** (raw): 0.14
| {
"content_hash": "3d8c6e8b48f5d2b895ce7f9df4c81830",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 100,
"avg_line_length": 25.904761904761905,
"alnum_prop": 0.6966911764705882,
"repo_name": "nikhilrajaram/nikhilrajaram.github.io",
"id": "aa0308f94bdd963ff5a92935a3069e4b35974014",
"size": "1092",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "instructors/Michelle_Nichol_Belleau.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15727"
},
{
"name": "HTML",
"bytes": "48339721"
},
{
"name": "Python",
"bytes": "9692"
},
{
"name": "Ruby",
"bytes": "5940"
}
],
"symlink_target": ""
} |
package voldemort.store.readonly.mr;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.jdom.JDOMException;
import voldemort.cluster.Cluster;
import voldemort.server.VoldemortConfig;
import voldemort.store.StoreDefinition;
import voldemort.store.readonly.checksum.CheckSum.CheckSumType;
import voldemort.utils.CmdUtils;
import voldemort.utils.ReflectUtils;
import voldemort.xml.ClusterMapper;
import voldemort.xml.StoreDefinitionsMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableCollection;
/**
* A runner class to facitilate the launching of HadoopStoreBuilder from the
* command-line.
*
*
*/
@SuppressWarnings("deprecation")
public class HadoopStoreJobRunner extends Configured implements Tool {
private static void printUsage(OptionParser parser, Exception e) throws IOException {
System.err.println("Usage: $VOLDEMORT_HOME/bin/hadoop-build-readonly-store.sh \\");
System.err.println(" [genericOptions] [options]\n");
System.err.println("Options:");
parser.printHelpOn(System.err);
System.err.println();
ToolRunner.printGenericCommandUsage(System.err);
if(e != null) {
System.err.println("\nAn exception ocurred:");
e.printStackTrace(System.err);
}
}
private static OptionParser configureParser() {
OptionParser parser = new OptionParser();
parser.accepts("input", "input file(s) for the Map step.").withRequiredArg();
parser.accepts("tmpdir", "output directory for the Reduce step.").withRequiredArg();
parser.accepts("output", "final output directory for store.").withRequiredArg();
parser.accepts("mapper", "store builder mapper class.").withRequiredArg();
parser.accepts("cluster", "local path to cluster.xml.").withRequiredArg();
parser.accepts("storedefinitions", "local path to stores.xml.").withRequiredArg();
parser.accepts("storename", "store name from store definition.").withRequiredArg();
parser.accepts("chunksize", "maximum size of a chunk in bytes.").withRequiredArg();
parser.accepts("inputformat", "JavaClassName (default=text).").withRequiredArg();
parser.accepts("jar", "mapper class jar if not in $HADOOP_CLASSPATH.").withRequiredArg();
parser.accepts("checksum", "enable checksum using md5, adler32, crc32").withRequiredArg();
parser.accepts("force-overwrite", "deletes final output directory if present.");
parser.accepts("save-keys", "save the keys in the data file");
parser.accepts("reducer-per-bucket", "run single reducer per bucket");
parser.accepts("num-chunks", "number of chunks (if set, takes precedence over chunksize)");
parser.accepts("is-avro", "is the data format avro?");
parser.accepts("help", "print usage information");
return parser;
}
@SuppressWarnings("unchecked")
public int run(String[] args) throws Exception {
OptionParser parser = configureParser();
OptionSet options = parser.parse(args);
if(options.has("help")) {
printUsage(parser, null);
System.exit(0);
}
Set<String> missing = CmdUtils.missing(options,
"input",
"output",
"mapper",
"cluster",
"storedefinitions",
"storename",
"chunksize",
"tmpdir");
if(missing.size() > 0) {
System.err.println("Missing required arguments: " + Joiner.on(", ").join(missing)
+ "\n");
printUsage(parser, null);
System.exit(1);
}
File clusterFile = new File((String) options.valueOf("cluster"));
Cluster cluster = new ClusterMapper().readCluster(new BufferedReader(new FileReader(clusterFile)));
File storeDefFile = new File((String) options.valueOf("storedefinitions"));
String storeName = (String) options.valueOf("storename");
List<StoreDefinition> stores;
stores = new StoreDefinitionsMapper().readStoreList(new BufferedReader(new FileReader(storeDefFile)));
StoreDefinition storeDef = null;
for(StoreDefinition def: stores) {
if(def.getName().equals(storeName))
storeDef = def;
}
long chunkSizeBytes = Long.parseLong((String) options.valueOf("chunksize"));
Path inputPath = new Path((String) options.valueOf("input"));
Path tempDir = new Path((String) options.valueOf("tmpdir"));
Path outputDir = new Path((String) options.valueOf("output"));
boolean saveKeys = options.has("save-keys");
boolean reducerPerBucket = options.has("reducer-per-bucket");
List<String> addJars = new ArrayList<String>();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if(options.has("jar")) {
String jar = (String) options.valueOf("jar");
URL[] urls = new URL[1];
urls[0] = new File(jar).toURI().toURL();
cl = new URLClassLoader(urls);
addJars.add(jar);
}
Class<? extends AbstractHadoopStoreBuilderMapper<?, ?>> mapperClass = (Class<? extends AbstractHadoopStoreBuilderMapper<?, ?>>) ReflectUtils.loadClass((String) options.valueOf("mapper"),
cl);
Class<? extends InputFormat<?, ?>> inputFormatClass = TextInputFormat.class;
if(options.has("inputformat")) {
String inputFormatClassName = (String) options.valueOf("inputformat");
if(!inputFormatClassName.equalsIgnoreCase("TextInputFormat")) {
inputFormatClass = (Class<? extends InputFormat<?, ?>>) ReflectUtils.loadClass(inputFormatClassName,
cl);
}
}
if(inputFormatClass == null) {
inputFormatClass = TextInputFormat.class;
}
Configuration conf = getConf();
// delete output dir if it already exists
if(options.has("force-overwrite")) {
FileSystem fs = outputDir.getFileSystem(conf);
fs.delete(outputDir, true);
}
CheckSumType checkSumType = CheckSumType.toType(CmdUtils.valueOf(options, "checksum", ""));
Class[] deps = new Class[] { ImmutableCollection.class, JDOMException.class,
VoldemortConfig.class, HadoopStoreJobRunner.class, mapperClass };
int numChunks = CmdUtils.valueOf(options, "num-chunks", -1);
boolean isAvro = CmdUtils.valueOf(options, "is-avro", false);
addDepJars(conf, deps, addJars);
HadoopStoreBuilder builder = new HadoopStoreBuilder(conf,
mapperClass,
inputFormatClass,
cluster,
storeDef,
tempDir,
outputDir,
inputPath,
checkSumType,
saveKeys,
reducerPerBucket,
chunkSizeBytes,
numChunks,
isAvro,
null);
builder.build();
return 0;
}
public static String findInClasspath(String className) {
return findInClasspath(className, HadoopStoreJobRunner.class.getClassLoader());
}
/**
* @return a jar file path or a base directory or null if not found.
*/
public static String findInClasspath(String className, ClassLoader loader) {
String relPath = className;
relPath = relPath.replace('.', '/');
relPath += ".class";
java.net.URL classUrl = loader.getResource(relPath);
String codePath;
if(classUrl != null) {
boolean inJar = classUrl.getProtocol().equals("jar");
codePath = classUrl.toString();
if(codePath.startsWith("jar:")) {
codePath = codePath.substring("jar:".length());
}
if(codePath.startsWith("file:")) { // can have both
codePath = codePath.substring("file:".length());
}
if(inJar) {
// A jar spec: remove class suffix in
// /path/my.jar!/package/Class
int bang = codePath.lastIndexOf('!');
codePath = codePath.substring(0, bang);
} else {
// A class spec: remove the /my/package/Class.class portion
int pos = codePath.lastIndexOf(relPath);
if(pos == -1) {
throw new IllegalArgumentException("invalid codePath: className=" + className
+ " codePath=" + codePath);
}
codePath = codePath.substring(0, pos);
}
} else {
codePath = null;
}
return codePath;
}
private static void addDepJars(Configuration conf, Class<?>[] deps, List<String> additionalJars)
throws IOException {
FileSystem localFs = FileSystem.getLocal(conf);
Set<String> depJars = new HashSet<String>();
for(Class<?> dep: deps) {
String tmp = findInClasspath(dep.getCanonicalName());
if(tmp != null) {
Path path = new Path(tmp);
depJars.add(path.makeQualified(localFs).toString());
}
}
for(String additional: additionalJars) {
Path path = new Path(additional);
depJars.add(path.makeQualified(localFs).toString());
}
String[] tmpjars = conf.get("tmpjars", "").split(",");
for(String tmpjar: tmpjars) {
if(!StringUtils.isEmpty(tmpjar)) {
depJars.add(tmpjar.trim());
}
}
conf.set("tmpjars", StringUtils.join(depJars.iterator(), ','));
}
public static void main(String[] args) {
int res = 1; // Init to 1 to please the compiler
try {
res = ToolRunner.run(new Configuration(), new HadoopStoreJobRunner(), args);
} catch(Exception e) {
e.printStackTrace();
System.err.print("\nTry '--help' for more information.");
System.exit(1);
}
System.exit(res);
}
}
| {
"content_hash": "7b39f58185ab230c5f79712f22734cbb",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 194,
"avg_line_length": 42.73571428571429,
"alnum_prop": 0.5568276784221963,
"repo_name": "rickbw/voldemort",
"id": "b39b8b8d5346788427bb3daebe7cc15f85122132",
"size": "12566",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/HadoopStoreJobRunner.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "11075"
},
{
"name": "C++",
"bytes": "208105"
},
{
"name": "CSS",
"bytes": "1078"
},
{
"name": "HTML",
"bytes": "13143"
},
{
"name": "Java",
"bytes": "8031814"
},
{
"name": "Protocol Buffer",
"bytes": "19298"
},
{
"name": "Python",
"bytes": "85637"
},
{
"name": "Ruby",
"bytes": "52094"
},
{
"name": "Shell",
"bytes": "74848"
},
{
"name": "Thrift",
"bytes": "837"
}
],
"symlink_target": ""
} |
import React, { useMemo } from 'react';
import features from './index';
import { getObjectKeys } from '@/lib/objects';
type ListItems = [string, React.ComponentType][];
export default ({ enabled }: { enabled: string[] }) => {
const mapped: ListItems = useMemo(() => {
return getObjectKeys(features)
.filter((key) => enabled.map((v) => v.toLowerCase()).includes(key.toLowerCase()))
.reduce((arr, key) => [...arr, [key, features[key]]], [] as ListItems);
}, [enabled]);
return (
<React.Suspense fallback={null}>
{mapped.map(([key, Component]) => (
<Component key={key} />
))}
</React.Suspense>
);
};
| {
"content_hash": "9962e40cb3cbd6386b2ac60ae5cc7316",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 93,
"avg_line_length": 33.57142857142857,
"alnum_prop": 0.550354609929078,
"repo_name": "Pterodactyl/Panel",
"id": "571c7afc6f0f4c99f7a61cf7f60e20aaa2fbcd8d",
"size": "705",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "resources/scripts/components/server/features/Features.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19668"
},
{
"name": "HTML",
"bytes": "434532"
},
{
"name": "JavaScript",
"bytes": "95971"
},
{
"name": "PHP",
"bytes": "1790620"
},
{
"name": "Shell",
"bytes": "4060"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
class RemoveNames
{
static void Main()
{
List<string> firstList = new List<string>();//FIRST LIST OF NAMES
string[] firstArray = Console.ReadLine().Split();
for (int i = 0; i < firstArray.Length; i++)
{
firstList.Add(firstArray[i]);
}
List<string> secondList = new List<string>();//SECOND LIST OF NAMES
string[] secondArray = Console.ReadLine().Split();
for (int i = 0; i < secondArray.Length; i++)
{
secondList.Add(secondArray[i]);
}
List<string> allLists = new List<string>();//COMBINED LIST OF 1ST AND 2ND LISTS
foreach (var VARIABLE in firstList)
{
if (secondList.Contains(VARIABLE))
{
continue;
}
else
{
allLists.Add(VARIABLE);
}
}
foreach (var VARIABLE in allLists)
{
Console.Write("{0} ", VARIABLE);
}
Console.WriteLine();
}
} | {
"content_hash": "c67a8d5fbaeed906f7b39eddacdcd58d",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 87,
"avg_line_length": 26.372093023255815,
"alnum_prop": 0.48853615520282184,
"repo_name": "AleikovStudio/HW09CSharpAdvanced",
"id": "4ea2f67c2574e7a33a3c884982c434dd937bea4c",
"size": "1136",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "09RemoveNames/RemoveNames.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "30213"
}
],
"symlink_target": ""
} |
// --------------------------------------------------------------------------------------------
// <copyright file="ResultSetComposerMock.cs" company="Effort Team">
// Copyright (C) 2011-2014 Effort Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------
namespace Effort.Test.Internal.Fakes
{
using System.Collections.Generic;
using Effort.Test.Internal.ResultSets;
internal class ResultSetComposerMock : IResultSetComposer
{
private int commitCounter;
private int setValueCounter;
private HashSet<string> currentItem;
public ResultSetComposerMock()
{
this.currentItem = new HashSet<string>();
this.commitCounter = 0;
this.setValueCounter = 0;
}
public IResultSet ResultSet
{
get { return null; }
}
public int CommitCount
{
get { return this.commitCounter; }
}
public int SetValueCount
{
get { return this.setValueCounter; }
}
public void SetValue<T>(string name, T value)
{
if (this.currentItem.Add(name))
{
this.setValueCounter++;
}
}
public void Commit()
{
this.commitCounter++;
this.currentItem.Clear();
}
}
}
| {
"content_hash": "2afbbdf3a9ac53da93c0d4f57be1f79b",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 96,
"avg_line_length": 35.78378378378378,
"alnum_prop": 0.5672205438066465,
"repo_name": "zamabraga/effort",
"id": "e2e9cd0e77664a19a403c98ce77a4a86976eb391",
"size": "2650",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "Main/Source/Effort.Test/Internal/Fakes/ResultSetComposerMock.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1104"
},
{
"name": "C#",
"bytes": "2446705"
}
],
"symlink_target": ""
} |
var EventsView = Backbone.View.extend({
initialize: function() {
_.bindAll(this,"render");
this.render();
},
//renders a simple map view
render: function() {
var self = this;
var filtertypelist = {'Type':{'val':1,'label':'eventType'},'Class':{'val':2,'label':'class'},'Cruise':{'val':3,'label':'cruiseNumber'}};
//bind
self.model = new EventsModel();
self.modalDialog = new ModalDialogView();
var PageableDeployments = Backbone.PageableCollection.extend({
model: EventsModel,
url: '/api/asset_events',
state: {
pageSize: 18
},
mode: "client",
parse: function(response, options) {
this.trigger("pageabledeploy:updated", { count : response.count, total : response.total, startAt : response.startAt } );
return response.events;
} // page entirely on the client side options: infinite, server
});
var pageabledeploy = new PageableDeployments();
self.collection = pageabledeploy;
var columns = [{
name: "eventId", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
// Defines a cell type, and ID is displayed as an integer without the ',' separating 1000s.
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
}, {
name: "cruiseNumber",
editable: false,
label: "Cruise Name",
cell: "string"
},
/*{
name: "assetInfo",
label: "Name",
editable: false,
// The cell type can be a reference of a Backgrid.Cell subclass, any Backgrid.Cell subclass instances like *id* above, or a string
cell: "string",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue, model) {
return rawValue['name'];
}
}),
sortValue: function (model, colName) {
return model.attributes[colName]['name'];
}
},*/{
name: "eventType",
label: "Type",
editable: false,
cell: "string"
}, {
name: "class",
label: "Class",
editable: false,
cell: "string"
}, {
name: "startDate",
label: "Start Date",
editable: false,
cell: "string",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue, model) {
if(rawValue !=null){
var sd = new Date(rawValue);
return sd.toDateString();
}
else{
return 'No Date';
}
}
})
},{
name: "endDate",
label: "End Date",
editable: false,
cell: "string",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue, model) {
if(rawValue !=null){
var sd = new Date(rawValue);
return sd.toDateString();
}
else{
return 'No Date';
}
}
})
}, {
name: "deploymentDepth",
editable: false,
label: "Depth",
cell: "string"
},{
name: "eventDescription",
label: "Description",
editable: false,
cell: "string"
}];
//add click event
var ClickableRow = Backgrid.Row.extend({
highlightColor: "#eee",
events: {
"click": "onClick",
mouseover: "rowFocused",
mouseout: "rowLostFocus"
},
onClick: function () {
Backbone.trigger("deployrowclicked", this.model);
this.el.style.backgroundColor = this.highlightColor;
var $table = $('#table-transform');
$table.bootstrapTable();
},
rowFocused: function() {
this.el.style.backgroundColor = this.highlightColor;
},
rowLostFocus: function() {
this.el.style.backgroundColor = '#FFF';
}
});
// Set up a grid to use the pageable collection
var pageableGrid = new Backgrid.Grid({
columns: columns,
// enable the select-all extension and select row
/*[{
name: "",
cell: "select-row",
headerCell: "select-all"
}].concat(columns),*/
collection: pageabledeploy,
row: ClickableRow
});
// Render the grid and attach the root to your HTML document
$("#datatable").append(pageableGrid.render().el);
// Initialize the paginator
var paginator = new Backgrid.Extension.Paginator({
collection: pageabledeploy
});
// Render the paginator
$("#datatable").after(paginator.render().el);
// Initialize a client-side filter to filter on the client
// mode pageable collection's cache.
//extend to match the nested object parameters
var AssetFilter = Backgrid.Extension.ClientSideFilter.extend({
//collection: pageabledeploy,
//fields: ["assetId",'@class'],
placeholder: "Search",
makeMatcher: function(query){
var q = '';
if(query!=""){
q = String(query).toUpperCase();
}
return function (model) {
var queryhit = false;
if(self.query_filter){
//iterate through the filtering to see if it matches any of the attributes
queryhit = true;
for(var obj in self.query_filter){
for (var j = 0; j < self.query_filter[obj].length; j++ ) {
if(self.query_filter[obj][j] == model.attributes[filtertypelist[obj].label]){queryhit= true;}
//else if(self.query_filter[obj][j] == model.attributes[String(obj).toLowerCase()]){queryhit= true;}
//this is so that it refreshes if there is no drop down queries
else{queryhit = false;}
}
}
if(q==''){
return queryhit;
}
}
//still allow upper right hand search to occur
if(q==''){
queryhit= true;
}
else{
if(model.attributes['class']){
if(String(model.attributes['class']).toUpperCase().search(q)>-1){
queryhit= true;
}else{queryhit= false};
}
if(model.attributes['eventDescription']){
if(String(model.attributes['eventDescription']).toUpperCase().search(q)>-1){
queryhit= true;
}else{queryhit= false};
}
if(model.attributes['eventType']){
if(String(model.attributes['eventType']).toUpperCase().search(q)>-1){
queryhit= true;
}else{queryhit= false};
}
if(model.attributes['cruiseNumber']){
if(String(model.attributes['cruiseNumber']).toUpperCase().search(q)>-1){
queryhit= true;
}else{queryhit= false};
}
}
return queryhit;
};
}
});
var filter = new AssetFilter({
collection: pageabledeploy
});
self.filter = filter;
// Render the filter
$("#datatable").before(filter.render().el);
// Add some space to the filter and move it to the right
$(filter.el).css({float: "right", margin: "20px"});
$(filter.el).find("input").attr('id', 'asset_search_box');
// Fetch some Events from the url
pageabledeploy.fetch({reset: true,
error: (function (e) {
$('#asset_top_panel').html('There was an error with the Event list.');
alert(' Service request failure: ' + e);
}),
complete: (function (e) {
$('#number_of_assets').html(e.responseJSON['events'].length+' total records');
$('#asset_top_panel').html('Click on an Event to View/Edit');
//need to add assets to the filtrify component
for ( t = 0; t < e.responseJSON['events'].length; t++ ) {
$('#container_of_data').append("<li data-Type='"+e.responseJSON['events'][t]['eventType']+"' data-Class='"+e.responseJSON['events'][t]['class']+"' data-Cruise='"+e.responseJSON['events'][t]['cruiseNumber']+"'><span>Type: <i>"+e.responseJSON['events'][t]['eventType']+"</i></span><span>Class: <i>"+e.responseJSON['events'][t]['class']+"</i></span><span>Cruise: <i>"+e.responseJSON['events'][t]['cruiseNumber']+"</span></li>");
}
//query drop downs filters based on data
$.filtrify( 'container_of_data', 'asset_search_pan', {
callback : function( query, match, mismatch ) {
self.query_filter = query;
self.filter.search();
$('#number_of_assets').html(match.length+' total records');
}
});
})
});
//try to call this on page change
pageabledeploy.on("pageabledeploy:updated", function( details ){
//updatePagination( details, showBicycles );
});
//move clicked row to edit panel
Backbone.on("deployrowclicked", function (model) {
//got to event page for that event
if(model.attributes.eventId){
window.open('/event/'+model.attributes.eventId,'_blank');
}
});
}
}); | {
"content_hash": "c44e1a53ce2ebec5886e313b3f34ed73",
"timestamp": "",
"source": "github",
"line_count": 274,
"max_line_length": 445,
"avg_line_length": 38.48905109489051,
"alnum_prop": 0.4806561729565712,
"repo_name": "ssontag55/ooi-ui",
"id": "eceb10d1380d9f6ffb6a5e0176704ce21744e079",
"size": "10546",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ooiui/static/js/views/asset_management/EventsView.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "53945"
},
{
"name": "HTML",
"bytes": "457461"
},
{
"name": "JavaScript",
"bytes": "353037"
},
{
"name": "Python",
"bytes": "29691"
}
],
"symlink_target": ""
} |
<html lang="en">
<head>
<title>More DFTs of Real Data - FFTW 3.2.2</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="FFTW 3.2.2">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Tutorial.html#Tutorial" title="Tutorial">
<link rel="prev" href="Multi_002dDimensional-DFTs-of-Real-Data.html#Multi_002dDimensional-DFTs-of-Real-Data" title="Multi-Dimensional DFTs of Real Data">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This manual is for FFTW
(version 3.2.2, 12 July 2009).
Copyright (C) 2003 Matteo Frigo.
Copyright (C) 2003 Massachusetts Institute of Technology.
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission
notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided
that the entire resulting derived work is distributed under the
terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for
modified versions, except that this permission notice may be
stated in a translation approved by the Free Software Foundation.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<a name="More-DFTs-of-Real-Data"></a>
<p>
Previous: <a rel="previous" accesskey="p" href="Multi_002dDimensional-DFTs-of-Real-Data.html#Multi_002dDimensional-DFTs-of-Real-Data">Multi-Dimensional DFTs of Real Data</a>,
Up: <a rel="up" accesskey="u" href="Tutorial.html#Tutorial">Tutorial</a>
<hr>
</div>
<h3 class="section">2.5 More DFTs of Real Data</h3>
<ul class="menu">
<li><a accesskey="1" href="The-Halfcomplex_002dformat-DFT.html#The-Halfcomplex_002dformat-DFT">The Halfcomplex-format DFT</a>
<li><a accesskey="2" href="Real-even_002fodd-DFTs-_0028cosine_002fsine-transforms_0029.html#Real-even_002fodd-DFTs-_0028cosine_002fsine-transforms_0029">Real even/odd DFTs (cosine/sine transforms)</a>
<li><a accesskey="3" href="The-Discrete-Hartley-Transform.html#The-Discrete-Hartley-Transform">The Discrete Hartley Transform</a>
</ul>
<p>FFTW supports several other transform types via a unified <dfn>r2r</dfn>
(real-to-real) interface,
<a name="index-r2r-64"></a>so called because it takes a real (<code>double</code>) array and outputs a
real array of the same size. These r2r transforms currently fall into
three categories: DFTs of real input and complex-Hermitian output in
halfcomplex format, DFTs of real input with even/odd symmetry
(a.k.a. discrete cosine/sine transforms, DCTs/DSTs), and discrete
Hartley transforms (DHTs), all described in more detail by the
following sections.
<p>The r2r transforms follow the by now familiar interface of creating an
<code>fftw_plan</code>, executing it with <code>fftw_execute(plan)</code>, and
destroying it with <code>fftw_destroy_plan(plan)</code>. Furthermore, all
r2r transforms share the same planner interface:
<pre class="example"> fftw_plan fftw_plan_r2r_1d(int n, double *in, double *out,
fftw_r2r_kind kind, unsigned flags);
fftw_plan fftw_plan_r2r_2d(int n0, int n1, double *in, double *out,
fftw_r2r_kind kind0, fftw_r2r_kind kind1,
unsigned flags);
fftw_plan fftw_plan_r2r_3d(int n0, int n1, int n2,
double *in, double *out,
fftw_r2r_kind kind0,
fftw_r2r_kind kind1,
fftw_r2r_kind kind2,
unsigned flags);
fftw_plan fftw_plan_r2r(int rank, const int *n, double *in, double *out,
const fftw_r2r_kind *kind, unsigned flags);
</pre>
<p><a name="index-fftw_005fplan_005fr2r_005f1d-65"></a><a name="index-fftw_005fplan_005fr2r_005f2d-66"></a><a name="index-fftw_005fplan_005fr2r_005f3d-67"></a><a name="index-fftw_005fplan_005fr2r-68"></a>
Just as for the complex DFT, these plan 1d/2d/3d/multi-dimensional
transforms for contiguous arrays in row-major order, transforming (real)
input to output of the same size, where <code>n</code> specifies the
<em>physical</em> dimensions of the arrays. All positive <code>n</code> are
supported (with the exception of <code>n=1</code> for the <code>FFTW_REDFT00</code>
kind, noted in the real-even subsection below); products of small
factors are most efficient (factorizing <code>n-1</code> and <code>n+1</code> for
<code>FFTW_REDFT00</code> and <code>FFTW_RODFT00</code> kinds, described below), but
an <i>O</i>(<i>n</i> log <i>n</i>) algorithm is used even for prime sizes.
<p>Each dimension has a <dfn>kind</dfn> parameter, of type
<code>fftw_r2r_kind</code>, specifying the kind of r2r transform to be used
for that dimension.
<a name="index-kind-_0028r2r_0029-69"></a><a name="index-fftw_005fr2r_005fkind-70"></a>(In the case of <code>fftw_plan_r2r</code>, this is an array <code>kind[rank]</code>
where <code>kind[i]</code> is the transform kind for the dimension
<code>n[i]</code>.) The kind can be one of a set of predefined constants,
defined in the following subsections.
<p>In other words, FFTW computes the separable product of the specified
r2r transforms over each dimension, which can be used e.g. for partial
differential equations with mixed boundary conditions. (For some r2r
kinds, notably the halfcomplex DFT and the DHT, such a separable
product is somewhat problematic in more than one dimension, however,
as is described below.)
<p>In the current version of FFTW, all r2r transforms except for the
halfcomplex type are computed via pre- or post-processing of
halfcomplex transforms, and they are therefore not as fast as they
could be. Since most other general DCT/DST codes employ a similar
algorithm, however, FFTW's implementation should provide at least
competitive performance.
<!-- =========> -->
</body></html>
| {
"content_hash": "e97a18bc38c616eee07e6f143f19ef71",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 207,
"avg_line_length": 53.110236220472444,
"alnum_prop": 0.7101556708673091,
"repo_name": "vtsuperdarn/SuperDARN_MSI_ROS",
"id": "eee66cc280bdf95dc395172b6d733bb4940d1b2f",
"size": "6745",
"binary": false,
"copies": "9",
"ref": "refs/heads/devel",
"path": "qnx/root/operational_radar_code/ros/fftw-3.2.2/doc/html/More-DFTs-of-Real-Data.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1239"
},
{
"name": "C",
"bytes": "12008713"
},
{
"name": "C++",
"bytes": "78496"
},
{
"name": "CSS",
"bytes": "14447"
},
{
"name": "Eagle",
"bytes": "5586"
},
{
"name": "Fortran",
"bytes": "5364"
},
{
"name": "Groff",
"bytes": "23733"
},
{
"name": "HTML",
"bytes": "1497290"
},
{
"name": "Makefile",
"bytes": "874578"
},
{
"name": "OCaml",
"bytes": "253115"
},
{
"name": "Objective-C",
"bytes": "17806"
},
{
"name": "Perl",
"bytes": "42100"
},
{
"name": "Python",
"bytes": "5507"
},
{
"name": "SAS",
"bytes": "5732"
},
{
"name": "Scheme",
"bytes": "5581"
},
{
"name": "Scilab",
"bytes": "5583"
},
{
"name": "Shell",
"bytes": "758443"
},
{
"name": "Standard ML",
"bytes": "1212"
},
{
"name": "TeX",
"bytes": "290889"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.execution.executor;
import com.google.common.base.Ticker;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.airlift.log.Logger;
import io.airlift.stats.CounterStat;
import io.airlift.stats.CpuTimer;
import io.airlift.stats.TimeStat;
import io.airlift.units.Duration;
import io.trino.execution.SplitRunner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static io.trino.operator.Operator.NOT_BLOCKED;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class PrioritizedSplitRunner
implements Comparable<PrioritizedSplitRunner>
{
private static final AtomicLong NEXT_WORKER_ID = new AtomicLong();
private static final Logger log = Logger.get(PrioritizedSplitRunner.class);
// each time we run a split, run it for this length before returning to the pool
public static final Duration SPLIT_RUN_QUANTA = new Duration(1, TimeUnit.SECONDS);
private final long createdNanos = System.nanoTime();
private final TaskHandle taskHandle;
private final int splitId;
private final long workerId;
private final SplitRunner split;
private final Ticker ticker;
private final SettableFuture<Void> finishedFuture = SettableFuture.create();
private final AtomicBoolean destroyed = new AtomicBoolean();
protected final AtomicReference<Priority> priority = new AtomicReference<>(new Priority(0, 0));
protected final AtomicLong lastRun = new AtomicLong();
private final AtomicLong lastReady = new AtomicLong();
private final AtomicLong start = new AtomicLong();
private final AtomicLong scheduledNanos = new AtomicLong();
private final AtomicLong waitNanos = new AtomicLong();
private final AtomicLong cpuTimeNanos = new AtomicLong();
private final AtomicLong processCalls = new AtomicLong();
private final CounterStat globalCpuTimeMicros;
private final CounterStat globalScheduledTimeMicros;
private final TimeStat blockedQuantaWallTime;
private final TimeStat unblockedQuantaWallTime;
PrioritizedSplitRunner(
TaskHandle taskHandle,
SplitRunner split,
Ticker ticker,
CounterStat globalCpuTimeMicros,
CounterStat globalScheduledTimeMicros,
TimeStat blockedQuantaWallTime,
TimeStat unblockedQuantaWallTime)
{
this.taskHandle = taskHandle;
this.splitId = taskHandle.getNextSplitId();
this.split = split;
this.ticker = ticker;
this.workerId = NEXT_WORKER_ID.getAndIncrement();
this.globalCpuTimeMicros = globalCpuTimeMicros;
this.globalScheduledTimeMicros = globalScheduledTimeMicros;
this.blockedQuantaWallTime = blockedQuantaWallTime;
this.unblockedQuantaWallTime = unblockedQuantaWallTime;
this.updateLevelPriority();
}
public TaskHandle getTaskHandle()
{
return taskHandle;
}
public ListenableFuture<Void> getFinishedFuture()
{
return finishedFuture;
}
public boolean isDestroyed()
{
return destroyed.get();
}
public void destroy()
{
destroyed.set(true);
try {
split.close();
}
catch (RuntimeException e) {
log.error(e, "Error closing split for task %s", taskHandle.getTaskId());
}
}
public long getCreatedNanos()
{
return createdNanos;
}
public boolean isFinished()
{
boolean finished = split.isFinished();
if (finished) {
finishedFuture.set(null);
}
return finished || destroyed.get() || taskHandle.isDestroyed();
}
public long getScheduledNanos()
{
return scheduledNanos.get();
}
public long getCpuTimeNanos()
{
return cpuTimeNanos.get();
}
public long getWaitNanos()
{
return waitNanos.get();
}
public ListenableFuture<Void> process()
{
try {
long startNanos = ticker.read();
start.compareAndSet(0, startNanos);
lastReady.compareAndSet(0, startNanos);
processCalls.incrementAndGet();
waitNanos.getAndAdd(startNanos - lastReady.get());
CpuTimer timer = new CpuTimer();
ListenableFuture<Void> blocked = split.processFor(SPLIT_RUN_QUANTA);
CpuTimer.CpuDuration elapsed = timer.elapsedTime();
long quantaScheduledNanos = ticker.read() - startNanos;
scheduledNanos.addAndGet(quantaScheduledNanos);
priority.set(taskHandle.addScheduledNanos(quantaScheduledNanos));
lastRun.set(ticker.read());
if (blocked == NOT_BLOCKED) {
unblockedQuantaWallTime.add(elapsed.getWall());
}
else {
blockedQuantaWallTime.add(elapsed.getWall());
}
long quantaCpuNanos = elapsed.getCpu().roundTo(NANOSECONDS);
cpuTimeNanos.addAndGet(quantaCpuNanos);
globalCpuTimeMicros.update(quantaCpuNanos / 1000);
globalScheduledTimeMicros.update(quantaScheduledNanos / 1000);
return blocked;
}
catch (Throwable e) {
finishedFuture.setException(e);
throw e;
}
}
public void setReady()
{
lastReady.set(ticker.read());
}
/**
* Updates the (potentially stale) priority value cached in this object.
* This should be called when this object is outside the queue.
*
* @return true if the level changed.
*/
public boolean updateLevelPriority()
{
Priority newPriority = taskHandle.getPriority();
Priority oldPriority = priority.getAndSet(newPriority);
return newPriority.getLevel() != oldPriority.getLevel();
}
/**
* Updates the task level priority to be greater than or equal to the minimum
* priority within that level. This ensures that tasks that spend time blocked do
* not return and starve already-running tasks. Also updates the cached priority
* object.
*/
public void resetLevelPriority()
{
priority.set(taskHandle.resetLevelPriority());
}
@Override
public int compareTo(PrioritizedSplitRunner o)
{
int result = Long.compare(priority.get().getLevelPriority(), o.getPriority().getLevelPriority());
if (result != 0) {
return result;
}
return Long.compare(workerId, o.workerId);
}
public int getSplitId()
{
return splitId;
}
public Priority getPriority()
{
return priority.get();
}
public String getInfo()
{
return format("Split %-15s-%d %s (start = %s, wall = %s ms, cpu = %s ms, wait = %s ms, calls = %s)",
taskHandle.getTaskId(),
splitId,
split.getInfo(),
start.get() / 1.0e6,
(int) ((ticker.read() - start.get()) / 1.0e6),
(int) (cpuTimeNanos.get() / 1.0e6),
(int) (waitNanos.get() / 1.0e6),
processCalls.get());
}
@Override
public String toString()
{
return format("Split %-15s-%d", taskHandle.getTaskId(), splitId);
}
}
| {
"content_hash": "bd12df453cec9baeb6ab35ecb82e33fe",
"timestamp": "",
"source": "github",
"line_count": 261,
"max_line_length": 108,
"avg_line_length": 30.938697318007662,
"alnum_prop": 0.6534984520123839,
"repo_name": "ebyhr/presto",
"id": "1b849e870ae03da2d084c5c06b3ec31f40766da5",
"size": "8075",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "core/trino-main/src/main/java/io/trino/execution/executor/PrioritizedSplitRunner.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "26917"
},
{
"name": "CSS",
"bytes": "12957"
},
{
"name": "HTML",
"bytes": "28832"
},
{
"name": "Java",
"bytes": "31247929"
},
{
"name": "JavaScript",
"bytes": "211244"
},
{
"name": "Makefile",
"bytes": "6830"
},
{
"name": "PLSQL",
"bytes": "2797"
},
{
"name": "PLpgSQL",
"bytes": "11504"
},
{
"name": "Python",
"bytes": "7811"
},
{
"name": "SQLPL",
"bytes": "926"
},
{
"name": "Shell",
"bytes": "29857"
},
{
"name": "Thrift",
"bytes": "12631"
}
],
"symlink_target": ""
} |
'use strict';
const models = require('./index');
/**
* Defines the metrics that indicate how well an item was rated by others.
*
* @extends models['Rating']
*/
class AggregateRating extends models['Rating'] {
/**
* Create a AggregateRating.
* @property {number} [reviewCount] The number of times the recipe has been
* rated or reviewed.
*/
constructor() {
super();
}
/**
* Defines the metadata of AggregateRating
*
* @returns {object} metadata of AggregateRating
*
*/
mapper() {
return {
required: false,
serializedName: 'AggregateRating',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'PropertiesItem',
className: 'AggregateRating',
modelProperties: {
text: {
required: false,
readOnly: true,
serializedName: 'text',
type: {
name: 'String'
}
},
_type: {
required: true,
serializedName: '_type',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
ratingValue: {
required: true,
serializedName: 'ratingValue',
type: {
name: 'Number'
}
},
bestRating: {
required: false,
readOnly: true,
serializedName: 'bestRating',
type: {
name: 'Number'
}
},
reviewCount: {
required: false,
readOnly: true,
serializedName: 'reviewCount',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = AggregateRating;
| {
"content_hash": "9bc4588d90077a6786cf0534cf4449fd",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 77,
"avg_line_length": 22,
"alnum_prop": 0.47463002114164904,
"repo_name": "xingwu1/azure-sdk-for-node",
"id": "b1e311c978b2e71525b18dd929094b31cc42f123",
"size": "2209",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "lib/services/imageSearch/lib/models/aggregateRating.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "661"
},
{
"name": "JavaScript",
"bytes": "122792600"
},
{
"name": "Shell",
"bytes": "437"
},
{
"name": "TypeScript",
"bytes": "2558"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">xaHChat</string>
<string name="action_settings">Settings</string>
</resources>
| {
"content_hash": "cb22d4f571f7d5db0d67dc4f147de26f",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 52,
"avg_line_length": 32.4,
"alnum_prop": 0.6790123456790124,
"repo_name": "lemonxah/xaHChat",
"id": "a4d9cf9748e04c19db574af81649c9e3f9202b36",
"size": "162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/res/values/strings.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "25889"
}
],
"symlink_target": ""
} |
<TS language="be_BY" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Правы клік, каб рэдагаваць адрас ці метку</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Стварыць новы адрас</translation>
</message>
<message>
<source>&New</source>
<translation>Новы</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Капіяваць пазначаны адрас у сістэмны буфер абмену</translation>
</message>
<message>
<source>&Copy</source>
<translation>Капіяваць</translation>
</message>
<message>
<source>C&lose</source>
<translation>Зачыніць</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>Капіяваць адрас</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Выдаліць абраны адрас са спісу</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Экспартаваць гэтыя звесткі у файл</translation>
</message>
<message>
<source>&Export</source>
<translation>Экспарт</translation>
</message>
<message>
<source>&Delete</source>
<translation>Выдаліць</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Выбраць адрас, куды выслаць сродкі</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Выбраць адрас, на які атрымаць сродкі</translation>
</message>
<message>
<source>C&hoose</source>
<translation>Выбраць</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>адрасы Адпраўкі</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>адрасы Прымання</translation>
</message>
<message>
<source>These are your Fullcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Тут знаходзяцца Fullcoin-адрасы для высылання плацяжоў. Заўсёды спраўджвайце колькасць і адрас прызначэння перад здзяйсненнем транзакцыі.</translation>
</message>
<message>
<source>These are your Fullcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Тут знаходзяцца Fullcoin-адрасы для прымання плацяжоў. Пажадана выкарыстоўваць новы адрас для кожнай транзакцыі.</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Капіяваць Метку</translation>
</message>
<message>
<source>&Edit</source>
<translation>Рэдагаваць</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Экспартаваць Спіс Адрасоў</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Коскамі падзелены файл (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Экспартаванне няўдалае</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>Адбылася памылка падчас спробы захаваць адрас у %1. Паспрабуйце зноў.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<source>Address</source>
<translation>Адрас</translation>
</message>
<message>
<source>(no label)</source>
<translation>непазначаны</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Дыялог сакрэтнай фразы</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Увядзіце кодавую фразу</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Новая кодавая фраза</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Паўтарыце новую кодавую фразу</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Зашыфраваць гаманец.</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Гэтая аперацыя патрабуе кодавую фразу, каб рзблакаваць гаманец.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Разблакаваць гаманец</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Гэтая аперацыя патрабуе пароль каб расшыфраваць гаманец.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Рачшыфраваць гаманец</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Змяніць пароль</translation>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Увядзіце стары і новы пароль да гаманца.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Пацвердзіце шыфраванне гаманца</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR FULLCOINS</b>!</source>
<translation>Увага: калі вы зашыфруеце свой гаманец і страціце парольную фразу, то <b>СТРАЦІЦЕ ЎСЕ СВАЕ FULLCOINS</b>!</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Ці ўпэўненыя вы, што жадаеце зашыфраваць свой гаманец?</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ВАЖНА: Усе папярэднія копіі гаманца варта замяніць новым зашыфраваным файлам. У мэтах бяспекі папярэднія копіі незашыфраванага файла-гаманца стануць неўжывальнымі, калі вы станеце карыстацца новым зашыфраваным гаманцом.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Увага: Caps Lock уключаны!</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Гаманец зашыфраваны</translation>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Увядзіце новы пароль для гаманца.<br/>Парольная фраза павинна складацца<b> не меньш чым з дзесяці сімвалаў</b>, ці <b>больш чым з васьмі слоў</b>.</translation>
</message>
<message>
<source>Fullcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your fullcoins from being stolen by malware infecting your computer.</source>
<translation>Fullcoin зачыняецца дзеля завяршэння працэсса шыфравання. Памятайце, што шыфраванне гаманца цалкам абараняе вашыя сродкі ад скрадання шкоднымі праграмамі якія могуць пранікнуць у ваш камп'ютар.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Шыфраванне гаманца няўдалае</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Шыфраванне гаманца не адбылося з-за ўнутранай памылкі. Гаманец незашыфраваны.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Уведдзеныя паролі не супадаюць</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Разблакаванне гаманца няўдалае</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Уведзена пароль дзеля расшыфравання гаманца памылковы</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Расшыфраванне гаманца няўдалае</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Парольная фраза гаманца паспяхова зменена.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Падпісаць паведамленне...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Сінхранізацыя з сецівам...</translation>
</message>
<message>
<source>&Overview</source>
<translation>Агляд</translation>
</message>
<message>
<source>Node</source>
<translation>Вузел</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Паказвае агульныя звесткі аб гаманцы</translation>
</message>
<message>
<source>&Transactions</source>
<translation>Транзакцыі</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Праглядзець гісторыю транзакцый</translation>
</message>
<message>
<source>E&xit</source>
<translation>Выйсці</translation>
</message>
<message>
<source>Quit application</source>
<translation>Выйсці з праграмы</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Аб Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Паказаць інфармацыю аб Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>Опцыі...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>Зашыфраваць Гаманец...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>Стварыць копію гаманца...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Change Passphrase...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>Адрасы дасылання...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>Адрасы прымання...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Адчыниць &URI...</translation>
</message>
<message>
<source>Fullcoin Core client</source>
<translation>Fullcoin Core кліент</translation>
</message>
<message>
<source>Importing blocks from disk...</source>
<translation>Імпартуюцца блокі з дыску...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Пераіндэксацыя блокаў на дыску...</translation>
</message>
<message>
<source>Send coins to a Fullcoin address</source>
<translation>Даслаць манеты на Fullcoin-адрас</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Зрабіце копію гаманца ў іншае месца</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Змяніць пароль шыфравання гаманца</translation>
</message>
<message>
<source>&Debug window</source>
<translation>Вакно адладкі</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Адкрыць кансоль дыягностыкі і адладкі</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>Праверыць паведамленне...</translation>
</message>
<message>
<source>Fullcoin</source>
<translation>Fullcoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Гаманец</translation>
</message>
<message>
<source>&Send</source>
<translation>Даслаць</translation>
</message>
<message>
<source>&Receive</source>
<translation>Атрымаць</translation>
</message>
<message>
<source>Show information about Fullcoin Core</source>
<translation>Паказаць інфармацыю аб Fullcoin Core</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Паказаць / Схаваць</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Паказаць альбо схаваць галоўнае вакно</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Зашыфраваць прыватныя ключы, якия належаць вашаму гаманцу</translation>
</message>
<message>
<source>Sign messages with your Fullcoin addresses to prove you own them</source>
<translation>Падпісаць паведамленне з дапамогай Fullcoin-адраса каб даказаць, што яно належыць вам</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Fullcoin addresses</source>
<translation>Спраўдзіць паведамленне з дапамогай Fullcoin-адраса каб даказаць, што яно належыць вам</translation>
</message>
<message>
<source>&File</source>
<translation>Ф&айл</translation>
</message>
<message>
<source>&Settings</source>
<translation>Наладкі</translation>
</message>
<message>
<source>&Help</source>
<translation>Дапамога</translation>
</message>
<message>
<source>Fullcoin Core</source>
<translation>Fullcoin Core</translation>
</message>
<message>
<source>Request payments (generates QR codes and fullcoin: URIs)</source>
<translation>Запатрабаваць плацёж (генеруецца QR-код для fullcoin URI)</translation>
</message>
<message>
<source>&About Fullcoin Core</source>
<translation>Аб Fullcoin Core</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Паказаць спіс адрасоў і метак для дасылання</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Паказаць спіс адрасоў і метак для прымання</translation>
</message>
<message>
<source>Open a fullcoin: URI or payment request</source>
<translation>Адкрыць fullcoin: URI ці запыт плацяжу</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Опцыі каманднага радка</translation>
</message>
<message>
<source>Show the Fullcoin Core help message to get a list with possible Fullcoin command-line options</source>
<translation>Паказваць даведку Fullcoin Core каб атрымаць спіс магчымых опцый каманднага радка</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Fullcoin network</source>
<translation><numerusform>%n актыўнае злучэнне з Fullcoin-сецівам</numerusform><numerusform>%n актыўных злучэнняў з Fullcoin-сецівам</numerusform><numerusform>%n актыўных злучэнняў з Fullcoin-сецівам</numerusform><numerusform>%n актыўных злучэнняў з Fullcoin-сецівам</numerusform></translation>
</message>
<message>
<source>No block source available...</source>
<translation>Крыніца блокаў недасяжная...</translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 і %2</translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 таму</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Апошні прыняты блок генераваны %1 таму.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Транзакцыи пасля гэтай не будуць бачныя.</translation>
</message>
<message>
<source>Error</source>
<translation>Памылка</translation>
</message>
<message>
<source>Warning</source>
<translation>Увага</translation>
</message>
<message>
<source>Information</source>
<translation>Інфармацыя</translation>
</message>
<message>
<source>Up to date</source>
<translation>Сінхранізавана</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Наганяем...</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Дасланыя транзакцыі</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Прынятыя транзакцыі</translation>
</message>
<message>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Дата: %1
Колькасць: %2
Тып: %3
Адрас: %4
</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Гаманец <b>зашыфраваны</b> і зараз <b>разблакаваны</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Гаманец <b>зашыфраваны</b> і зараз <b>заблакаваны</b></translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<source>Network Alert</source>
<translation>Трывога Сеціва</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Quantity:</source>
<translation>Колькасць:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Байтаў:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Колькасць:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Прыярытэт:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Камісія:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Пыл:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Пасля камісіі:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(не)выбраць ўсё</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Рэжым дрэва</translation>
</message>
<message>
<source>List mode</source>
<translation>Рэжым спіса</translation>
</message>
<message>
<source>Amount</source>
<translation>Колькасць</translation>
</message>
<message>
<source>Received with label</source>
<translation>Прыняць праз метку</translation>
</message>
<message>
<source>Received with address</source>
<translation>Прыняць праз адрас</translation>
</message>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Пацверджанняў</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Пацверджана</translation>
</message>
<message>
<source>Priority</source>
<translation>Прыярытэт</translation>
</message>
<message>
<source>Copy address</source>
<translation>Капіяваць адрас</translation>
</message>
<message>
<source>Copy label</source>
<translation>Капіяваць пазнаку</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Капіяваць колькасць</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Капіяваць ID транзакцыі</translation>
</message>
<message>
<source>Lock unspent</source>
<translation>Замкнуць непатрачанае</translation>
</message>
<message>
<source>Unlock unspent</source>
<translation>Адамкнуць непатрачанае</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Капіяваць колькасць</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Капіяваць камісію</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Капіяваць з выняткам камісіі</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Капіяваць байты</translation>
</message>
<message>
<source>Copy priority</source>
<translation>Капіяваць прыярытэт</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Капіяваць пыл</translation>
</message>
<message>
<source>highest</source>
<translation>найвышэйшы</translation>
</message>
<message>
<source>higher</source>
<translation>вышэйшы</translation>
</message>
<message>
<source>high</source>
<translation>высокі</translation>
</message>
<message>
<source>medium-high</source>
<translation>вышэй сярэдняга</translation>
</message>
<message>
<source>medium</source>
<translation>сярэдні</translation>
</message>
<message>
<source>low-medium</source>
<translation>ніжэй сярэдняга</translation>
</message>
<message>
<source>low</source>
<translation>нізкі</translation>
</message>
<message>
<source>lower</source>
<translation>ніжэйшы</translation>
</message>
<message>
<source>lowest</source>
<translation>найніжэйшы</translation>
</message>
<message>
<source>yes</source>
<translation>так</translation>
</message>
<message>
<source>no</source>
<translation>не</translation>
</message>
<message>
<source>This label turns red, if the transaction size is greater than 1000 bytes.</source>
<translation>Гэта метка стане чырвонай, калі транзакцыя перавысіць 1000 байт.</translation>
</message>
<message>
<source>This means a fee of at least %1 per kB is required.</source>
<translation>Гэта значыць патрэбную камісію мінімум %1 на Кб.</translation>
</message>
<message>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation>Транзакцыя большага прыярытэту больш прываблівая для ўключэння ў блок.</translation>
</message>
<message>
<source>This label turns red, if the priority is smaller than "medium".</source>
<translation>Гэта метка стане чырвонай, калі прыярытэт меньш чым "сярэдні".</translation>
</message>
<message>
<source>This label turns red, if any recipient receives an amount smaller than %1.</source>
<translation>Гэта метка стане чырвонай, калі любы з адрасатаў атрымае меньш чым %1.</translation>
</message>
<message>
<source>(no label)</source>
<translation>непазначаны</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Рэдагаваць Адрас</translation>
</message>
<message>
<source>&Label</source>
<translation>Метка</translation>
</message>
<message>
<source>&Address</source>
<translation>Адрас</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Новы адрас для атрымання</translation>
</message>
<message>
<source>New sending address</source>
<translation>Новы адрас для дасылання</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Рэдагаваць адрас прымання</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Рэдагаваць адрас дасылання</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>Уведзены адрас "%1" ужо ў кніге адрасоў</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Немагчыма разблакаваць гаманец</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Генерацыя новага ключа няўдалая</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Будзе створаны новы каталог з данымі.</translation>
</message>
<message>
<source>name</source>
<translation>імя</translation>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>Каталог ужо існуе. Дадайце %1 калі вы збіраецеся стварыць тут новы каталог.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>Fullcoin Core</source>
<translation>Fullcoin Core</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-біт)</translation>
</message>
<message>
<source>About Fullcoin Core</source>
<translation>Аб Fullcoin Core</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Опцыі каманднага радка</translation>
</message>
<message>
<source>Usage:</source>
<translation>Ужыванне:</translation>
</message>
<message>
<source>command-line options</source>
<translation>опцыі каманднага радка</translation>
</message>
<message>
<source>Start minimized</source>
<translation>Стартаваць ммінімізаванай</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Вітаем</translation>
</message>
<message>
<source>Welcome to Fullcoin Core.</source>
<translation>Вітаем у Fullcoin Core.</translation>
</message>
<message>
<source>Fullcoin Core</source>
<translation>Fullcoin Core</translation>
</message>
<message>
<source>Error</source>
<translation>Памылка</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>Адкрыць URI</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Опцыі</translation>
</message>
<message>
<source>MB</source>
<translation>Мб</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Форма</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Колькасць</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Label:</source>
<translation>Метка:</translation>
</message>
<message>
<source>Copy label</source>
<translation>Капіяваць пазнаку</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Капіяваць колькасць</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>Адрас</translation>
</message>
<message>
<source>Amount</source>
<translation>Колькасць</translation>
</message>
<message>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<source>Message</source>
<translation>Паведамленне</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<source>Message</source>
<translation>Паведамленне</translation>
</message>
<message>
<source>Amount</source>
<translation>Колькасць</translation>
</message>
<message>
<source>(no label)</source>
<translation>непазначаны</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Даслаць Манеты</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Колькасць:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Байтаў:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Колькасць:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Прыярытэт:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Камісія:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Пасля камісіі:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Даслаць адразу некалькім атрымальнікам</translation>
</message>
<message>
<source>Dust:</source>
<translation>Пыл:</translation>
</message>
<message>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Пацвердзіць дасыланне</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Пацвердзіць дасыланне манет</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Капіяваць колькасць</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Капіяваць колькасць</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Капіяваць камісію</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Капіяваць з выняткам камісіі</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Капіяваць байты</translation>
</message>
<message>
<source>Copy priority</source>
<translation>Капіяваць прыярытэт</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>Велічыня плацяжу мае быць больш за 0.</translation>
</message>
<message>
<source>(no label)</source>
<translation>непазначаны</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Капіяваць пыл</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Колькасць:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Заплаціць да:</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>Увядзіце пазнаку гэтаму адрасу, каб дадаць яго ў адрасную кнігу</translation>
</message>
<message>
<source>&Label:</source>
<translation>Метка:</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Уставіць адрас з буферу абмена</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Memo:</source>
<translation>Памятка:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Уставіць адрас з буферу абмена</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>Fullcoin Core</source>
<translation>Fullcoin Core</translation>
</message>
<message>
<source>The Bitcoin Core developers</source>
<translation>Распрацоўнікі Bitcoin Core</translation>
</message>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>Кб/с</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/непацверджана</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 пацверджанняў</translation>
</message>
<message>
<source>Status</source>
<translation>Статус</translation>
</message>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Message</source>
<translation>Паведамленне</translation>
</message>
<message>
<source>Comment</source>
<translation>Каментар</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID</translation>
</message>
<message>
<source>Amount</source>
<translation>Колькасць</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>, пакуль не было паспяхова транслявана</translation>
</message>
<message>
<source>unknown</source>
<translation>невядома</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>Дэталі транзакцыі</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Гэтая панэль паказвае дэтальнае апісанне транзакцыі</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Type</source>
<translation>Тып</translation>
</message>
<message>
<source>Address</source>
<translation>Адрас</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Пацверджана (%1 пацверджанняў)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Гэты блок не быў прыняты іншымі вузламі і магчыма не будзе ўхвалены!</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Згенеравана, але не прынята</translation>
</message>
<message>
<source>Received with</source>
<translation>Прынята з</translation>
</message>
<message>
<source>Received from</source>
<translation>Прынята ад</translation>
</message>
<message>
<source>Sent to</source>
<translation>Даслана да</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Плацёж самому сабе</translation>
</message>
<message>
<source>Mined</source>
<translation>Здабыта</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Статус транзакцыі. Навядзіце курсар на гэтае поле, каб паказаць колькасць пацверджанняў.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Дата і час, калі транзакцыя была прынята.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Тып транзакцыі</translation>
</message>
<message>
<source>Destination address of transaction.</source>
<translation>Адрас прызначэння транзакцыі.</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Колькасць аднятая ці даданая да балансу.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Усё</translation>
</message>
<message>
<source>Today</source>
<translation>Сёння</translation>
</message>
<message>
<source>This week</source>
<translation>Гэты тыдзень</translation>
</message>
<message>
<source>This month</source>
<translation>Гэты месяц</translation>
</message>
<message>
<source>Last month</source>
<translation>Мінулы месяц</translation>
</message>
<message>
<source>This year</source>
<translation>Гэты год</translation>
</message>
<message>
<source>Range...</source>
<translation>Прамежак...</translation>
</message>
<message>
<source>Received with</source>
<translation>Прынята з</translation>
</message>
<message>
<source>Sent to</source>
<translation>Даслана да</translation>
</message>
<message>
<source>To yourself</source>
<translation>Да сябе</translation>
</message>
<message>
<source>Mined</source>
<translation>Здабыта</translation>
</message>
<message>
<source>Other</source>
<translation>Іншыя</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Увядзіце адрас ці пазнаку для пошуку</translation>
</message>
<message>
<source>Min amount</source>
<translation>Мін. колькасць</translation>
</message>
<message>
<source>Copy address</source>
<translation>Капіяваць адрас</translation>
</message>
<message>
<source>Copy label</source>
<translation>Капіяваць пазнаку</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Капіяваць колькасць</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Капіяваць ID транзакцыі</translation>
</message>
<message>
<source>Edit label</source>
<translation>Рэдагаваць пазнаку</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Экспартаванне няўдалае</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Коскамі падзелены файл (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Пацверджана</translation>
</message>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Type</source>
<translation>Тып</translation>
</message>
<message>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<source>Address</source>
<translation>Адрас</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Range:</source>
<translation>Прамежак:</translation>
</message>
<message>
<source>to</source>
<translation>да</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Даслаць Манеты</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>Экспарт</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Экспартаваць гэтыя звесткі у файл</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Опцыі:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Вызначыць каталог даных</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Прымаць камандны радок і JSON-RPC каманды</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Запусціць у фоне як дэман і прымаць каманды</translation>
</message>
<message>
<source>Use the test network</source>
<translation>Ужываць тэставае сеціва</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Ці жадаеце вы перабудаваць зараз базу звестак блокаў?</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>Памылка ініцыялізацыі базвы звестак блокаў</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>Памалка ініцыялізацыі асяроддзя базы звестак гаманца %s!</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Памылка загрузкі базвы звестак блокаў</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Памылка адчынення базы звестак блокаў</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Памылка: Замала вольнага месца на дыску!</translation>
</message>
<message>
<source>Importing...</source>
<translation>Імпартаванне...</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>Не хапае файлавых дэскрыптараў.</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: %u)</source>
<translation>Use UPnP to map the listening port (default: %u)</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Праверка блокаў...</translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>Праверка гаманца...</translation>
</message>
<message>
<source>Wallet options:</source>
<translation>Опцыі гаманца:</translation>
</message>
<message>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Імпартаванне блокаў з вонкавага blk000??.dat файла</translation>
</message>
<message>
<source>Information</source>
<translation>Інфармацыя</translation>
</message>
<message>
<source>RPC server options:</source>
<translation>Опцыі RPC сервера:</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Слаць trace/debug звесткі ў кансоль замест файла debug.log</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Памылка подпісу транзакцыі</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>Гэта эксперыментальная праграма.</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Транзакцыя занадта малая</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Транзакцыя занадта вялікая</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Імя карыстальника для JSON-RPC злучэнняў</translation>
</message>
<message>
<source>Warning</source>
<translation>Увага</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Пароль для JSON-RPC злучэнняў</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Выканаць каманду калі лепшы блок зменіцца (%s замяняецца на хэш блока)</translation>
</message>
<message>
<source>Upgrade wallet to latest format</source>
<translation>Абнавіць гаманец на новы фармат</translation>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Перасканаваць ланцуг блокаў дзеля пошуку адсутных транзакцый</translation>
</message>
<message>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Ужываць OpenSSL (https) для JSON-RPC злучэнняў</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Загружаем адрасы...</translation>
</message>
<message>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Памылка загрузкі wallet.dat: гаманец пашкоджаны</translation>
</message>
<message>
<source>Error loading wallet.dat</source>
<translation>Памылка загрузкі wallet.dat</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Недастаткова сродкаў</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Загружаем індэкс блокаў...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Загружаем гаманец...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>Немагчыма рэгрэсаваць гаманец</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Перасканаванне...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Загрузка выканана</translation>
</message>
<message>
<source>Error</source>
<translation>Памылка</translation>
</message>
</context>
</TS>
| {
"content_hash": "53133bbb7f7eefc640f021a494fd80f1",
"timestamp": "",
"source": "github",
"line_count": 1498,
"max_line_length": 302,
"avg_line_length": 33.45594125500668,
"alnum_prop": 0.6411995929524912,
"repo_name": "fullcoins/fullcoin",
"id": "aa8e5f50f42a0e60066d1061841c6c36c25b3da2",
"size": "56849",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_be_BY.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "7639"
},
{
"name": "C",
"bytes": "320255"
},
{
"name": "C++",
"bytes": "3590528"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2100"
},
{
"name": "M4",
"bytes": "142321"
},
{
"name": "Makefile",
"bytes": "83376"
},
{
"name": "Objective-C",
"bytes": "3283"
},
{
"name": "Objective-C++",
"bytes": "7238"
},
{
"name": "Protocol Buffer",
"bytes": "2308"
},
{
"name": "Python",
"bytes": "221553"
},
{
"name": "QMake",
"bytes": "2019"
},
{
"name": "Roff",
"bytes": "18043"
},
{
"name": "Shell",
"bytes": "44913"
}
],
"symlink_target": ""
} |
CRC_VCNL4200::CRC_VCNL4200() {
_i2caddr = VCNL4200_I2CADDR;
}
boolean CRC_VCNL4200::exists() {
Wire.begin();
uint8_t rev = 0;
Wire.beginTransmission(_i2caddr);
Wire.write(VCNL4200_DeviceID_REG);
Wire.endTransmission(false);
Wire.requestFrom(_i2caddr, uint8_t(2));
byte lowByte = Wire.read();
byte highByte = Wire.read();
//Strange that highByte returns 0x10 while documentation says it should return 0x01
if ((lowByte == 0x58) && (highByte == 0x10)) {
return true;
}
return false;
}
boolean CRC_VCNL4200::initialize() {
set_ALS_CONF();
set_PS_CONF1_CONF2();
set_PS_CONF3_MS();
//Set the PS interrupt levels
write16_LowHigh(VCNL4200_PS_THDL_REG, B10001000, B00010011);
write16_LowHigh(VCNL4200_PS_THDH_REG, B11100000, B00101110);
return true;
}
boolean CRC_VCNL4200::set_ALS_CONF(uint8_t settingTotal) {
write16_LowHigh(VCNL4200_ALS_CONF_REG, settingTotal, B00000000);
return true;
}
boolean CRC_VCNL4200::set_PS_CONF1_CONF2(uint8_t conf1, uint8_t conf2) {
write16_LowHigh(VCNL4200_PS_CONF1_CONF2_REG, conf1, conf2);
return true;
}
boolean CRC_VCNL4200::set_PS_CONF3_MS(uint8_t conf3, uint8_t ms) {
Serial.print("Conf3, MS:");
Serial.print(conf3);
Serial.print(", ");
Serial.println(ms);
write16_LowHigh(VCNL4200_PS_CONF3_MS_REG, conf3, ms);
return true;
}
uint16_t CRC_VCNL4200::getProximity() {
return readData(VCNL4200_PROXIMITY_REG);
}
uint16_t CRC_VCNL4200::getProxLowInterrupt() {
return readData(VCNL4200_PS_THDL_REG);
}
uint16_t CRC_VCNL4200::getProxHighInterrupt() {
return readData(VCNL4200_PS_THDH_REG);
}
uint8_t CRC_VCNL4200::getInterruptFlag() {
uint8_t reading;
reading = readData(VCNL4200_INT_FLAG_REG);
return reading;
}
uint16_t CRC_VCNL4200::getAmbient() {
return readData(VCNL4200_AMBIENT_REG);
}
uint16_t CRC_VCNL4200::readData(uint8_t command_code)
{
uint16_t reading;
Wire.beginTransmission(_i2caddr);
Wire.write(command_code);
Wire.endTransmission(false);
Wire.requestFrom(_i2caddr, uint8_t(2));
while (!Wire.available());
uint8_t byteLow = Wire.read();
while (!Wire.available());
uint16_t byteHigh = Wire.read();
reading = (byteHigh <<= 8) + byteLow;
return reading;
}
void CRC_VCNL4200::write8(uint8_t address, uint8_t data) //Original
{
Wire.beginTransmission(_i2caddr);
Wire.write(address);
Wire.write(data);
Wire.endTransmission();
}
uint8_t CRC_VCNL4200::write16_LowHigh(uint8_t address, uint8_t low, uint8_t high)
{
Wire.beginTransmission(_i2caddr);
Wire.write(address);
Wire.write(low);
Wire.write(high);
Wire.endTransmission();
}
| {
"content_hash": "70e849c43afafcb677b3de35dd31ef50",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 84,
"avg_line_length": 24.39423076923077,
"alnum_prop": 0.7229010642491132,
"repo_name": "ChicagoRobotics/CRC_VCNL4200",
"id": "88702b8cc0ee6a65d8226e104f18cbc7417bbed5",
"size": "2658",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/CRC_VCNL4200.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "5064"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<localEntry xmlns="http://ws.apache.org/ns/synapse" key="server-policy">
<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
wsu:Id="UTOverTransport">
<wsp:ExactlyOne>
<wsp:All>
<sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:TransportToken>
<wsp:Policy>
<sp:HttpsToken RequireClientCertificate="true"/>
</wsp:Policy>
</sp:TransportToken>
<sp:AlgorithmSuite>
<wsp:Policy>
<sp:Basic256/>
</wsp:Policy>
</sp:AlgorithmSuite>
<sp:Layout>
<wsp:Policy>
<sp:Lax/>
</wsp:Policy>
</sp:Layout>
</wsp:Policy>
</sp:TransportBinding>
<rampart:RampartConfig xmlns:rampart="http://ws.apache.org/rampart/policy">
<rampart:encryptionUser>useReqSigCert</rampart:encryptionUser>
<rampart:timestampPrecisionInMilliseconds>true</rampart:timestampPrecisionInMilliseconds>
<rampart:timestampTTL>300</rampart:timestampTTL>
<rampart:timestampMaxSkew>300</rampart:timestampMaxSkew>
<rampart:tokenStoreClass>org.wso2.carbon.security.util.SecurityTokenStore</rampart:tokenStoreClass>
<rampart:nonceLifeTime>300</rampart:nonceLifeTime>
</rampart:RampartConfig>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
<description/>
</localEntry>
| {
"content_hash": "32cbcfd9c5668fa4360d1e34f81be6b6",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 114,
"avg_line_length": 47.51282051282051,
"alnum_prop": 0.5509983810037776,
"repo_name": "pubudup/wso2-qa-artifacts",
"id": "d8ae8437628a585ce252c21033b6a54c61612b2c",
"size": "1853",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "products/wso2_ESB/product_features/features/proxy_services/secure_proxy/secure_with_localentry_policy/server-policy.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "62"
},
{
"name": "CSS",
"bytes": "44042"
},
{
"name": "HTML",
"bytes": "1223168"
},
{
"name": "Java",
"bytes": "4296085"
},
{
"name": "Python",
"bytes": "8"
},
{
"name": "Roff",
"bytes": "1360"
},
{
"name": "Ruby",
"bytes": "8"
},
{
"name": "Shell",
"bytes": "118670"
},
{
"name": "XQuery",
"bytes": "8"
},
{
"name": "XSLT",
"bytes": "57004"
}
],
"symlink_target": ""
} |
package ca.uhn.fhir.rest.server.interceptor.auth;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.IQueryParameterOr;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.annotation.Transaction;
import ca.uhn.fhir.rest.annotation.TransactionParam;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.gclient.ICriterion;
import ca.uhn.fhir.rest.gclient.TokenClientParam;
import ca.uhn.fhir.rest.param.BaseAndListParam;
import ca.uhn.fhir.rest.param.ReferenceAndListParam;
import ca.uhn.fhir.rest.param.StringAndListParam;
import ca.uhn.fhir.rest.param.TokenAndListParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.TokenParamModifier;
import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider;
import ca.uhn.fhir.rest.server.IResourceProvider;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.exceptions.ForbiddenOperationException;
import ca.uhn.fhir.test.utilities.JettyUtil;
import ca.uhn.fhir.util.TestUtil;
import ca.uhn.fhir.util.UrlUtil;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hamcrest.Matchers;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Observation;
import org.hl7.fhir.r4.model.Patient;
import org.hl7.fhir.r4.model.Resource;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static ca.uhn.fhir.util.UrlUtil.escapeUrlParam;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
public class SearchNarrowingInterceptorTest {
private static final Logger ourLog = LoggerFactory.getLogger(SearchNarrowingInterceptorTest.class);
private static String ourLastHitMethod;
private static FhirContext ourCtx;
private static TokenAndListParam ourLastIdParam;
private static TokenAndListParam ourLastCodeParam;
private static ReferenceAndListParam ourLastSubjectParam;
private static ReferenceAndListParam ourLastPatientParam;
private static ReferenceAndListParam ourLastPerformerParam;
private static StringAndListParam ourLastNameParam;
private static List<Resource> ourReturn;
private static Server ourServer;
private static IGenericClient ourClient;
private static AuthorizedList ourNextAuthorizedList;
private static Bundle.BundleEntryRequestComponent ourLastBundleRequest;
@BeforeEach
public void before() {
ourLastHitMethod = null;
ourReturn = Collections.emptyList();
ourLastIdParam = null;
ourLastNameParam = null;
ourLastSubjectParam = null;
ourLastPatientParam = null;
ourLastPerformerParam = null;
ourLastCodeParam = null;
ourNextAuthorizedList = null;
}
@Test
public void testReturnNull() {
ourNextAuthorizedList = null;
ourClient
.search()
.forResource("Patient")
.execute();
assertEquals("Patient.search", ourLastHitMethod);
assertNull(ourLastCodeParam);
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertNull(ourLastPatientParam);
assertNull(ourLastIdParam);
}
@Test
public void testNarrowCode_NotInSelected_ClientRequestedNoParams() {
ourNextAuthorizedList = new AuthorizedList()
.addCodeNotInValueSet("Observation", "code", "http://myvs");
ourClient
.search()
.forResource("Observation")
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertEquals(1, ourLastCodeParam.size());
assertEquals(1, ourLastCodeParam.getValuesAsQueryTokens().get(0).size());
assertEquals(TokenParamModifier.NOT_IN, ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getModifier());
assertEquals("http://myvs", ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue());
assertEquals(null, ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getSystem());
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertNull(ourLastPatientParam);
assertNull(ourLastIdParam);
}
@Test
public void testNarrowCode_InSelected_ClientRequestedNoParams() {
ourNextAuthorizedList = new AuthorizedList()
.addCodeInValueSet("Observation", "code", "http://myvs");
ourClient
.search()
.forResource("Observation")
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertEquals(1, ourLastCodeParam.size());
assertEquals(1, ourLastCodeParam.getValuesAsQueryTokens().get(0).size());
assertEquals(TokenParamModifier.IN, ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getModifier());
assertEquals("http://myvs", ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue());
assertEquals(null, ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getSystem());
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertNull(ourLastPatientParam);
assertNull(ourLastIdParam);
}
@Test
public void testNarrowCode_InSelected_ClientRequestedBundleWithNoParams() {
ourNextAuthorizedList = new AuthorizedList()
.addCodeInValueSet("Observation", "code", "http://myvs");
Bundle bundle = new Bundle();
bundle.setType(Bundle.BundleType.TRANSACTION);
bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.GET).setUrl("Observation?subject=Patient/123");
ourLog.info(ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle));
ourClient
.transaction()
.withBundle(bundle)
.execute();
assertEquals("transaction", ourLastHitMethod);
String expectedUrl = "Observation?" +
escapeUrlParam("code:in") +
"=" +
escapeUrlParam("http://myvs") +
"&subject=" +
escapeUrlParam("Patient/123");
assertEquals(expectedUrl, ourLastBundleRequest.getUrl());
}
@Test
public void testNarrowCode_InSelected_ClientRequestedOtherInParam() {
ourNextAuthorizedList = new AuthorizedList()
.addCodeInValueSet("Observation", "code", "http://myvs");
ourClient.registerInterceptor(new LoggingInterceptor(false));
ourClient
.search()
.forResource("Observation")
.where(singletonMap("code", singletonList(new TokenParam("http://othervs").setModifier(TokenParamModifier.IN))))
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertEquals(2, ourLastCodeParam.size());
assertEquals(1, ourLastCodeParam.getValuesAsQueryTokens().get(0).size());
assertEquals(TokenParamModifier.IN, ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getModifier());
assertEquals("http://othervs", ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getValue());
assertEquals(null, ourLastCodeParam.getValuesAsQueryTokens().get(0).getValuesAsQueryTokens().get(0).getSystem());
assertEquals(1, ourLastCodeParam.getValuesAsQueryTokens().get(1).size());
assertEquals(TokenParamModifier.IN, ourLastCodeParam.getValuesAsQueryTokens().get(1).getValuesAsQueryTokens().get(0).getModifier());
assertEquals("http://myvs", ourLastCodeParam.getValuesAsQueryTokens().get(1).getValuesAsQueryTokens().get(0).getValue());
assertEquals(null, ourLastCodeParam.getValuesAsQueryTokens().get(1).getValuesAsQueryTokens().get(0).getSystem());
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertNull(ourLastPatientParam);
assertNull(ourLastIdParam);
}
@Test
public void testNarrowCode_InSelected_DifferentResource() {
ourNextAuthorizedList = new AuthorizedList()
.addCodeInValueSet("Procedure", "code", "http://myvs");
ourClient
.search()
.forResource("Observation")
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertEquals(null, ourLastCodeParam);
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedNoParams() {
ourNextAuthorizedList = new AuthorizedList()
.addCompartments("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Observation")
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertNull(ourLastIdParam);
assertNull(ourLastCodeParam);
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertThat(toStrings(ourLastPatientParam), Matchers.contains("Patient/123,Patient/456"));
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedBundleNoParams() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
Bundle bundle = new Bundle();
bundle.setType(Bundle.BundleType.TRANSACTION);
bundle.addEntry().getRequest().setMethod(Bundle.HTTPVerb.GET).setUrl("Patient");
ourLog.info(ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle));
ourClient
.transaction()
.withBundle(bundle)
.execute();
assertEquals("transaction", ourLastHitMethod);
assertEquals("Patient?_id=" + URLEncoder.encode("Patient/123,Patient/456"), ourLastBundleRequest.getUrl());
}
@Test
public void testNarrowCompartment_PatientByPatientContext_ClientRequestedNoParams() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Patient")
.execute();
assertEquals("Patient.search", ourLastHitMethod);
assertNull(ourLastNameParam);
assertThat(toStrings(ourLastIdParam), Matchers.contains("Patient/123,Patient/456"));
}
@Test
public void testNarrowCompartment_PatientByPatientContext_ClientRequestedSomeOverlap() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Patient")
.where(IAnyResource.RES_ID.exactly().codes("Patient/123", "Patient/999"))
.execute();
assertEquals("Patient.search", ourLastHitMethod);
assertNull(ourLastNameParam);
assertThat(toStrings(ourLastIdParam), Matchers.contains("Patient/123"));
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedSomeOverlap() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Observation")
.where(Observation.PATIENT.hasAnyOfIds("Patient/456", "Patient/777"))
.and(Observation.PATIENT.hasAnyOfIds("Patient/456", "Patient/888"))
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertNull(ourLastIdParam);
assertNull(ourLastCodeParam);
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertThat(toStrings(ourLastPatientParam), Matchers.contains("Patient/456", "Patient/456"));
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedSomeOverlap_ShortIds() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Observation")
.where(Observation.PATIENT.hasAnyOfIds("456", "777"))
.and(Observation.PATIENT.hasAnyOfIds("456", "888"))
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertNull(ourLastIdParam);
assertNull(ourLastCodeParam);
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertThat(toStrings(ourLastPatientParam), Matchers.contains("456", "456"));
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedSomeOverlap_UseSynonym() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Observation")
.where(Observation.SUBJECT.hasAnyOfIds("Patient/456", "Patient/777"))
.and(Observation.SUBJECT.hasAnyOfIds("Patient/456", "Patient/888"))
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertNull(ourLastIdParam);
assertNull(ourLastCodeParam);
assertThat(toStrings(ourLastSubjectParam), Matchers.contains("Patient/456", "Patient/456"));
assertNull(ourLastPerformerParam);
assertNull(ourLastPatientParam);
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedNoOverlap() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
try {
ourClient
.search()
.forResource("Observation")
.where(Observation.PATIENT.hasAnyOfIds("Patient/111", "Patient/777"))
.and(Observation.PATIENT.hasAnyOfIds("Patient/111", "Patient/888"))
.execute();
fail("Expected a 403 error");
} catch (ForbiddenOperationException e) {
assertEquals(Constants.STATUS_HTTP_403_FORBIDDEN, e.getStatusCode());
}
assertNull(ourLastHitMethod);
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedNoOverlap_UseSynonym() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
try {
ourClient
.search()
.forResource("Observation")
.where(Observation.SUBJECT.hasAnyOfIds("Patient/111", "Patient/777"))
.and(Observation.SUBJECT.hasAnyOfIds("Patient/111", "Patient/888"))
.execute();
fail("Expected a 403 error");
} catch (ForbiddenOperationException e) {
assertEquals(Constants.STATUS_HTTP_403_FORBIDDEN, e.getStatusCode());
}
assertNull(ourLastHitMethod);
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedBadParameter() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/123", "Patient/456");
try {
ourClient
.search()
.forResource("Observation")
.where(Observation.PATIENT.hasAnyOfIds("Patient/"))
.execute();
fail("Expected a 403 error");
} catch (ForbiddenOperationException e) {
assertEquals(Constants.STATUS_HTTP_403_FORBIDDEN, e.getStatusCode());
}
assertNull(ourLastHitMethod);
}
@Test
public void testNarrowCompartment_ObservationsByPatientContext_ClientRequestedBadPermission() {
ourNextAuthorizedList = new AuthorizedList().addCompartments("Patient/");
try {
ourClient
.search()
.forResource("Observation")
.where(Observation.PATIENT.hasAnyOfIds("Patient/111", "Patient/777"))
.execute();
fail("Expected a 403 error");
} catch (ForbiddenOperationException e) {
assertEquals(Constants.STATUS_HTTP_403_FORBIDDEN, e.getStatusCode());
}
assertNull(ourLastHitMethod);
}
/**
* Should not make any changes
*/
@Test
public void testNarrowResources_ObservationsByPatientResources_ClientRequestedNoParams() {
ourNextAuthorizedList = new AuthorizedList()
.addResources("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Observation")
.execute();
assertEquals("Observation.search", ourLastHitMethod);
assertNull(ourLastIdParam);
assertNull(ourLastCodeParam);
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertNull(ourLastPatientParam);
}
@Test
public void testNarrowResources_PatientByPatientResources_ClientRequestedNoParams() {
ourNextAuthorizedList = new AuthorizedList()
.addResources("Patient/123", "Patient/456");
ourClient
.search()
.forResource("Patient")
.execute();
assertEquals("Patient.search", ourLastHitMethod);
assertNull(ourLastCodeParam);
assertNull(ourLastSubjectParam);
assertNull(ourLastPerformerParam);
assertNull(ourLastPatientParam);
assertThat(toStrings(ourLastIdParam), Matchers.contains("Patient/123,Patient/456"));
}
private List<String> toStrings(BaseAndListParam<? extends IQueryParameterOr<?>> theParams) {
List<? extends IQueryParameterOr<? extends IQueryParameterType>> valuesAsQueryTokens = theParams.getValuesAsQueryTokens();
return valuesAsQueryTokens
.stream()
.map(IQueryParameterOr::getValuesAsQueryTokens)
.map(t -> t
.stream()
.map(j -> j.getValueAsQueryToken(ourCtx))
.collect(Collectors.joining(",")))
.collect(Collectors.toList());
}
public static class DummyPatientResourceProvider implements IResourceProvider {
@Override
public Class<? extends IBaseResource> getResourceType() {
return Patient.class;
}
@Search()
public List<Resource> search(
@OptionalParam(name = "_id") TokenAndListParam theIdParam,
@OptionalParam(name = "name") StringAndListParam theNameParam
) {
ourLastHitMethod = "Patient.search";
ourLastIdParam = theIdParam;
ourLastNameParam = theNameParam;
return ourReturn;
}
}
public static class DummyObservationResourceProvider implements IResourceProvider {
@Override
public Class<? extends IBaseResource> getResourceType() {
return Observation.class;
}
@Search()
public List<Resource> search(
@OptionalParam(name = "_id") TokenAndListParam theIdParam,
@OptionalParam(name = Observation.SP_SUBJECT) ReferenceAndListParam theSubjectParam,
@OptionalParam(name = Observation.SP_PATIENT) ReferenceAndListParam thePatientParam,
@OptionalParam(name = Observation.SP_PERFORMER) ReferenceAndListParam thePerformerParam,
@OptionalParam(name = Observation.SP_CODE) TokenAndListParam theCodeParam
) {
ourLastHitMethod = "Observation.search";
ourLastIdParam = theIdParam;
ourLastSubjectParam = theSubjectParam;
ourLastPatientParam = thePatientParam;
ourLastPerformerParam = thePerformerParam;
ourLastCodeParam = theCodeParam;
return ourReturn;
}
}
public static class DummySystemProvider {
@Transaction
public Bundle transaction(@TransactionParam Bundle theInput) {
ourLastHitMethod = "transaction";
ourLastBundleRequest = theInput.getEntry().get(0).getRequest();
return theInput;
}
}
private static class MySearchNarrowingInterceptor extends SearchNarrowingInterceptor {
@Override
protected AuthorizedList buildAuthorizedList(RequestDetails theRequestDetails) {
if (ourNextAuthorizedList == null) {
return null;
}
return ourNextAuthorizedList;
}
}
@AfterAll
public static void afterClassClearContext() throws Exception {
JettyUtil.closeServer(ourServer);
TestUtil.randomizeLocaleAndTimezone();
}
@BeforeAll
public static void beforeClass() throws Exception {
ourCtx = FhirContext.forR4();
ourServer = new Server(0);
DummyPatientResourceProvider patProvider = new DummyPatientResourceProvider();
DummyObservationResourceProvider obsProv = new DummyObservationResourceProvider();
DummySystemProvider systemProv = new DummySystemProvider();
ServletHandler proxyHandler = new ServletHandler();
RestfulServer ourServlet = new RestfulServer(ourCtx);
ourServlet.setFhirContext(ourCtx);
ourServlet.registerProviders(systemProv);
ourServlet.setResourceProviders(patProvider, obsProv);
ourServlet.setPagingProvider(new FifoMemoryPagingProvider(100));
ourServlet.registerInterceptor(new MySearchNarrowingInterceptor());
ServletHolder servletHolder = new ServletHolder(ourServlet);
proxyHandler.addServletWithMapping(servletHolder, "/*");
ourServer.setHandler(proxyHandler);
JettyUtil.startServer(ourServer);
int ourPort = JettyUtil.getPortForStartedServer(ourServer);
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
ourCtx.getRestfulClientFactory().setSocketTimeout(1000000);
ourClient = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort);
}
}
| {
"content_hash": "7a65fd30abc1945a09218a123fc32d7f",
"timestamp": "",
"source": "github",
"line_count": 587,
"max_line_length": 138,
"avg_line_length": 34.369676320272575,
"alnum_prop": 0.7759603469640645,
"repo_name": "aemay2/hapi-fhir",
"id": "9c1413a3ad8962d8bb3ab8f4a1c8ff963a7fcebf",
"size": "20175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hapi-fhir-structures-r4/src/test/java/ca/uhn/fhir/rest/server/interceptor/auth/SearchNarrowingInterceptorTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3861"
},
{
"name": "CSS",
"bytes": "9608"
},
{
"name": "HTML",
"bytes": "213468"
},
{
"name": "Java",
"bytes": "25723741"
},
{
"name": "JavaScript",
"bytes": "31583"
},
{
"name": "Kotlin",
"bytes": "3951"
},
{
"name": "Ruby",
"bytes": "230677"
},
{
"name": "Shell",
"bytes": "46167"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/adamrees89/PythonExcelReader) [](https://snyk.io/test/github/adamrees89/PythonExcelReader?targetFile=requirements.txt)
[](https://coveralls.io/github/adamrees89/PythonExcelReader?branch=master)
Python scripts to read an excel file and print the contents to a SQLlite3 database. Future work involves re-writing that excel file elsewhere
## templateReader.py
Reads an excel file, then creates an SQLlite3 database with the values and formatting
## CreateSSExcelDoc.py
This crates an excel document based on the database created by templateReader.py
| {
"content_hash": "4ed74b350302508f8c0f0279e388875f",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 348,
"avg_line_length": 74.08333333333333,
"alnum_prop": 0.8155230596175478,
"repo_name": "adamrees89/PythonExcelReader",
"id": "d448e195d1986e18a72e8e4f1df6eb343fea9742",
"size": "909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "4936"
}
],
"symlink_target": ""
} |
#include "test.h"
__FBSDID("$FreeBSD$");
#define should(__a, __code, __m, __o, __v) \
assertEqualInt(__code, archive_write_set_option(__a, __m, __o, __v))
static void
test(int pristine)
{
struct archive* a = archive_write_new();
int known_option_rv = pristine ? ARCHIVE_FAILED : ARCHIVE_OK;
if (!pristine) {
archive_write_add_filter_gzip(a);
archive_write_set_format_iso9660(a);
}
/* NULL and "" denote `no option', so they're ok no matter
* what, if any, formats are registered */
should(a, ARCHIVE_OK, NULL, NULL, NULL);
should(a, ARCHIVE_OK, "", "", "");
/* unknown modules and options */
should(a, ARCHIVE_FAILED, "fubar", "snafu", NULL);
should(a, ARCHIVE_FAILED, "fubar", "snafu", "betcha");
/* unknown modules and options */
should(a, ARCHIVE_FAILED, NULL, "snafu", NULL);
should(a, ARCHIVE_FAILED, NULL, "snafu", "betcha");
/* ARCHIVE_OK with iso9660 loaded, ARCHIVE_WARN otherwise */
should(a, known_option_rv, "iso9660", "joliet", NULL);
should(a, known_option_rv, "iso9660", "joliet", NULL);
should(a, known_option_rv, NULL, "joliet", NULL);
should(a, known_option_rv, NULL, "joliet", NULL);
archive_write_free(a);
}
DEFINE_TEST(test_archive_write_set_option)
{
test(1);
test(0);
}
| {
"content_hash": "8bc93dac441f5db380abef7d902d5c46",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 68,
"avg_line_length": 26.91304347826087,
"alnum_prop": 0.6470113085621971,
"repo_name": "IngwiePhoenix/d0p",
"id": "27782342f330d6b7b804117a68308123aae355a4",
"size": "2560",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "libarchive-3.1.2/libarchive/test/test_archive_write_set_option.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "13989"
},
{
"name": "Awk",
"bytes": "21380"
},
{
"name": "C",
"bytes": "6566911"
},
{
"name": "C++",
"bytes": "325687"
},
{
"name": "Objective-C",
"bytes": "63515"
},
{
"name": "PHP",
"bytes": "3556"
},
{
"name": "Shell",
"bytes": "1313904"
}
],
"symlink_target": ""
} |
// Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
/* jshint maxstatements:2147483647 */
/* jshint esnext:true */
import * as XDR from 'js-xdr';
var types = XDR.config(xdr => {
// === xdr source ============================================================
//
// typedef opaque Value<>;
//
// ===========================================================================
xdr.typedef("Value", xdr.varOpaque());
// === xdr source ============================================================
//
// struct SCPBallot
// {
// uint32 counter; // n
// Value value; // x
// };
//
// ===========================================================================
xdr.struct("ScpBallot", [
["counter", xdr.lookup("Uint32")],
["value", xdr.lookup("Value")],
]);
// === xdr source ============================================================
//
// enum SCPStatementType
// {
// SCP_ST_PREPARE = 0,
// SCP_ST_CONFIRM = 1,
// SCP_ST_EXTERNALIZE = 2,
// SCP_ST_NOMINATE = 3
// };
//
// ===========================================================================
xdr.enum("ScpStatementType", {
scpStPrepare: 0,
scpStConfirm: 1,
scpStExternalize: 2,
scpStNominate: 3,
});
// === xdr source ============================================================
//
// struct SCPNomination
// {
// Hash quorumSetHash; // D
// Value votes<>; // X
// Value accepted<>; // Y
// };
//
// ===========================================================================
xdr.struct("ScpNomination", [
["quorumSetHash", xdr.lookup("Hash")],
["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)],
["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)],
]);
// === xdr source ============================================================
//
// struct
// {
// Hash quorumSetHash; // D
// SCPBallot ballot; // b
// SCPBallot* prepared; // p
// SCPBallot* preparedPrime; // p'
// uint32 nC; // c.n
// uint32 nH; // h.n
// }
//
// ===========================================================================
xdr.struct("ScpStatementPrepare", [
["quorumSetHash", xdr.lookup("Hash")],
["ballot", xdr.lookup("ScpBallot")],
["prepared", xdr.option(xdr.lookup("ScpBallot"))],
["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))],
["nC", xdr.lookup("Uint32")],
["nH", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// struct
// {
// SCPBallot ballot; // b
// uint32 nPrepared; // p.n
// uint32 nCommit; // c.n
// uint32 nH; // h.n
// Hash quorumSetHash; // D
// }
//
// ===========================================================================
xdr.struct("ScpStatementConfirm", [
["ballot", xdr.lookup("ScpBallot")],
["nPrepared", xdr.lookup("Uint32")],
["nCommit", xdr.lookup("Uint32")],
["nH", xdr.lookup("Uint32")],
["quorumSetHash", xdr.lookup("Hash")],
]);
// === xdr source ============================================================
//
// struct
// {
// SCPBallot commit; // c
// uint32 nH; // h.n
// Hash commitQuorumSetHash; // D used before EXTERNALIZE
// }
//
// ===========================================================================
xdr.struct("ScpStatementExternalize", [
["commit", xdr.lookup("ScpBallot")],
["nH", xdr.lookup("Uint32")],
["commitQuorumSetHash", xdr.lookup("Hash")],
]);
// === xdr source ============================================================
//
// union switch (SCPStatementType type)
// {
// case SCP_ST_PREPARE:
// struct
// {
// Hash quorumSetHash; // D
// SCPBallot ballot; // b
// SCPBallot* prepared; // p
// SCPBallot* preparedPrime; // p'
// uint32 nC; // c.n
// uint32 nH; // h.n
// } prepare;
// case SCP_ST_CONFIRM:
// struct
// {
// SCPBallot ballot; // b
// uint32 nPrepared; // p.n
// uint32 nCommit; // c.n
// uint32 nH; // h.n
// Hash quorumSetHash; // D
// } confirm;
// case SCP_ST_EXTERNALIZE:
// struct
// {
// SCPBallot commit; // c
// uint32 nH; // h.n
// Hash commitQuorumSetHash; // D used before EXTERNALIZE
// } externalize;
// case SCP_ST_NOMINATE:
// SCPNomination nominate;
// }
//
// ===========================================================================
xdr.union("ScpStatementPledges", {
switchOn: xdr.lookup("ScpStatementType"),
switchName: "type",
switches: [
["scpStPrepare", "prepare"],
["scpStConfirm", "confirm"],
["scpStExternalize", "externalize"],
["scpStNominate", "nominate"],
],
arms: {
prepare: xdr.lookup("ScpStatementPrepare"),
confirm: xdr.lookup("ScpStatementConfirm"),
externalize: xdr.lookup("ScpStatementExternalize"),
nominate: xdr.lookup("ScpNomination"),
},
});
// === xdr source ============================================================
//
// struct SCPStatement
// {
// NodeID nodeID; // v
// uint64 slotIndex; // i
//
// union switch (SCPStatementType type)
// {
// case SCP_ST_PREPARE:
// struct
// {
// Hash quorumSetHash; // D
// SCPBallot ballot; // b
// SCPBallot* prepared; // p
// SCPBallot* preparedPrime; // p'
// uint32 nC; // c.n
// uint32 nH; // h.n
// } prepare;
// case SCP_ST_CONFIRM:
// struct
// {
// SCPBallot ballot; // b
// uint32 nPrepared; // p.n
// uint32 nCommit; // c.n
// uint32 nH; // h.n
// Hash quorumSetHash; // D
// } confirm;
// case SCP_ST_EXTERNALIZE:
// struct
// {
// SCPBallot commit; // c
// uint32 nH; // h.n
// Hash commitQuorumSetHash; // D used before EXTERNALIZE
// } externalize;
// case SCP_ST_NOMINATE:
// SCPNomination nominate;
// }
// pledges;
// };
//
// ===========================================================================
xdr.struct("ScpStatement", [
["nodeId", xdr.lookup("NodeId")],
["slotIndex", xdr.lookup("Uint64")],
["pledges", xdr.lookup("ScpStatementPledges")],
]);
// === xdr source ============================================================
//
// struct SCPEnvelope
// {
// SCPStatement statement;
// Signature signature;
// };
//
// ===========================================================================
xdr.struct("ScpEnvelope", [
["statement", xdr.lookup("ScpStatement")],
["signature", xdr.lookup("Signature")],
]);
// === xdr source ============================================================
//
// struct SCPQuorumSet
// {
// uint32 threshold;
// NodeID validators<>;
// SCPQuorumSet innerSets<>;
// };
//
// ===========================================================================
xdr.struct("ScpQuorumSet", [
["threshold", xdr.lookup("Uint32")],
["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)],
["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)],
]);
// === xdr source ============================================================
//
// typedef PublicKey AccountID;
//
// ===========================================================================
xdr.typedef("AccountId", xdr.lookup("PublicKey"));
// === xdr source ============================================================
//
// typedef opaque Thresholds[4];
//
// ===========================================================================
xdr.typedef("Thresholds", xdr.opaque(4));
// === xdr source ============================================================
//
// typedef string string32<32>;
//
// ===========================================================================
xdr.typedef("String32", xdr.string(32));
// === xdr source ============================================================
//
// typedef string string64<64>;
//
// ===========================================================================
xdr.typedef("String64", xdr.string(64));
// === xdr source ============================================================
//
// typedef int64 SequenceNumber;
//
// ===========================================================================
xdr.typedef("SequenceNumber", xdr.lookup("Int64"));
// === xdr source ============================================================
//
// typedef uint64 TimePoint;
//
// ===========================================================================
xdr.typedef("TimePoint", xdr.lookup("Uint64"));
// === xdr source ============================================================
//
// typedef uint64 Duration;
//
// ===========================================================================
xdr.typedef("Duration", xdr.lookup("Uint64"));
// === xdr source ============================================================
//
// typedef opaque DataValue<64>;
//
// ===========================================================================
xdr.typedef("DataValue", xdr.varOpaque(64));
// === xdr source ============================================================
//
// typedef Hash PoolID;
//
// ===========================================================================
xdr.typedef("PoolId", xdr.lookup("Hash"));
// === xdr source ============================================================
//
// typedef opaque AssetCode4[4];
//
// ===========================================================================
xdr.typedef("AssetCode4", xdr.opaque(4));
// === xdr source ============================================================
//
// typedef opaque AssetCode12[12];
//
// ===========================================================================
xdr.typedef("AssetCode12", xdr.opaque(12));
// === xdr source ============================================================
//
// enum AssetType
// {
// ASSET_TYPE_NATIVE = 0,
// ASSET_TYPE_CREDIT_ALPHANUM4 = 1,
// ASSET_TYPE_CREDIT_ALPHANUM12 = 2,
// ASSET_TYPE_POOL_SHARE = 3
// };
//
// ===========================================================================
xdr.enum("AssetType", {
assetTypeNative: 0,
assetTypeCreditAlphanum4: 1,
assetTypeCreditAlphanum12: 2,
assetTypePoolShare: 3,
});
// === xdr source ============================================================
//
// union AssetCode switch (AssetType type)
// {
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AssetCode4 assetCode4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AssetCode12 assetCode12;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("AssetCode", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [
["assetTypeCreditAlphanum4", "assetCode4"],
["assetTypeCreditAlphanum12", "assetCode12"],
],
arms: {
assetCode4: xdr.lookup("AssetCode4"),
assetCode12: xdr.lookup("AssetCode12"),
},
});
// === xdr source ============================================================
//
// struct AlphaNum4
// {
// AssetCode4 assetCode;
// AccountID issuer;
// };
//
// ===========================================================================
xdr.struct("AlphaNum4", [
["assetCode", xdr.lookup("AssetCode4")],
["issuer", xdr.lookup("AccountId")],
]);
// === xdr source ============================================================
//
// struct AlphaNum12
// {
// AssetCode12 assetCode;
// AccountID issuer;
// };
//
// ===========================================================================
xdr.struct("AlphaNum12", [
["assetCode", xdr.lookup("AssetCode12")],
["issuer", xdr.lookup("AccountId")],
]);
// === xdr source ============================================================
//
// union Asset switch (AssetType type)
// {
// case ASSET_TYPE_NATIVE: // Not credit
// void;
//
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AlphaNum4 alphaNum4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AlphaNum12 alphaNum12;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("Asset", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [
["assetTypeNative", xdr.void()],
["assetTypeCreditAlphanum4", "alphaNum4"],
["assetTypeCreditAlphanum12", "alphaNum12"],
],
arms: {
alphaNum4: xdr.lookup("AlphaNum4"),
alphaNum12: xdr.lookup("AlphaNum12"),
},
});
// === xdr source ============================================================
//
// struct Price
// {
// int32 n; // numerator
// int32 d; // denominator
// };
//
// ===========================================================================
xdr.struct("Price", [
["n", xdr.lookup("Int32")],
["d", xdr.lookup("Int32")],
]);
// === xdr source ============================================================
//
// struct Liabilities
// {
// int64 buying;
// int64 selling;
// };
//
// ===========================================================================
xdr.struct("Liabilities", [
["buying", xdr.lookup("Int64")],
["selling", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// enum ThresholdIndexes
// {
// THRESHOLD_MASTER_WEIGHT = 0,
// THRESHOLD_LOW = 1,
// THRESHOLD_MED = 2,
// THRESHOLD_HIGH = 3
// };
//
// ===========================================================================
xdr.enum("ThresholdIndices", {
thresholdMasterWeight: 0,
thresholdLow: 1,
thresholdMed: 2,
thresholdHigh: 3,
});
// === xdr source ============================================================
//
// enum LedgerEntryType
// {
// ACCOUNT = 0,
// TRUSTLINE = 1,
// OFFER = 2,
// DATA = 3,
// CLAIMABLE_BALANCE = 4,
// LIQUIDITY_POOL = 5
// };
//
// ===========================================================================
xdr.enum("LedgerEntryType", {
account: 0,
trustline: 1,
offer: 2,
data: 3,
claimableBalance: 4,
liquidityPool: 5,
});
// === xdr source ============================================================
//
// struct Signer
// {
// SignerKey key;
// uint32 weight; // really only need 1 byte
// };
//
// ===========================================================================
xdr.struct("Signer", [
["key", xdr.lookup("SignerKey")],
["weight", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// enum AccountFlags
// { // masks for each flag
//
// // Flags set on issuer accounts
// // TrustLines are created with authorized set to "false" requiring
// // the issuer to set it for each TrustLine
// AUTH_REQUIRED_FLAG = 0x1,
// // If set, the authorized flag in TrustLines can be cleared
// // otherwise, authorization cannot be revoked
// AUTH_REVOCABLE_FLAG = 0x2,
// // Once set, causes all AUTH_* flags to be read-only
// AUTH_IMMUTABLE_FLAG = 0x4,
// // Trustlines are created with clawback enabled set to "true",
// // and claimable balances created from those trustlines are created
// // with clawback enabled set to "true"
// AUTH_CLAWBACK_ENABLED_FLAG = 0x8
// };
//
// ===========================================================================
xdr.enum("AccountFlags", {
authRequiredFlag: 1,
authRevocableFlag: 2,
authImmutableFlag: 4,
authClawbackEnabledFlag: 8,
});
// === xdr source ============================================================
//
// const MASK_ACCOUNT_FLAGS = 0x7;
//
// ===========================================================================
xdr.const("MASK_ACCOUNT_FLAGS", 0x7);
// === xdr source ============================================================
//
// const MASK_ACCOUNT_FLAGS_V17 = 0xF;
//
// ===========================================================================
xdr.const("MASK_ACCOUNT_FLAGS_V17", 0xF);
// === xdr source ============================================================
//
// const MAX_SIGNERS = 20;
//
// ===========================================================================
xdr.const("MAX_SIGNERS", 20);
// === xdr source ============================================================
//
// typedef AccountID* SponsorshipDescriptor;
//
// ===========================================================================
xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId")));
// === xdr source ============================================================
//
// struct AccountEntryExtensionV3
// {
// // We can use this to add more fields, or because it is first, to
// // change AccountEntryExtensionV3 into a union.
// ExtensionPoint ext;
//
// // Ledger number at which `seqNum` took on its present value.
// uint32 seqLedger;
//
// // Time at which `seqNum` took on its present value.
// TimePoint seqTime;
// };
//
// ===========================================================================
xdr.struct("AccountEntryExtensionV3", [
["ext", xdr.lookup("ExtensionPoint")],
["seqLedger", xdr.lookup("Uint32")],
["seqTime", xdr.lookup("TimePoint")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 3:
// AccountEntryExtensionV3 v3;
// }
//
// ===========================================================================
xdr.union("AccountEntryExtensionV2Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[3, "v3"],
],
arms: {
v3: xdr.lookup("AccountEntryExtensionV3"),
},
});
// === xdr source ============================================================
//
// struct AccountEntryExtensionV2
// {
// uint32 numSponsored;
// uint32 numSponsoring;
// SponsorshipDescriptor signerSponsoringIDs<MAX_SIGNERS>;
//
// union switch (int v)
// {
// case 0:
// void;
// case 3:
// AccountEntryExtensionV3 v3;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("AccountEntryExtensionV2", [
["numSponsored", xdr.lookup("Uint32")],
["numSponsoring", xdr.lookup("Uint32")],
["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))],
["ext", xdr.lookup("AccountEntryExtensionV2Ext")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// AccountEntryExtensionV2 v2;
// }
//
// ===========================================================================
xdr.union("AccountEntryExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[2, "v2"],
],
arms: {
v2: xdr.lookup("AccountEntryExtensionV2"),
},
});
// === xdr source ============================================================
//
// struct AccountEntryExtensionV1
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// AccountEntryExtensionV2 v2;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("AccountEntryExtensionV1", [
["liabilities", xdr.lookup("Liabilities")],
["ext", xdr.lookup("AccountEntryExtensionV1Ext")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// AccountEntryExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("AccountEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[1, "v1"],
],
arms: {
v1: xdr.lookup("AccountEntryExtensionV1"),
},
});
// === xdr source ============================================================
//
// struct AccountEntry
// {
// AccountID accountID; // master public key for this account
// int64 balance; // in stroops
// SequenceNumber seqNum; // last sequence number used for this account
// uint32 numSubEntries; // number of sub-entries this account has
// // drives the reserve
// AccountID* inflationDest; // Account to vote for during inflation
// uint32 flags; // see AccountFlags
//
// string32 homeDomain; // can be used for reverse federation and memo lookup
//
// // fields used for signatures
// // thresholds stores unsigned bytes: [weight of master|low|medium|high]
// Thresholds thresholds;
//
// Signer signers<MAX_SIGNERS>; // possible signers for this account
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// AccountEntryExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("AccountEntry", [
["accountId", xdr.lookup("AccountId")],
["balance", xdr.lookup("Int64")],
["seqNum", xdr.lookup("SequenceNumber")],
["numSubEntries", xdr.lookup("Uint32")],
["inflationDest", xdr.option(xdr.lookup("AccountId"))],
["flags", xdr.lookup("Uint32")],
["homeDomain", xdr.lookup("String32")],
["thresholds", xdr.lookup("Thresholds")],
["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))],
["ext", xdr.lookup("AccountEntryExt")],
]);
// === xdr source ============================================================
//
// enum TrustLineFlags
// {
// // issuer has authorized account to perform transactions with its credit
// AUTHORIZED_FLAG = 1,
// // issuer has authorized account to maintain and reduce liabilities for its
// // credit
// AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2,
// // issuer has specified that it may clawback its credit, and that claimable
// // balances created with its credit may also be clawed back
// TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4
// };
//
// ===========================================================================
xdr.enum("TrustLineFlags", {
authorizedFlag: 1,
authorizedToMaintainLiabilitiesFlag: 2,
trustlineClawbackEnabledFlag: 4,
});
// === xdr source ============================================================
//
// const MASK_TRUSTLINE_FLAGS = 1;
//
// ===========================================================================
xdr.const("MASK_TRUSTLINE_FLAGS", 1);
// === xdr source ============================================================
//
// const MASK_TRUSTLINE_FLAGS_V13 = 3;
//
// ===========================================================================
xdr.const("MASK_TRUSTLINE_FLAGS_V13", 3);
// === xdr source ============================================================
//
// const MASK_TRUSTLINE_FLAGS_V17 = 7;
//
// ===========================================================================
xdr.const("MASK_TRUSTLINE_FLAGS_V17", 7);
// === xdr source ============================================================
//
// enum LiquidityPoolType
// {
// LIQUIDITY_POOL_CONSTANT_PRODUCT = 0
// };
//
// ===========================================================================
xdr.enum("LiquidityPoolType", {
liquidityPoolConstantProduct: 0,
});
// === xdr source ============================================================
//
// union TrustLineAsset switch (AssetType type)
// {
// case ASSET_TYPE_NATIVE: // Not credit
// void;
//
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AlphaNum4 alphaNum4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AlphaNum12 alphaNum12;
//
// case ASSET_TYPE_POOL_SHARE:
// PoolID liquidityPoolID;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("TrustLineAsset", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [
["assetTypeNative", xdr.void()],
["assetTypeCreditAlphanum4", "alphaNum4"],
["assetTypeCreditAlphanum12", "alphaNum12"],
["assetTypePoolShare", "liquidityPoolId"],
],
arms: {
alphaNum4: xdr.lookup("AlphaNum4"),
alphaNum12: xdr.lookup("AlphaNum12"),
liquidityPoolId: xdr.lookup("PoolId"),
},
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TrustLineEntryExtensionV2Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct TrustLineEntryExtensionV2
// {
// int32 liquidityPoolUseCount;
//
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TrustLineEntryExtensionV2", [
["liquidityPoolUseCount", xdr.lookup("Int32")],
["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
//
// ===========================================================================
xdr.union("TrustLineEntryV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[2, "v2"],
],
arms: {
v2: xdr.lookup("TrustLineEntryExtensionV2"),
},
});
// === xdr source ============================================================
//
// struct
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
// ext;
// }
//
// ===========================================================================
xdr.struct("TrustLineEntryV1", [
["liabilities", xdr.lookup("Liabilities")],
["ext", xdr.lookup("TrustLineEntryV1Ext")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// struct
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
// ext;
// } v1;
// }
//
// ===========================================================================
xdr.union("TrustLineEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[1, "v1"],
],
arms: {
v1: xdr.lookup("TrustLineEntryV1"),
},
});
// === xdr source ============================================================
//
// struct TrustLineEntry
// {
// AccountID accountID; // account this trustline belongs to
// TrustLineAsset asset; // type of asset (with issuer)
// int64 balance; // how much of this asset the user has.
// // Asset defines the unit for this;
//
// int64 limit; // balance cannot be above this
// uint32 flags; // see TrustLineFlags
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// struct
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
// ext;
// } v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TrustLineEntry", [
["accountId", xdr.lookup("AccountId")],
["asset", xdr.lookup("TrustLineAsset")],
["balance", xdr.lookup("Int64")],
["limit", xdr.lookup("Int64")],
["flags", xdr.lookup("Uint32")],
["ext", xdr.lookup("TrustLineEntryExt")],
]);
// === xdr source ============================================================
//
// enum OfferEntryFlags
// {
// // an offer with this flag will not act on and take a reverse offer of equal
// // price
// PASSIVE_FLAG = 1
// };
//
// ===========================================================================
xdr.enum("OfferEntryFlags", {
passiveFlag: 1,
});
// === xdr source ============================================================
//
// const MASK_OFFERENTRY_FLAGS = 1;
//
// ===========================================================================
xdr.const("MASK_OFFERENTRY_FLAGS", 1);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("OfferEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct OfferEntry
// {
// AccountID sellerID;
// int64 offerID;
// Asset selling; // A
// Asset buying; // B
// int64 amount; // amount of A
//
// /* price for this offer:
// price of A in terms of B
// price=AmountB/AmountA=priceNumerator/priceDenominator
// price is after fees
// */
// Price price;
// uint32 flags; // see OfferEntryFlags
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("OfferEntry", [
["sellerId", xdr.lookup("AccountId")],
["offerId", xdr.lookup("Int64")],
["selling", xdr.lookup("Asset")],
["buying", xdr.lookup("Asset")],
["amount", xdr.lookup("Int64")],
["price", xdr.lookup("Price")],
["flags", xdr.lookup("Uint32")],
["ext", xdr.lookup("OfferEntryExt")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("DataEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct DataEntry
// {
// AccountID accountID; // account this data belongs to
// string64 dataName;
// DataValue dataValue;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("DataEntry", [
["accountId", xdr.lookup("AccountId")],
["dataName", xdr.lookup("String64")],
["dataValue", xdr.lookup("DataValue")],
["ext", xdr.lookup("DataEntryExt")],
]);
// === xdr source ============================================================
//
// enum ClaimPredicateType
// {
// CLAIM_PREDICATE_UNCONDITIONAL = 0,
// CLAIM_PREDICATE_AND = 1,
// CLAIM_PREDICATE_OR = 2,
// CLAIM_PREDICATE_NOT = 3,
// CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4,
// CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5
// };
//
// ===========================================================================
xdr.enum("ClaimPredicateType", {
claimPredicateUnconditional: 0,
claimPredicateAnd: 1,
claimPredicateOr: 2,
claimPredicateNot: 3,
claimPredicateBeforeAbsoluteTime: 4,
claimPredicateBeforeRelativeTime: 5,
});
// === xdr source ============================================================
//
// union ClaimPredicate switch (ClaimPredicateType type)
// {
// case CLAIM_PREDICATE_UNCONDITIONAL:
// void;
// case CLAIM_PREDICATE_AND:
// ClaimPredicate andPredicates<2>;
// case CLAIM_PREDICATE_OR:
// ClaimPredicate orPredicates<2>;
// case CLAIM_PREDICATE_NOT:
// ClaimPredicate* notPredicate;
// case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME:
// int64 absBefore; // Predicate will be true if closeTime < absBefore
// case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME:
// int64 relBefore; // Seconds since closeTime of the ledger in which the
// // ClaimableBalanceEntry was created
// };
//
// ===========================================================================
xdr.union("ClaimPredicate", {
switchOn: xdr.lookup("ClaimPredicateType"),
switchName: "type",
switches: [
["claimPredicateUnconditional", xdr.void()],
["claimPredicateAnd", "andPredicates"],
["claimPredicateOr", "orPredicates"],
["claimPredicateNot", "notPredicate"],
["claimPredicateBeforeAbsoluteTime", "absBefore"],
["claimPredicateBeforeRelativeTime", "relBefore"],
],
arms: {
andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2),
orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2),
notPredicate: xdr.option(xdr.lookup("ClaimPredicate")),
absBefore: xdr.lookup("Int64"),
relBefore: xdr.lookup("Int64"),
},
});
// === xdr source ============================================================
//
// enum ClaimantType
// {
// CLAIMANT_TYPE_V0 = 0
// };
//
// ===========================================================================
xdr.enum("ClaimantType", {
claimantTypeV0: 0,
});
// === xdr source ============================================================
//
// struct
// {
// AccountID destination; // The account that can use this condition
// ClaimPredicate predicate; // Claimable if predicate is true
// }
//
// ===========================================================================
xdr.struct("ClaimantV0", [
["destination", xdr.lookup("AccountId")],
["predicate", xdr.lookup("ClaimPredicate")],
]);
// === xdr source ============================================================
//
// union Claimant switch (ClaimantType type)
// {
// case CLAIMANT_TYPE_V0:
// struct
// {
// AccountID destination; // The account that can use this condition
// ClaimPredicate predicate; // Claimable if predicate is true
// } v0;
// };
//
// ===========================================================================
xdr.union("Claimant", {
switchOn: xdr.lookup("ClaimantType"),
switchName: "type",
switches: [
["claimantTypeV0", "v0"],
],
arms: {
v0: xdr.lookup("ClaimantV0"),
},
});
// === xdr source ============================================================
//
// enum ClaimableBalanceIDType
// {
// CLAIMABLE_BALANCE_ID_TYPE_V0 = 0
// };
//
// ===========================================================================
xdr.enum("ClaimableBalanceIdType", {
claimableBalanceIdTypeV0: 0,
});
// === xdr source ============================================================
//
// union ClaimableBalanceID switch (ClaimableBalanceIDType type)
// {
// case CLAIMABLE_BALANCE_ID_TYPE_V0:
// Hash v0;
// };
//
// ===========================================================================
xdr.union("ClaimableBalanceId", {
switchOn: xdr.lookup("ClaimableBalanceIdType"),
switchName: "type",
switches: [
["claimableBalanceIdTypeV0", "v0"],
],
arms: {
v0: xdr.lookup("Hash"),
},
});
// === xdr source ============================================================
//
// enum ClaimableBalanceFlags
// {
// // If set, the issuer account of the asset held by the claimable balance may
// // clawback the claimable balance
// CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1
// };
//
// ===========================================================================
xdr.enum("ClaimableBalanceFlags", {
claimableBalanceClawbackEnabledFlag: 1,
});
// === xdr source ============================================================
//
// const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1;
//
// ===========================================================================
xdr.const("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("ClaimableBalanceEntryExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct ClaimableBalanceEntryExtensionV1
// {
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
//
// uint32 flags; // see ClaimableBalanceFlags
// };
//
// ===========================================================================
xdr.struct("ClaimableBalanceEntryExtensionV1", [
["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")],
["flags", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// ClaimableBalanceEntryExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("ClaimableBalanceEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[1, "v1"],
],
arms: {
v1: xdr.lookup("ClaimableBalanceEntryExtensionV1"),
},
});
// === xdr source ============================================================
//
// struct ClaimableBalanceEntry
// {
// // Unique identifier for this ClaimableBalanceEntry
// ClaimableBalanceID balanceID;
//
// // List of claimants with associated predicate
// Claimant claimants<10>;
//
// // Any asset including native
// Asset asset;
//
// // Amount of asset
// int64 amount;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// ClaimableBalanceEntryExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("ClaimableBalanceEntry", [
["balanceId", xdr.lookup("ClaimableBalanceId")],
["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)],
["asset", xdr.lookup("Asset")],
["amount", xdr.lookup("Int64")],
["ext", xdr.lookup("ClaimableBalanceEntryExt")],
]);
// === xdr source ============================================================
//
// struct LiquidityPoolConstantProductParameters
// {
// Asset assetA; // assetA < assetB
// Asset assetB;
// int32 fee; // Fee is in basis points, so the actual rate is (fee/100)%
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolConstantProductParameters", [
["assetA", xdr.lookup("Asset")],
["assetB", xdr.lookup("Asset")],
["fee", xdr.lookup("Int32")],
]);
// === xdr source ============================================================
//
// struct
// {
// LiquidityPoolConstantProductParameters params;
//
// int64 reserveA; // amount of A in the pool
// int64 reserveB; // amount of B in the pool
// int64 totalPoolShares; // total number of pool shares issued
// int64 poolSharesTrustLineCount; // number of trust lines for the
// // associated pool shares
// }
//
// ===========================================================================
xdr.struct("LiquidityPoolEntryConstantProduct", [
["params", xdr.lookup("LiquidityPoolConstantProductParameters")],
["reserveA", xdr.lookup("Int64")],
["reserveB", xdr.lookup("Int64")],
["totalPoolShares", xdr.lookup("Int64")],
["poolSharesTrustLineCount", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// union switch (LiquidityPoolType type)
// {
// case LIQUIDITY_POOL_CONSTANT_PRODUCT:
// struct
// {
// LiquidityPoolConstantProductParameters params;
//
// int64 reserveA; // amount of A in the pool
// int64 reserveB; // amount of B in the pool
// int64 totalPoolShares; // total number of pool shares issued
// int64 poolSharesTrustLineCount; // number of trust lines for the
// // associated pool shares
// } constantProduct;
// }
//
// ===========================================================================
xdr.union("LiquidityPoolEntryBody", {
switchOn: xdr.lookup("LiquidityPoolType"),
switchName: "type",
switches: [
["liquidityPoolConstantProduct", "constantProduct"],
],
arms: {
constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct"),
},
});
// === xdr source ============================================================
//
// struct LiquidityPoolEntry
// {
// PoolID liquidityPoolID;
//
// union switch (LiquidityPoolType type)
// {
// case LIQUIDITY_POOL_CONSTANT_PRODUCT:
// struct
// {
// LiquidityPoolConstantProductParameters params;
//
// int64 reserveA; // amount of A in the pool
// int64 reserveB; // amount of B in the pool
// int64 totalPoolShares; // total number of pool shares issued
// int64 poolSharesTrustLineCount; // number of trust lines for the
// // associated pool shares
// } constantProduct;
// }
// body;
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolEntry", [
["liquidityPoolId", xdr.lookup("PoolId")],
["body", xdr.lookup("LiquidityPoolEntryBody")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("LedgerEntryExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct LedgerEntryExtensionV1
// {
// SponsorshipDescriptor sponsoringID;
//
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerEntryExtensionV1", [
["sponsoringId", xdr.lookup("SponsorshipDescriptor")],
["ext", xdr.lookup("LedgerEntryExtensionV1Ext")],
]);
// === xdr source ============================================================
//
// union switch (LedgerEntryType type)
// {
// case ACCOUNT:
// AccountEntry account;
// case TRUSTLINE:
// TrustLineEntry trustLine;
// case OFFER:
// OfferEntry offer;
// case DATA:
// DataEntry data;
// case CLAIMABLE_BALANCE:
// ClaimableBalanceEntry claimableBalance;
// case LIQUIDITY_POOL:
// LiquidityPoolEntry liquidityPool;
// }
//
// ===========================================================================
xdr.union("LedgerEntryData", {
switchOn: xdr.lookup("LedgerEntryType"),
switchName: "type",
switches: [
["account", "account"],
["trustline", "trustLine"],
["offer", "offer"],
["data", "data"],
["claimableBalance", "claimableBalance"],
["liquidityPool", "liquidityPool"],
],
arms: {
account: xdr.lookup("AccountEntry"),
trustLine: xdr.lookup("TrustLineEntry"),
offer: xdr.lookup("OfferEntry"),
data: xdr.lookup("DataEntry"),
claimableBalance: xdr.lookup("ClaimableBalanceEntry"),
liquidityPool: xdr.lookup("LiquidityPoolEntry"),
},
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerEntryExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("LedgerEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[1, "v1"],
],
arms: {
v1: xdr.lookup("LedgerEntryExtensionV1"),
},
});
// === xdr source ============================================================
//
// struct LedgerEntry
// {
// uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed
//
// union switch (LedgerEntryType type)
// {
// case ACCOUNT:
// AccountEntry account;
// case TRUSTLINE:
// TrustLineEntry trustLine;
// case OFFER:
// OfferEntry offer;
// case DATA:
// DataEntry data;
// case CLAIMABLE_BALANCE:
// ClaimableBalanceEntry claimableBalance;
// case LIQUIDITY_POOL:
// LiquidityPoolEntry liquidityPool;
// }
// data;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerEntryExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerEntry", [
["lastModifiedLedgerSeq", xdr.lookup("Uint32")],
["data", xdr.lookup("LedgerEntryData")],
["ext", xdr.lookup("LedgerEntryExt")],
]);
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyAccount", [
["accountId", xdr.lookup("AccountId")],
]);
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// TrustLineAsset asset;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyTrustLine", [
["accountId", xdr.lookup("AccountId")],
["asset", xdr.lookup("TrustLineAsset")],
]);
// === xdr source ============================================================
//
// struct
// {
// AccountID sellerID;
// int64 offerID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyOffer", [
["sellerId", xdr.lookup("AccountId")],
["offerId", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// string64 dataName;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyData", [
["accountId", xdr.lookup("AccountId")],
["dataName", xdr.lookup("String64")],
]);
// === xdr source ============================================================
//
// struct
// {
// ClaimableBalanceID balanceID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyClaimableBalance", [
["balanceId", xdr.lookup("ClaimableBalanceId")],
]);
// === xdr source ============================================================
//
// struct
// {
// PoolID liquidityPoolID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyLiquidityPool", [
["liquidityPoolId", xdr.lookup("PoolId")],
]);
// === xdr source ============================================================
//
// union LedgerKey switch (LedgerEntryType type)
// {
// case ACCOUNT:
// struct
// {
// AccountID accountID;
// } account;
//
// case TRUSTLINE:
// struct
// {
// AccountID accountID;
// TrustLineAsset asset;
// } trustLine;
//
// case OFFER:
// struct
// {
// AccountID sellerID;
// int64 offerID;
// } offer;
//
// case DATA:
// struct
// {
// AccountID accountID;
// string64 dataName;
// } data;
//
// case CLAIMABLE_BALANCE:
// struct
// {
// ClaimableBalanceID balanceID;
// } claimableBalance;
//
// case LIQUIDITY_POOL:
// struct
// {
// PoolID liquidityPoolID;
// } liquidityPool;
// };
//
// ===========================================================================
xdr.union("LedgerKey", {
switchOn: xdr.lookup("LedgerEntryType"),
switchName: "type",
switches: [
["account", "account"],
["trustline", "trustLine"],
["offer", "offer"],
["data", "data"],
["claimableBalance", "claimableBalance"],
["liquidityPool", "liquidityPool"],
],
arms: {
account: xdr.lookup("LedgerKeyAccount"),
trustLine: xdr.lookup("LedgerKeyTrustLine"),
offer: xdr.lookup("LedgerKeyOffer"),
data: xdr.lookup("LedgerKeyData"),
claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"),
liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"),
},
});
// === xdr source ============================================================
//
// enum EnvelopeType
// {
// ENVELOPE_TYPE_TX_V0 = 0,
// ENVELOPE_TYPE_SCP = 1,
// ENVELOPE_TYPE_TX = 2,
// ENVELOPE_TYPE_AUTH = 3,
// ENVELOPE_TYPE_SCPVALUE = 4,
// ENVELOPE_TYPE_TX_FEE_BUMP = 5,
// ENVELOPE_TYPE_OP_ID = 6,
// ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7
// };
//
// ===========================================================================
xdr.enum("EnvelopeType", {
envelopeTypeTxV0: 0,
envelopeTypeScp: 1,
envelopeTypeTx: 2,
envelopeTypeAuth: 3,
envelopeTypeScpvalue: 4,
envelopeTypeTxFeeBump: 5,
envelopeTypeOpId: 6,
envelopeTypePoolRevokeOpId: 7,
});
// === xdr source ============================================================
//
// typedef opaque UpgradeType<128>;
//
// ===========================================================================
xdr.typedef("UpgradeType", xdr.varOpaque(128));
// === xdr source ============================================================
//
// enum StellarValueType
// {
// STELLAR_VALUE_BASIC = 0,
// STELLAR_VALUE_SIGNED = 1
// };
//
// ===========================================================================
xdr.enum("StellarValueType", {
stellarValueBasic: 0,
stellarValueSigned: 1,
});
// === xdr source ============================================================
//
// struct LedgerCloseValueSignature
// {
// NodeID nodeID; // which node introduced the value
// Signature signature; // nodeID's signature
// };
//
// ===========================================================================
xdr.struct("LedgerCloseValueSignature", [
["nodeId", xdr.lookup("NodeId")],
["signature", xdr.lookup("Signature")],
]);
// === xdr source ============================================================
//
// union switch (StellarValueType v)
// {
// case STELLAR_VALUE_BASIC:
// void;
// case STELLAR_VALUE_SIGNED:
// LedgerCloseValueSignature lcValueSignature;
// }
//
// ===========================================================================
xdr.union("StellarValueExt", {
switchOn: xdr.lookup("StellarValueType"),
switchName: "v",
switches: [
["stellarValueBasic", xdr.void()],
["stellarValueSigned", "lcValueSignature"],
],
arms: {
lcValueSignature: xdr.lookup("LedgerCloseValueSignature"),
},
});
// === xdr source ============================================================
//
// struct StellarValue
// {
// Hash txSetHash; // transaction set to apply to previous ledger
// TimePoint closeTime; // network close time
//
// // upgrades to apply to the previous ledger (usually empty)
// // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop
// // unknown steps during consensus if needed.
// // see notes below on 'LedgerUpgrade' for more detail
// // max size is dictated by number of upgrade types (+ room for future)
// UpgradeType upgrades<6>;
//
// // reserved for future use
// union switch (StellarValueType v)
// {
// case STELLAR_VALUE_BASIC:
// void;
// case STELLAR_VALUE_SIGNED:
// LedgerCloseValueSignature lcValueSignature;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("StellarValue", [
["txSetHash", xdr.lookup("Hash")],
["closeTime", xdr.lookup("TimePoint")],
["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)],
["ext", xdr.lookup("StellarValueExt")],
]);
// === xdr source ============================================================
//
// const MASK_LEDGER_HEADER_FLAGS = 0x7;
//
// ===========================================================================
xdr.const("MASK_LEDGER_HEADER_FLAGS", 0x7);
// === xdr source ============================================================
//
// enum LedgerHeaderFlags
// {
// DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1,
// DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2,
// DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4
// };
//
// ===========================================================================
xdr.enum("LedgerHeaderFlags", {
disableLiquidityPoolTradingFlag: 1,
disableLiquidityPoolDepositFlag: 2,
disableLiquidityPoolWithdrawalFlag: 4,
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("LedgerHeaderExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct LedgerHeaderExtensionV1
// {
// uint32 flags; // LedgerHeaderFlags
//
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerHeaderExtensionV1", [
["flags", xdr.lookup("Uint32")],
["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerHeaderExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("LedgerHeaderExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[1, "v1"],
],
arms: {
v1: xdr.lookup("LedgerHeaderExtensionV1"),
},
});
// === xdr source ============================================================
//
// struct LedgerHeader
// {
// uint32 ledgerVersion; // the protocol version of the ledger
// Hash previousLedgerHash; // hash of the previous ledger header
// StellarValue scpValue; // what consensus agreed to
// Hash txSetResultHash; // the TransactionResultSet that led to this ledger
// Hash bucketListHash; // hash of the ledger state
//
// uint32 ledgerSeq; // sequence number of this ledger
//
// int64 totalCoins; // total number of stroops in existence.
// // 10,000,000 stroops in 1 XLM
//
// int64 feePool; // fees burned since last inflation run
// uint32 inflationSeq; // inflation sequence number
//
// uint64 idPool; // last used global ID, used for generating objects
//
// uint32 baseFee; // base fee per operation in stroops
// uint32 baseReserve; // account base reserve in stroops
//
// uint32 maxTxSetSize; // maximum size a transaction set can be
//
// Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back
// // in time without walking the chain back ledger by ledger
// // each slot contains the oldest ledger that is mod of
// // either 50 5000 50000 or 500000 depending on index
// // skipList[0] mod(50), skipList[1] mod(5000), etc
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerHeaderExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerHeader", [
["ledgerVersion", xdr.lookup("Uint32")],
["previousLedgerHash", xdr.lookup("Hash")],
["scpValue", xdr.lookup("StellarValue")],
["txSetResultHash", xdr.lookup("Hash")],
["bucketListHash", xdr.lookup("Hash")],
["ledgerSeq", xdr.lookup("Uint32")],
["totalCoins", xdr.lookup("Int64")],
["feePool", xdr.lookup("Int64")],
["inflationSeq", xdr.lookup("Uint32")],
["idPool", xdr.lookup("Uint64")],
["baseFee", xdr.lookup("Uint32")],
["baseReserve", xdr.lookup("Uint32")],
["maxTxSetSize", xdr.lookup("Uint32")],
["skipList", xdr.array(xdr.lookup("Hash"), 4)],
["ext", xdr.lookup("LedgerHeaderExt")],
]);
// === xdr source ============================================================
//
// enum LedgerUpgradeType
// {
// LEDGER_UPGRADE_VERSION = 1,
// LEDGER_UPGRADE_BASE_FEE = 2,
// LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3,
// LEDGER_UPGRADE_BASE_RESERVE = 4,
// LEDGER_UPGRADE_FLAGS = 5
// };
//
// ===========================================================================
xdr.enum("LedgerUpgradeType", {
ledgerUpgradeVersion: 1,
ledgerUpgradeBaseFee: 2,
ledgerUpgradeMaxTxSetSize: 3,
ledgerUpgradeBaseReserve: 4,
ledgerUpgradeFlags: 5,
});
// === xdr source ============================================================
//
// union LedgerUpgrade switch (LedgerUpgradeType type)
// {
// case LEDGER_UPGRADE_VERSION:
// uint32 newLedgerVersion; // update ledgerVersion
// case LEDGER_UPGRADE_BASE_FEE:
// uint32 newBaseFee; // update baseFee
// case LEDGER_UPGRADE_MAX_TX_SET_SIZE:
// uint32 newMaxTxSetSize; // update maxTxSetSize
// case LEDGER_UPGRADE_BASE_RESERVE:
// uint32 newBaseReserve; // update baseReserve
// case LEDGER_UPGRADE_FLAGS:
// uint32 newFlags; // update flags
// };
//
// ===========================================================================
xdr.union("LedgerUpgrade", {
switchOn: xdr.lookup("LedgerUpgradeType"),
switchName: "type",
switches: [
["ledgerUpgradeVersion", "newLedgerVersion"],
["ledgerUpgradeBaseFee", "newBaseFee"],
["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"],
["ledgerUpgradeBaseReserve", "newBaseReserve"],
["ledgerUpgradeFlags", "newFlags"],
],
arms: {
newLedgerVersion: xdr.lookup("Uint32"),
newBaseFee: xdr.lookup("Uint32"),
newMaxTxSetSize: xdr.lookup("Uint32"),
newBaseReserve: xdr.lookup("Uint32"),
newFlags: xdr.lookup("Uint32"),
},
});
// === xdr source ============================================================
//
// enum BucketEntryType
// {
// METAENTRY =
// -1, // At-and-after protocol 11: bucket metadata, should come first.
// LIVEENTRY = 0, // Before protocol 11: created-or-updated;
// // At-and-after protocol 11: only updated.
// DEADENTRY = 1,
// INITENTRY = 2 // At-and-after protocol 11: only created.
// };
//
// ===========================================================================
xdr.enum("BucketEntryType", {
metaentry: -1,
liveentry: 0,
deadentry: 1,
initentry: 2,
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("BucketMetadataExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct BucketMetadata
// {
// // Indicates the protocol version used to create / merge this bucket.
// uint32 ledgerVersion;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("BucketMetadata", [
["ledgerVersion", xdr.lookup("Uint32")],
["ext", xdr.lookup("BucketMetadataExt")],
]);
// === xdr source ============================================================
//
// union BucketEntry switch (BucketEntryType type)
// {
// case LIVEENTRY:
// case INITENTRY:
// LedgerEntry liveEntry;
//
// case DEADENTRY:
// LedgerKey deadEntry;
// case METAENTRY:
// BucketMetadata metaEntry;
// };
//
// ===========================================================================
xdr.union("BucketEntry", {
switchOn: xdr.lookup("BucketEntryType"),
switchName: "type",
switches: [
["liveentry", "liveEntry"],
["initentry", "liveEntry"],
["deadentry", "deadEntry"],
["metaentry", "metaEntry"],
],
arms: {
liveEntry: xdr.lookup("LedgerEntry"),
deadEntry: xdr.lookup("LedgerKey"),
metaEntry: xdr.lookup("BucketMetadata"),
},
});
// === xdr source ============================================================
//
// enum TxSetComponentType
// {
// // txs with effective fee <= bid derived from a base fee (if any).
// // If base fee is not specified, no discount is applied.
// TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0
// };
//
// ===========================================================================
xdr.enum("TxSetComponentType", {
txsetCompTxsMaybeDiscountedFee: 0,
});
// === xdr source ============================================================
//
// struct
// {
// int64* baseFee;
// TransactionEnvelope txs<>;
// }
//
// ===========================================================================
xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [
["baseFee", xdr.option(xdr.lookup("Int64"))],
["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)],
]);
// === xdr source ============================================================
//
// union TxSetComponent switch (TxSetComponentType type)
// {
// case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE:
// struct
// {
// int64* baseFee;
// TransactionEnvelope txs<>;
// } txsMaybeDiscountedFee;
// };
//
// ===========================================================================
xdr.union("TxSetComponent", {
switchOn: xdr.lookup("TxSetComponentType"),
switchName: "type",
switches: [
["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"],
],
arms: {
txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee"),
},
});
// === xdr source ============================================================
//
// union TransactionPhase switch (int v)
// {
// case 0:
// TxSetComponent v0Components<>;
// };
//
// ===========================================================================
xdr.union("TransactionPhase", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, "v0Components"],
],
arms: {
v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647),
},
});
// === xdr source ============================================================
//
// struct TransactionSet
// {
// Hash previousLedgerHash;
// TransactionEnvelope txs<>;
// };
//
// ===========================================================================
xdr.struct("TransactionSet", [
["previousLedgerHash", xdr.lookup("Hash")],
["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)],
]);
// === xdr source ============================================================
//
// struct TransactionSetV1
// {
// Hash previousLedgerHash;
// TransactionPhase phases<>;
// };
//
// ===========================================================================
xdr.struct("TransactionSetV1", [
["previousLedgerHash", xdr.lookup("Hash")],
["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)],
]);
// === xdr source ============================================================
//
// union GeneralizedTransactionSet switch (int v)
// {
// // We consider the legacy TransactionSet to be v0.
// case 1:
// TransactionSetV1 v1TxSet;
// };
//
// ===========================================================================
xdr.union("GeneralizedTransactionSet", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[1, "v1TxSet"],
],
arms: {
v1TxSet: xdr.lookup("TransactionSetV1"),
},
});
// === xdr source ============================================================
//
// struct TransactionResultPair
// {
// Hash transactionHash;
// TransactionResult result; // result for the transaction
// };
//
// ===========================================================================
xdr.struct("TransactionResultPair", [
["transactionHash", xdr.lookup("Hash")],
["result", xdr.lookup("TransactionResult")],
]);
// === xdr source ============================================================
//
// struct TransactionResultSet
// {
// TransactionResultPair results<>;
// };
//
// ===========================================================================
xdr.struct("TransactionResultSet", [
["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// GeneralizedTransactionSet generalizedTxSet;
// }
//
// ===========================================================================
xdr.union("TransactionHistoryEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
[1, "generalizedTxSet"],
],
arms: {
generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"),
},
});
// === xdr source ============================================================
//
// struct TransactionHistoryEntry
// {
// uint32 ledgerSeq;
// TransactionSet txSet;
//
// // when v != 0, txSet must be empty
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// GeneralizedTransactionSet generalizedTxSet;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionHistoryEntry", [
["ledgerSeq", xdr.lookup("Uint32")],
["txSet", xdr.lookup("TransactionSet")],
["ext", xdr.lookup("TransactionHistoryEntryExt")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionHistoryResultEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct TransactionHistoryResultEntry
// {
// uint32 ledgerSeq;
// TransactionResultSet txResultSet;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionHistoryResultEntry", [
["ledgerSeq", xdr.lookup("Uint32")],
["txResultSet", xdr.lookup("TransactionResultSet")],
["ext", xdr.lookup("TransactionHistoryResultEntryExt")],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("LedgerHeaderHistoryEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct LedgerHeaderHistoryEntry
// {
// Hash hash;
// LedgerHeader header;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerHeaderHistoryEntry", [
["hash", xdr.lookup("Hash")],
["header", xdr.lookup("LedgerHeader")],
["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")],
]);
// === xdr source ============================================================
//
// struct LedgerSCPMessages
// {
// uint32 ledgerSeq;
// SCPEnvelope messages<>;
// };
//
// ===========================================================================
xdr.struct("LedgerScpMessages", [
["ledgerSeq", xdr.lookup("Uint32")],
["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)],
]);
// === xdr source ============================================================
//
// struct SCPHistoryEntryV0
// {
// SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages
// LedgerSCPMessages ledgerMessages;
// };
//
// ===========================================================================
xdr.struct("ScpHistoryEntryV0", [
["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)],
["ledgerMessages", xdr.lookup("LedgerScpMessages")],
]);
// === xdr source ============================================================
//
// union SCPHistoryEntry switch (int v)
// {
// case 0:
// SCPHistoryEntryV0 v0;
// };
//
// ===========================================================================
xdr.union("ScpHistoryEntry", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, "v0"],
],
arms: {
v0: xdr.lookup("ScpHistoryEntryV0"),
},
});
// === xdr source ============================================================
//
// enum LedgerEntryChangeType
// {
// LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger
// LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger
// LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger
// LEDGER_ENTRY_STATE = 3 // value of the entry
// };
//
// ===========================================================================
xdr.enum("LedgerEntryChangeType", {
ledgerEntryCreated: 0,
ledgerEntryUpdated: 1,
ledgerEntryRemoved: 2,
ledgerEntryState: 3,
});
// === xdr source ============================================================
//
// union LedgerEntryChange switch (LedgerEntryChangeType type)
// {
// case LEDGER_ENTRY_CREATED:
// LedgerEntry created;
// case LEDGER_ENTRY_UPDATED:
// LedgerEntry updated;
// case LEDGER_ENTRY_REMOVED:
// LedgerKey removed;
// case LEDGER_ENTRY_STATE:
// LedgerEntry state;
// };
//
// ===========================================================================
xdr.union("LedgerEntryChange", {
switchOn: xdr.lookup("LedgerEntryChangeType"),
switchName: "type",
switches: [
["ledgerEntryCreated", "created"],
["ledgerEntryUpdated", "updated"],
["ledgerEntryRemoved", "removed"],
["ledgerEntryState", "state"],
],
arms: {
created: xdr.lookup("LedgerEntry"),
updated: xdr.lookup("LedgerEntry"),
removed: xdr.lookup("LedgerKey"),
state: xdr.lookup("LedgerEntry"),
},
});
// === xdr source ============================================================
//
// typedef LedgerEntryChange LedgerEntryChanges<>;
//
// ===========================================================================
xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647));
// === xdr source ============================================================
//
// struct OperationMeta
// {
// LedgerEntryChanges changes;
// };
//
// ===========================================================================
xdr.struct("OperationMeta", [
["changes", xdr.lookup("LedgerEntryChanges")],
]);
// === xdr source ============================================================
//
// struct TransactionMetaV1
// {
// LedgerEntryChanges txChanges; // tx level changes if any
// OperationMeta operations<>; // meta for each operation
// };
//
// ===========================================================================
xdr.struct("TransactionMetaV1", [
["txChanges", xdr.lookup("LedgerEntryChanges")],
["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)],
]);
// === xdr source ============================================================
//
// struct TransactionMetaV2
// {
// LedgerEntryChanges txChangesBefore; // tx level changes before operations
// // are applied if any
// OperationMeta operations<>; // meta for each operation
// LedgerEntryChanges txChangesAfter; // tx level changes after operations are
// // applied if any
// };
//
// ===========================================================================
xdr.struct("TransactionMetaV2", [
["txChangesBefore", xdr.lookup("LedgerEntryChanges")],
["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)],
["txChangesAfter", xdr.lookup("LedgerEntryChanges")],
]);
// === xdr source ============================================================
//
// union TransactionMeta switch (int v)
// {
// case 0:
// OperationMeta operations<>;
// case 1:
// TransactionMetaV1 v1;
// case 2:
// TransactionMetaV2 v2;
// };
//
// ===========================================================================
xdr.union("TransactionMeta", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, "operations"],
[1, "v1"],
[2, "v2"],
],
arms: {
operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647),
v1: xdr.lookup("TransactionMetaV1"),
v2: xdr.lookup("TransactionMetaV2"),
},
});
// === xdr source ============================================================
//
// struct TransactionResultMeta
// {
// TransactionResultPair result;
// LedgerEntryChanges feeProcessing;
// TransactionMeta txApplyProcessing;
// };
//
// ===========================================================================
xdr.struct("TransactionResultMeta", [
["result", xdr.lookup("TransactionResultPair")],
["feeProcessing", xdr.lookup("LedgerEntryChanges")],
["txApplyProcessing", xdr.lookup("TransactionMeta")],
]);
// === xdr source ============================================================
//
// struct UpgradeEntryMeta
// {
// LedgerUpgrade upgrade;
// LedgerEntryChanges changes;
// };
//
// ===========================================================================
xdr.struct("UpgradeEntryMeta", [
["upgrade", xdr.lookup("LedgerUpgrade")],
["changes", xdr.lookup("LedgerEntryChanges")],
]);
// === xdr source ============================================================
//
// struct LedgerCloseMetaV0
// {
// LedgerHeaderHistoryEntry ledgerHeader;
// // NB: txSet is sorted in "Hash order"
// TransactionSet txSet;
//
// // NB: transactions are sorted in apply order here
// // fees for all transactions are processed first
// // followed by applying transactions
// TransactionResultMeta txProcessing<>;
//
// // upgrades are applied last
// UpgradeEntryMeta upgradesProcessing<>;
//
// // other misc information attached to the ledger close
// SCPHistoryEntry scpInfo<>;
// };
//
// ===========================================================================
xdr.struct("LedgerCloseMetaV0", [
["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")],
["txSet", xdr.lookup("TransactionSet")],
["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)],
["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)],
["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)],
]);
// === xdr source ============================================================
//
// struct LedgerCloseMetaV1
// {
// LedgerHeaderHistoryEntry ledgerHeader;
//
// GeneralizedTransactionSet txSet;
//
// // NB: transactions are sorted in apply order here
// // fees for all transactions are processed first
// // followed by applying transactions
// TransactionResultMeta txProcessing<>;
//
// // upgrades are applied last
// UpgradeEntryMeta upgradesProcessing<>;
//
// // other misc information attached to the ledger close
// SCPHistoryEntry scpInfo<>;
// };
//
// ===========================================================================
xdr.struct("LedgerCloseMetaV1", [
["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")],
["txSet", xdr.lookup("GeneralizedTransactionSet")],
["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)],
["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)],
["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)],
]);
// === xdr source ============================================================
//
// union LedgerCloseMeta switch (int v)
// {
// case 0:
// LedgerCloseMetaV0 v0;
// case 1:
// LedgerCloseMetaV1 v1;
// };
//
// ===========================================================================
xdr.union("LedgerCloseMeta", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, "v0"],
[1, "v1"],
],
arms: {
v0: xdr.lookup("LedgerCloseMetaV0"),
v1: xdr.lookup("LedgerCloseMetaV1"),
},
});
// === xdr source ============================================================
//
// enum ErrorCode
// {
// ERR_MISC = 0, // Unspecific error
// ERR_DATA = 1, // Malformed data
// ERR_CONF = 2, // Misconfiguration error
// ERR_AUTH = 3, // Authentication failure
// ERR_LOAD = 4 // System overloaded
// };
//
// ===========================================================================
xdr.enum("ErrorCode", {
errMisc: 0,
errData: 1,
errConf: 2,
errAuth: 3,
errLoad: 4,
});
// === xdr source ============================================================
//
// struct Error
// {
// ErrorCode code;
// string msg<100>;
// };
//
// ===========================================================================
xdr.struct("Error", [
["code", xdr.lookup("ErrorCode")],
["msg", xdr.string(100)],
]);
// === xdr source ============================================================
//
// struct SendMore
// {
// uint32 numMessages;
// };
//
// ===========================================================================
xdr.struct("SendMore", [
["numMessages", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// struct AuthCert
// {
// Curve25519Public pubkey;
// uint64 expiration;
// Signature sig;
// };
//
// ===========================================================================
xdr.struct("AuthCert", [
["pubkey", xdr.lookup("Curve25519Public")],
["expiration", xdr.lookup("Uint64")],
["sig", xdr.lookup("Signature")],
]);
// === xdr source ============================================================
//
// struct Hello
// {
// uint32 ledgerVersion;
// uint32 overlayVersion;
// uint32 overlayMinVersion;
// Hash networkID;
// string versionStr<100>;
// int listeningPort;
// NodeID peerID;
// AuthCert cert;
// uint256 nonce;
// };
//
// ===========================================================================
xdr.struct("Hello", [
["ledgerVersion", xdr.lookup("Uint32")],
["overlayVersion", xdr.lookup("Uint32")],
["overlayMinVersion", xdr.lookup("Uint32")],
["networkId", xdr.lookup("Hash")],
["versionStr", xdr.string(100)],
["listeningPort", xdr.int()],
["peerId", xdr.lookup("NodeId")],
["cert", xdr.lookup("AuthCert")],
["nonce", xdr.lookup("Uint256")],
]);
// === xdr source ============================================================
//
// struct Auth
// {
// // Empty message, just to confirm
// // establishment of MAC keys.
// int unused;
// };
//
// ===========================================================================
xdr.struct("Auth", [
["unused", xdr.int()],
]);
// === xdr source ============================================================
//
// enum IPAddrType
// {
// IPv4 = 0,
// IPv6 = 1
// };
//
// ===========================================================================
xdr.enum("IpAddrType", {
iPv4: 0,
iPv6: 1,
});
// === xdr source ============================================================
//
// union switch (IPAddrType type)
// {
// case IPv4:
// opaque ipv4[4];
// case IPv6:
// opaque ipv6[16];
// }
//
// ===========================================================================
xdr.union("PeerAddressIp", {
switchOn: xdr.lookup("IpAddrType"),
switchName: "type",
switches: [
["iPv4", "ipv4"],
["iPv6", "ipv6"],
],
arms: {
ipv4: xdr.opaque(4),
ipv6: xdr.opaque(16),
},
});
// === xdr source ============================================================
//
// struct PeerAddress
// {
// union switch (IPAddrType type)
// {
// case IPv4:
// opaque ipv4[4];
// case IPv6:
// opaque ipv6[16];
// }
// ip;
// uint32 port;
// uint32 numFailures;
// };
//
// ===========================================================================
xdr.struct("PeerAddress", [
["ip", xdr.lookup("PeerAddressIp")],
["port", xdr.lookup("Uint32")],
["numFailures", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// enum MessageType
// {
// ERROR_MSG = 0,
// AUTH = 2,
// DONT_HAVE = 3,
//
// GET_PEERS = 4, // gets a list of peers this guy knows about
// PEERS = 5,
//
// GET_TX_SET = 6, // gets a particular txset by hash
// TX_SET = 7,
// GENERALIZED_TX_SET = 17,
//
// TRANSACTION = 8, // pass on a tx you have heard about
//
// // SCP
// GET_SCP_QUORUMSET = 9,
// SCP_QUORUMSET = 10,
// SCP_MESSAGE = 11,
// GET_SCP_STATE = 12,
//
// // new messages
// HELLO = 13,
//
// SURVEY_REQUEST = 14,
// SURVEY_RESPONSE = 15,
//
// SEND_MORE = 16
// };
//
// ===========================================================================
xdr.enum("MessageType", {
errorMsg: 0,
auth: 2,
dontHave: 3,
getPeers: 4,
peers: 5,
getTxSet: 6,
txSet: 7,
generalizedTxSet: 17,
transaction: 8,
getScpQuorumset: 9,
scpQuorumset: 10,
scpMessage: 11,
getScpState: 12,
hello: 13,
surveyRequest: 14,
surveyResponse: 15,
sendMore: 16,
});
// === xdr source ============================================================
//
// struct DontHave
// {
// MessageType type;
// uint256 reqHash;
// };
//
// ===========================================================================
xdr.struct("DontHave", [
["type", xdr.lookup("MessageType")],
["reqHash", xdr.lookup("Uint256")],
]);
// === xdr source ============================================================
//
// enum SurveyMessageCommandType
// {
// SURVEY_TOPOLOGY = 0
// };
//
// ===========================================================================
xdr.enum("SurveyMessageCommandType", {
surveyTopology: 0,
});
// === xdr source ============================================================
//
// struct SurveyRequestMessage
// {
// NodeID surveyorPeerID;
// NodeID surveyedPeerID;
// uint32 ledgerNum;
// Curve25519Public encryptionKey;
// SurveyMessageCommandType commandType;
// };
//
// ===========================================================================
xdr.struct("SurveyRequestMessage", [
["surveyorPeerId", xdr.lookup("NodeId")],
["surveyedPeerId", xdr.lookup("NodeId")],
["ledgerNum", xdr.lookup("Uint32")],
["encryptionKey", xdr.lookup("Curve25519Public")],
["commandType", xdr.lookup("SurveyMessageCommandType")],
]);
// === xdr source ============================================================
//
// struct SignedSurveyRequestMessage
// {
// Signature requestSignature;
// SurveyRequestMessage request;
// };
//
// ===========================================================================
xdr.struct("SignedSurveyRequestMessage", [
["requestSignature", xdr.lookup("Signature")],
["request", xdr.lookup("SurveyRequestMessage")],
]);
// === xdr source ============================================================
//
// typedef opaque EncryptedBody<64000>;
//
// ===========================================================================
xdr.typedef("EncryptedBody", xdr.varOpaque(64000));
// === xdr source ============================================================
//
// struct SurveyResponseMessage
// {
// NodeID surveyorPeerID;
// NodeID surveyedPeerID;
// uint32 ledgerNum;
// SurveyMessageCommandType commandType;
// EncryptedBody encryptedBody;
// };
//
// ===========================================================================
xdr.struct("SurveyResponseMessage", [
["surveyorPeerId", xdr.lookup("NodeId")],
["surveyedPeerId", xdr.lookup("NodeId")],
["ledgerNum", xdr.lookup("Uint32")],
["commandType", xdr.lookup("SurveyMessageCommandType")],
["encryptedBody", xdr.lookup("EncryptedBody")],
]);
// === xdr source ============================================================
//
// struct SignedSurveyResponseMessage
// {
// Signature responseSignature;
// SurveyResponseMessage response;
// };
//
// ===========================================================================
xdr.struct("SignedSurveyResponseMessage", [
["responseSignature", xdr.lookup("Signature")],
["response", xdr.lookup("SurveyResponseMessage")],
]);
// === xdr source ============================================================
//
// struct PeerStats
// {
// NodeID id;
// string versionStr<100>;
// uint64 messagesRead;
// uint64 messagesWritten;
// uint64 bytesRead;
// uint64 bytesWritten;
// uint64 secondsConnected;
//
// uint64 uniqueFloodBytesRecv;
// uint64 duplicateFloodBytesRecv;
// uint64 uniqueFetchBytesRecv;
// uint64 duplicateFetchBytesRecv;
//
// uint64 uniqueFloodMessageRecv;
// uint64 duplicateFloodMessageRecv;
// uint64 uniqueFetchMessageRecv;
// uint64 duplicateFetchMessageRecv;
// };
//
// ===========================================================================
xdr.struct("PeerStats", [
["id", xdr.lookup("NodeId")],
["versionStr", xdr.string(100)],
["messagesRead", xdr.lookup("Uint64")],
["messagesWritten", xdr.lookup("Uint64")],
["bytesRead", xdr.lookup("Uint64")],
["bytesWritten", xdr.lookup("Uint64")],
["secondsConnected", xdr.lookup("Uint64")],
["uniqueFloodBytesRecv", xdr.lookup("Uint64")],
["duplicateFloodBytesRecv", xdr.lookup("Uint64")],
["uniqueFetchBytesRecv", xdr.lookup("Uint64")],
["duplicateFetchBytesRecv", xdr.lookup("Uint64")],
["uniqueFloodMessageRecv", xdr.lookup("Uint64")],
["duplicateFloodMessageRecv", xdr.lookup("Uint64")],
["uniqueFetchMessageRecv", xdr.lookup("Uint64")],
["duplicateFetchMessageRecv", xdr.lookup("Uint64")],
]);
// === xdr source ============================================================
//
// typedef PeerStats PeerStatList<25>;
//
// ===========================================================================
xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25));
// === xdr source ============================================================
//
// struct TopologyResponseBody
// {
// PeerStatList inboundPeers;
// PeerStatList outboundPeers;
//
// uint32 totalInboundPeerCount;
// uint32 totalOutboundPeerCount;
// };
//
// ===========================================================================
xdr.struct("TopologyResponseBody", [
["inboundPeers", xdr.lookup("PeerStatList")],
["outboundPeers", xdr.lookup("PeerStatList")],
["totalInboundPeerCount", xdr.lookup("Uint32")],
["totalOutboundPeerCount", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// union SurveyResponseBody switch (SurveyMessageCommandType type)
// {
// case SURVEY_TOPOLOGY:
// TopologyResponseBody topologyResponseBody;
// };
//
// ===========================================================================
xdr.union("SurveyResponseBody", {
switchOn: xdr.lookup("SurveyMessageCommandType"),
switchName: "type",
switches: [
["surveyTopology", "topologyResponseBody"],
],
arms: {
topologyResponseBody: xdr.lookup("TopologyResponseBody"),
},
});
// === xdr source ============================================================
//
// union StellarMessage switch (MessageType type)
// {
// case ERROR_MSG:
// Error error;
// case HELLO:
// Hello hello;
// case AUTH:
// Auth auth;
// case DONT_HAVE:
// DontHave dontHave;
// case GET_PEERS:
// void;
// case PEERS:
// PeerAddress peers<100>;
//
// case GET_TX_SET:
// uint256 txSetHash;
// case TX_SET:
// TransactionSet txSet;
// case GENERALIZED_TX_SET:
// GeneralizedTransactionSet generalizedTxSet;
//
// case TRANSACTION:
// TransactionEnvelope transaction;
//
// case SURVEY_REQUEST:
// SignedSurveyRequestMessage signedSurveyRequestMessage;
//
// case SURVEY_RESPONSE:
// SignedSurveyResponseMessage signedSurveyResponseMessage;
//
// // SCP
// case GET_SCP_QUORUMSET:
// uint256 qSetHash;
// case SCP_QUORUMSET:
// SCPQuorumSet qSet;
// case SCP_MESSAGE:
// SCPEnvelope envelope;
// case GET_SCP_STATE:
// uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest
// case SEND_MORE:
// SendMore sendMoreMessage;
// };
//
// ===========================================================================
xdr.union("StellarMessage", {
switchOn: xdr.lookup("MessageType"),
switchName: "type",
switches: [
["errorMsg", "error"],
["hello", "hello"],
["auth", "auth"],
["dontHave", "dontHave"],
["getPeers", xdr.void()],
["peers", "peers"],
["getTxSet", "txSetHash"],
["txSet", "txSet"],
["generalizedTxSet", "generalizedTxSet"],
["transaction", "transaction"],
["surveyRequest", "signedSurveyRequestMessage"],
["surveyResponse", "signedSurveyResponseMessage"],
["getScpQuorumset", "qSetHash"],
["scpQuorumset", "qSet"],
["scpMessage", "envelope"],
["getScpState", "getScpLedgerSeq"],
["sendMore", "sendMoreMessage"],
],
arms: {
error: xdr.lookup("Error"),
hello: xdr.lookup("Hello"),
auth: xdr.lookup("Auth"),
dontHave: xdr.lookup("DontHave"),
peers: xdr.varArray(xdr.lookup("PeerAddress"), 100),
txSetHash: xdr.lookup("Uint256"),
txSet: xdr.lookup("TransactionSet"),
generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"),
transaction: xdr.lookup("TransactionEnvelope"),
signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"),
signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"),
qSetHash: xdr.lookup("Uint256"),
qSet: xdr.lookup("ScpQuorumSet"),
envelope: xdr.lookup("ScpEnvelope"),
getScpLedgerSeq: xdr.lookup("Uint32"),
sendMoreMessage: xdr.lookup("SendMore"),
},
});
// === xdr source ============================================================
//
// struct
// {
// uint64 sequence;
// StellarMessage message;
// HmacSha256Mac mac;
// }
//
// ===========================================================================
xdr.struct("AuthenticatedMessageV0", [
["sequence", xdr.lookup("Uint64")],
["message", xdr.lookup("StellarMessage")],
["mac", xdr.lookup("HmacSha256Mac")],
]);
// === xdr source ============================================================
//
// union AuthenticatedMessage switch (uint32 v)
// {
// case 0:
// struct
// {
// uint64 sequence;
// StellarMessage message;
// HmacSha256Mac mac;
// } v0;
// };
//
// ===========================================================================
xdr.union("AuthenticatedMessage", {
switchOn: xdr.lookup("Uint32"),
switchName: "v",
switches: [
[0, "v0"],
],
arms: {
v0: xdr.lookup("AuthenticatedMessageV0"),
},
});
// === xdr source ============================================================
//
// union LiquidityPoolParameters switch (LiquidityPoolType type)
// {
// case LIQUIDITY_POOL_CONSTANT_PRODUCT:
// LiquidityPoolConstantProductParameters constantProduct;
// };
//
// ===========================================================================
xdr.union("LiquidityPoolParameters", {
switchOn: xdr.lookup("LiquidityPoolType"),
switchName: "type",
switches: [
["liquidityPoolConstantProduct", "constantProduct"],
],
arms: {
constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters"),
},
});
// === xdr source ============================================================
//
// struct
// {
// uint64 id;
// uint256 ed25519;
// }
//
// ===========================================================================
xdr.struct("MuxedAccountMed25519", [
["id", xdr.lookup("Uint64")],
["ed25519", xdr.lookup("Uint256")],
]);
// === xdr source ============================================================
//
// union MuxedAccount switch (CryptoKeyType type)
// {
// case KEY_TYPE_ED25519:
// uint256 ed25519;
// case KEY_TYPE_MUXED_ED25519:
// struct
// {
// uint64 id;
// uint256 ed25519;
// } med25519;
// };
//
// ===========================================================================
xdr.union("MuxedAccount", {
switchOn: xdr.lookup("CryptoKeyType"),
switchName: "type",
switches: [
["keyTypeEd25519", "ed25519"],
["keyTypeMuxedEd25519", "med25519"],
],
arms: {
ed25519: xdr.lookup("Uint256"),
med25519: xdr.lookup("MuxedAccountMed25519"),
},
});
// === xdr source ============================================================
//
// struct DecoratedSignature
// {
// SignatureHint hint; // last 4 bytes of the public key, used as a hint
// Signature signature; // actual signature
// };
//
// ===========================================================================
xdr.struct("DecoratedSignature", [
["hint", xdr.lookup("SignatureHint")],
["signature", xdr.lookup("Signature")],
]);
// === xdr source ============================================================
//
// enum OperationType
// {
// CREATE_ACCOUNT = 0,
// PAYMENT = 1,
// PATH_PAYMENT_STRICT_RECEIVE = 2,
// MANAGE_SELL_OFFER = 3,
// CREATE_PASSIVE_SELL_OFFER = 4,
// SET_OPTIONS = 5,
// CHANGE_TRUST = 6,
// ALLOW_TRUST = 7,
// ACCOUNT_MERGE = 8,
// INFLATION = 9,
// MANAGE_DATA = 10,
// BUMP_SEQUENCE = 11,
// MANAGE_BUY_OFFER = 12,
// PATH_PAYMENT_STRICT_SEND = 13,
// CREATE_CLAIMABLE_BALANCE = 14,
// CLAIM_CLAIMABLE_BALANCE = 15,
// BEGIN_SPONSORING_FUTURE_RESERVES = 16,
// END_SPONSORING_FUTURE_RESERVES = 17,
// REVOKE_SPONSORSHIP = 18,
// CLAWBACK = 19,
// CLAWBACK_CLAIMABLE_BALANCE = 20,
// SET_TRUST_LINE_FLAGS = 21,
// LIQUIDITY_POOL_DEPOSIT = 22,
// LIQUIDITY_POOL_WITHDRAW = 23
// };
//
// ===========================================================================
xdr.enum("OperationType", {
createAccount: 0,
payment: 1,
pathPaymentStrictReceive: 2,
manageSellOffer: 3,
createPassiveSellOffer: 4,
setOptions: 5,
changeTrust: 6,
allowTrust: 7,
accountMerge: 8,
inflation: 9,
manageData: 10,
bumpSequence: 11,
manageBuyOffer: 12,
pathPaymentStrictSend: 13,
createClaimableBalance: 14,
claimClaimableBalance: 15,
beginSponsoringFutureReserves: 16,
endSponsoringFutureReserves: 17,
revokeSponsorship: 18,
clawback: 19,
clawbackClaimableBalance: 20,
setTrustLineFlags: 21,
liquidityPoolDeposit: 22,
liquidityPoolWithdraw: 23,
});
// === xdr source ============================================================
//
// struct CreateAccountOp
// {
// AccountID destination; // account to create
// int64 startingBalance; // amount they end up with
// };
//
// ===========================================================================
xdr.struct("CreateAccountOp", [
["destination", xdr.lookup("AccountId")],
["startingBalance", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct PaymentOp
// {
// MuxedAccount destination; // recipient of the payment
// Asset asset; // what they end up with
// int64 amount; // amount they end up with
// };
//
// ===========================================================================
xdr.struct("PaymentOp", [
["destination", xdr.lookup("MuxedAccount")],
["asset", xdr.lookup("Asset")],
["amount", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct PathPaymentStrictReceiveOp
// {
// Asset sendAsset; // asset we pay with
// int64 sendMax; // the maximum amount of sendAsset to
// // send (excluding fees).
// // The operation will fail if can't be met
//
// MuxedAccount destination; // recipient of the payment
// Asset destAsset; // what they end up with
// int64 destAmount; // amount they end up with
//
// Asset path<5>; // additional hops it must go through to get there
// };
//
// ===========================================================================
xdr.struct("PathPaymentStrictReceiveOp", [
["sendAsset", xdr.lookup("Asset")],
["sendMax", xdr.lookup("Int64")],
["destination", xdr.lookup("MuxedAccount")],
["destAsset", xdr.lookup("Asset")],
["destAmount", xdr.lookup("Int64")],
["path", xdr.varArray(xdr.lookup("Asset"), 5)],
]);
// === xdr source ============================================================
//
// struct PathPaymentStrictSendOp
// {
// Asset sendAsset; // asset we pay with
// int64 sendAmount; // amount of sendAsset to send (excluding fees)
//
// MuxedAccount destination; // recipient of the payment
// Asset destAsset; // what they end up with
// int64 destMin; // the minimum amount of dest asset to
// // be received
// // The operation will fail if it can't be met
//
// Asset path<5>; // additional hops it must go through to get there
// };
//
// ===========================================================================
xdr.struct("PathPaymentStrictSendOp", [
["sendAsset", xdr.lookup("Asset")],
["sendAmount", xdr.lookup("Int64")],
["destination", xdr.lookup("MuxedAccount")],
["destAsset", xdr.lookup("Asset")],
["destMin", xdr.lookup("Int64")],
["path", xdr.varArray(xdr.lookup("Asset"), 5)],
]);
// === xdr source ============================================================
//
// struct ManageSellOfferOp
// {
// Asset selling;
// Asset buying;
// int64 amount; // amount being sold. if set to 0, delete the offer
// Price price; // price of thing being sold in terms of what you are buying
//
// // 0=create a new offer, otherwise edit an existing offer
// int64 offerID;
// };
//
// ===========================================================================
xdr.struct("ManageSellOfferOp", [
["selling", xdr.lookup("Asset")],
["buying", xdr.lookup("Asset")],
["amount", xdr.lookup("Int64")],
["price", xdr.lookup("Price")],
["offerId", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct ManageBuyOfferOp
// {
// Asset selling;
// Asset buying;
// int64 buyAmount; // amount being bought. if set to 0, delete the offer
// Price price; // price of thing being bought in terms of what you are
// // selling
//
// // 0=create a new offer, otherwise edit an existing offer
// int64 offerID;
// };
//
// ===========================================================================
xdr.struct("ManageBuyOfferOp", [
["selling", xdr.lookup("Asset")],
["buying", xdr.lookup("Asset")],
["buyAmount", xdr.lookup("Int64")],
["price", xdr.lookup("Price")],
["offerId", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct CreatePassiveSellOfferOp
// {
// Asset selling; // A
// Asset buying; // B
// int64 amount; // amount taker gets
// Price price; // cost of A in terms of B
// };
//
// ===========================================================================
xdr.struct("CreatePassiveSellOfferOp", [
["selling", xdr.lookup("Asset")],
["buying", xdr.lookup("Asset")],
["amount", xdr.lookup("Int64")],
["price", xdr.lookup("Price")],
]);
// === xdr source ============================================================
//
// struct SetOptionsOp
// {
// AccountID* inflationDest; // sets the inflation destination
//
// uint32* clearFlags; // which flags to clear
// uint32* setFlags; // which flags to set
//
// // account threshold manipulation
// uint32* masterWeight; // weight of the master account
// uint32* lowThreshold;
// uint32* medThreshold;
// uint32* highThreshold;
//
// string32* homeDomain; // sets the home domain
//
// // Add, update or remove a signer for the account
// // signer is deleted if the weight is 0
// Signer* signer;
// };
//
// ===========================================================================
xdr.struct("SetOptionsOp", [
["inflationDest", xdr.option(xdr.lookup("AccountId"))],
["clearFlags", xdr.option(xdr.lookup("Uint32"))],
["setFlags", xdr.option(xdr.lookup("Uint32"))],
["masterWeight", xdr.option(xdr.lookup("Uint32"))],
["lowThreshold", xdr.option(xdr.lookup("Uint32"))],
["medThreshold", xdr.option(xdr.lookup("Uint32"))],
["highThreshold", xdr.option(xdr.lookup("Uint32"))],
["homeDomain", xdr.option(xdr.lookup("String32"))],
["signer", xdr.option(xdr.lookup("Signer"))],
]);
// === xdr source ============================================================
//
// union ChangeTrustAsset switch (AssetType type)
// {
// case ASSET_TYPE_NATIVE: // Not credit
// void;
//
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AlphaNum4 alphaNum4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AlphaNum12 alphaNum12;
//
// case ASSET_TYPE_POOL_SHARE:
// LiquidityPoolParameters liquidityPool;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("ChangeTrustAsset", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [
["assetTypeNative", xdr.void()],
["assetTypeCreditAlphanum4", "alphaNum4"],
["assetTypeCreditAlphanum12", "alphaNum12"],
["assetTypePoolShare", "liquidityPool"],
],
arms: {
alphaNum4: xdr.lookup("AlphaNum4"),
alphaNum12: xdr.lookup("AlphaNum12"),
liquidityPool: xdr.lookup("LiquidityPoolParameters"),
},
});
// === xdr source ============================================================
//
// struct ChangeTrustOp
// {
// ChangeTrustAsset line;
//
// // if limit is set to 0, deletes the trust line
// int64 limit;
// };
//
// ===========================================================================
xdr.struct("ChangeTrustOp", [
["line", xdr.lookup("ChangeTrustAsset")],
["limit", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct AllowTrustOp
// {
// AccountID trustor;
// AssetCode asset;
//
// // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG
// uint32 authorize;
// };
//
// ===========================================================================
xdr.struct("AllowTrustOp", [
["trustor", xdr.lookup("AccountId")],
["asset", xdr.lookup("AssetCode")],
["authorize", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// struct ManageDataOp
// {
// string64 dataName;
// DataValue* dataValue; // set to null to clear
// };
//
// ===========================================================================
xdr.struct("ManageDataOp", [
["dataName", xdr.lookup("String64")],
["dataValue", xdr.option(xdr.lookup("DataValue"))],
]);
// === xdr source ============================================================
//
// struct BumpSequenceOp
// {
// SequenceNumber bumpTo;
// };
//
// ===========================================================================
xdr.struct("BumpSequenceOp", [
["bumpTo", xdr.lookup("SequenceNumber")],
]);
// === xdr source ============================================================
//
// struct CreateClaimableBalanceOp
// {
// Asset asset;
// int64 amount;
// Claimant claimants<10>;
// };
//
// ===========================================================================
xdr.struct("CreateClaimableBalanceOp", [
["asset", xdr.lookup("Asset")],
["amount", xdr.lookup("Int64")],
["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)],
]);
// === xdr source ============================================================
//
// struct ClaimClaimableBalanceOp
// {
// ClaimableBalanceID balanceID;
// };
//
// ===========================================================================
xdr.struct("ClaimClaimableBalanceOp", [
["balanceId", xdr.lookup("ClaimableBalanceId")],
]);
// === xdr source ============================================================
//
// struct BeginSponsoringFutureReservesOp
// {
// AccountID sponsoredID;
// };
//
// ===========================================================================
xdr.struct("BeginSponsoringFutureReservesOp", [
["sponsoredId", xdr.lookup("AccountId")],
]);
// === xdr source ============================================================
//
// enum RevokeSponsorshipType
// {
// REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0,
// REVOKE_SPONSORSHIP_SIGNER = 1
// };
//
// ===========================================================================
xdr.enum("RevokeSponsorshipType", {
revokeSponsorshipLedgerEntry: 0,
revokeSponsorshipSigner: 1,
});
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// SignerKey signerKey;
// }
//
// ===========================================================================
xdr.struct("RevokeSponsorshipOpSigner", [
["accountId", xdr.lookup("AccountId")],
["signerKey", xdr.lookup("SignerKey")],
]);
// === xdr source ============================================================
//
// union RevokeSponsorshipOp switch (RevokeSponsorshipType type)
// {
// case REVOKE_SPONSORSHIP_LEDGER_ENTRY:
// LedgerKey ledgerKey;
// case REVOKE_SPONSORSHIP_SIGNER:
// struct
// {
// AccountID accountID;
// SignerKey signerKey;
// } signer;
// };
//
// ===========================================================================
xdr.union("RevokeSponsorshipOp", {
switchOn: xdr.lookup("RevokeSponsorshipType"),
switchName: "type",
switches: [
["revokeSponsorshipLedgerEntry", "ledgerKey"],
["revokeSponsorshipSigner", "signer"],
],
arms: {
ledgerKey: xdr.lookup("LedgerKey"),
signer: xdr.lookup("RevokeSponsorshipOpSigner"),
},
});
// === xdr source ============================================================
//
// struct ClawbackOp
// {
// Asset asset;
// MuxedAccount from;
// int64 amount;
// };
//
// ===========================================================================
xdr.struct("ClawbackOp", [
["asset", xdr.lookup("Asset")],
["from", xdr.lookup("MuxedAccount")],
["amount", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct ClawbackClaimableBalanceOp
// {
// ClaimableBalanceID balanceID;
// };
//
// ===========================================================================
xdr.struct("ClawbackClaimableBalanceOp", [
["balanceId", xdr.lookup("ClaimableBalanceId")],
]);
// === xdr source ============================================================
//
// struct SetTrustLineFlagsOp
// {
// AccountID trustor;
// Asset asset;
//
// uint32 clearFlags; // which flags to clear
// uint32 setFlags; // which flags to set
// };
//
// ===========================================================================
xdr.struct("SetTrustLineFlagsOp", [
["trustor", xdr.lookup("AccountId")],
["asset", xdr.lookup("Asset")],
["clearFlags", xdr.lookup("Uint32")],
["setFlags", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// const LIQUIDITY_POOL_FEE_V18 = 30;
//
// ===========================================================================
xdr.const("LIQUIDITY_POOL_FEE_V18", 30);
// === xdr source ============================================================
//
// struct LiquidityPoolDepositOp
// {
// PoolID liquidityPoolID;
// int64 maxAmountA; // maximum amount of first asset to deposit
// int64 maxAmountB; // maximum amount of second asset to deposit
// Price minPrice; // minimum depositA/depositB
// Price maxPrice; // maximum depositA/depositB
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolDepositOp", [
["liquidityPoolId", xdr.lookup("PoolId")],
["maxAmountA", xdr.lookup("Int64")],
["maxAmountB", xdr.lookup("Int64")],
["minPrice", xdr.lookup("Price")],
["maxPrice", xdr.lookup("Price")],
]);
// === xdr source ============================================================
//
// struct LiquidityPoolWithdrawOp
// {
// PoolID liquidityPoolID;
// int64 amount; // amount of pool shares to withdraw
// int64 minAmountA; // minimum amount of first asset to withdraw
// int64 minAmountB; // minimum amount of second asset to withdraw
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolWithdrawOp", [
["liquidityPoolId", xdr.lookup("PoolId")],
["amount", xdr.lookup("Int64")],
["minAmountA", xdr.lookup("Int64")],
["minAmountB", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountOp createAccountOp;
// case PAYMENT:
// PaymentOp paymentOp;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp;
// case MANAGE_SELL_OFFER:
// ManageSellOfferOp manageSellOfferOp;
// case CREATE_PASSIVE_SELL_OFFER:
// CreatePassiveSellOfferOp createPassiveSellOfferOp;
// case SET_OPTIONS:
// SetOptionsOp setOptionsOp;
// case CHANGE_TRUST:
// ChangeTrustOp changeTrustOp;
// case ALLOW_TRUST:
// AllowTrustOp allowTrustOp;
// case ACCOUNT_MERGE:
// MuxedAccount destination;
// case INFLATION:
// void;
// case MANAGE_DATA:
// ManageDataOp manageDataOp;
// case BUMP_SEQUENCE:
// BumpSequenceOp bumpSequenceOp;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferOp manageBuyOfferOp;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendOp pathPaymentStrictSendOp;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceOp createClaimableBalanceOp;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceOp claimClaimableBalanceOp;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp;
// case END_SPONSORING_FUTURE_RESERVES:
// void;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipOp revokeSponsorshipOp;
// case CLAWBACK:
// ClawbackOp clawbackOp;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceOp clawbackClaimableBalanceOp;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsOp setTrustLineFlagsOp;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositOp liquidityPoolDepositOp;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawOp liquidityPoolWithdrawOp;
// }
//
// ===========================================================================
xdr.union("OperationBody", {
switchOn: xdr.lookup("OperationType"),
switchName: "type",
switches: [
["createAccount", "createAccountOp"],
["payment", "paymentOp"],
["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"],
["manageSellOffer", "manageSellOfferOp"],
["createPassiveSellOffer", "createPassiveSellOfferOp"],
["setOptions", "setOptionsOp"],
["changeTrust", "changeTrustOp"],
["allowTrust", "allowTrustOp"],
["accountMerge", "destination"],
["inflation", xdr.void()],
["manageData", "manageDataOp"],
["bumpSequence", "bumpSequenceOp"],
["manageBuyOffer", "manageBuyOfferOp"],
["pathPaymentStrictSend", "pathPaymentStrictSendOp"],
["createClaimableBalance", "createClaimableBalanceOp"],
["claimClaimableBalance", "claimClaimableBalanceOp"],
["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"],
["endSponsoringFutureReserves", xdr.void()],
["revokeSponsorship", "revokeSponsorshipOp"],
["clawback", "clawbackOp"],
["clawbackClaimableBalance", "clawbackClaimableBalanceOp"],
["setTrustLineFlags", "setTrustLineFlagsOp"],
["liquidityPoolDeposit", "liquidityPoolDepositOp"],
["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"],
],
arms: {
createAccountOp: xdr.lookup("CreateAccountOp"),
paymentOp: xdr.lookup("PaymentOp"),
pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"),
manageSellOfferOp: xdr.lookup("ManageSellOfferOp"),
createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"),
setOptionsOp: xdr.lookup("SetOptionsOp"),
changeTrustOp: xdr.lookup("ChangeTrustOp"),
allowTrustOp: xdr.lookup("AllowTrustOp"),
destination: xdr.lookup("MuxedAccount"),
manageDataOp: xdr.lookup("ManageDataOp"),
bumpSequenceOp: xdr.lookup("BumpSequenceOp"),
manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"),
pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"),
createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"),
claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"),
beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"),
revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"),
clawbackOp: xdr.lookup("ClawbackOp"),
clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"),
setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"),
liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"),
liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"),
},
});
// === xdr source ============================================================
//
// struct Operation
// {
// // sourceAccount is the account used to run the operation
// // if not set, the runtime defaults to "sourceAccount" specified at
// // the transaction level
// MuxedAccount* sourceAccount;
//
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountOp createAccountOp;
// case PAYMENT:
// PaymentOp paymentOp;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp;
// case MANAGE_SELL_OFFER:
// ManageSellOfferOp manageSellOfferOp;
// case CREATE_PASSIVE_SELL_OFFER:
// CreatePassiveSellOfferOp createPassiveSellOfferOp;
// case SET_OPTIONS:
// SetOptionsOp setOptionsOp;
// case CHANGE_TRUST:
// ChangeTrustOp changeTrustOp;
// case ALLOW_TRUST:
// AllowTrustOp allowTrustOp;
// case ACCOUNT_MERGE:
// MuxedAccount destination;
// case INFLATION:
// void;
// case MANAGE_DATA:
// ManageDataOp manageDataOp;
// case BUMP_SEQUENCE:
// BumpSequenceOp bumpSequenceOp;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferOp manageBuyOfferOp;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendOp pathPaymentStrictSendOp;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceOp createClaimableBalanceOp;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceOp claimClaimableBalanceOp;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp;
// case END_SPONSORING_FUTURE_RESERVES:
// void;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipOp revokeSponsorshipOp;
// case CLAWBACK:
// ClawbackOp clawbackOp;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceOp clawbackClaimableBalanceOp;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsOp setTrustLineFlagsOp;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositOp liquidityPoolDepositOp;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawOp liquidityPoolWithdrawOp;
// }
// body;
// };
//
// ===========================================================================
xdr.struct("Operation", [
["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))],
["body", xdr.lookup("OperationBody")],
]);
// === xdr source ============================================================
//
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// }
//
// ===========================================================================
xdr.struct("HashIdPreimageOperationId", [
["sourceAccount", xdr.lookup("AccountId")],
["seqNum", xdr.lookup("SequenceNumber")],
["opNum", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// PoolID liquidityPoolID;
// Asset asset;
// }
//
// ===========================================================================
xdr.struct("HashIdPreimageRevokeId", [
["sourceAccount", xdr.lookup("AccountId")],
["seqNum", xdr.lookup("SequenceNumber")],
["opNum", xdr.lookup("Uint32")],
["liquidityPoolId", xdr.lookup("PoolId")],
["asset", xdr.lookup("Asset")],
]);
// === xdr source ============================================================
//
// union HashIDPreimage switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_OP_ID:
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// } operationID;
// case ENVELOPE_TYPE_POOL_REVOKE_OP_ID:
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// PoolID liquidityPoolID;
// Asset asset;
// } revokeID;
// };
//
// ===========================================================================
xdr.union("HashIdPreimage", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [
["envelopeTypeOpId", "operationId"],
["envelopeTypePoolRevokeOpId", "revokeId"],
],
arms: {
operationId: xdr.lookup("HashIdPreimageOperationId"),
revokeId: xdr.lookup("HashIdPreimageRevokeId"),
},
});
// === xdr source ============================================================
//
// enum MemoType
// {
// MEMO_NONE = 0,
// MEMO_TEXT = 1,
// MEMO_ID = 2,
// MEMO_HASH = 3,
// MEMO_RETURN = 4
// };
//
// ===========================================================================
xdr.enum("MemoType", {
memoNone: 0,
memoText: 1,
memoId: 2,
memoHash: 3,
memoReturn: 4,
});
// === xdr source ============================================================
//
// union Memo switch (MemoType type)
// {
// case MEMO_NONE:
// void;
// case MEMO_TEXT:
// string text<28>;
// case MEMO_ID:
// uint64 id;
// case MEMO_HASH:
// Hash hash; // the hash of what to pull from the content server
// case MEMO_RETURN:
// Hash retHash; // the hash of the tx you are rejecting
// };
//
// ===========================================================================
xdr.union("Memo", {
switchOn: xdr.lookup("MemoType"),
switchName: "type",
switches: [
["memoNone", xdr.void()],
["memoText", "text"],
["memoId", "id"],
["memoHash", "hash"],
["memoReturn", "retHash"],
],
arms: {
text: xdr.string(28),
id: xdr.lookup("Uint64"),
hash: xdr.lookup("Hash"),
retHash: xdr.lookup("Hash"),
},
});
// === xdr source ============================================================
//
// struct TimeBounds
// {
// TimePoint minTime;
// TimePoint maxTime; // 0 here means no maxTime
// };
//
// ===========================================================================
xdr.struct("TimeBounds", [
["minTime", xdr.lookup("TimePoint")],
["maxTime", xdr.lookup("TimePoint")],
]);
// === xdr source ============================================================
//
// struct LedgerBounds
// {
// uint32 minLedger;
// uint32 maxLedger; // 0 here means no maxLedger
// };
//
// ===========================================================================
xdr.struct("LedgerBounds", [
["minLedger", xdr.lookup("Uint32")],
["maxLedger", xdr.lookup("Uint32")],
]);
// === xdr source ============================================================
//
// struct PreconditionsV2
// {
// TimeBounds* timeBounds;
//
// // Transaction only valid for ledger numbers n such that
// // minLedger <= n < maxLedger (if maxLedger == 0, then
// // only minLedger is checked)
// LedgerBounds* ledgerBounds;
//
// // If NULL, only valid when sourceAccount's sequence number
// // is seqNum - 1. Otherwise, valid when sourceAccount's
// // sequence number n satisfies minSeqNum <= n < tx.seqNum.
// // Note that after execution the account's sequence number
// // is always raised to tx.seqNum, and a transaction is not
// // valid if tx.seqNum is too high to ensure replay protection.
// SequenceNumber* minSeqNum;
//
// // For the transaction to be valid, the current ledger time must
// // be at least minSeqAge greater than sourceAccount's seqTime.
// Duration minSeqAge;
//
// // For the transaction to be valid, the current ledger number
// // must be at least minSeqLedgerGap greater than sourceAccount's
// // seqLedger.
// uint32 minSeqLedgerGap;
//
// // For the transaction to be valid, there must be a signature
// // corresponding to every Signer in this array, even if the
// // signature is not otherwise required by the sourceAccount or
// // operations.
// SignerKey extraSigners<2>;
// };
//
// ===========================================================================
xdr.struct("PreconditionsV2", [
["timeBounds", xdr.option(xdr.lookup("TimeBounds"))],
["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))],
["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))],
["minSeqAge", xdr.lookup("Duration")],
["minSeqLedgerGap", xdr.lookup("Uint32")],
["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)],
]);
// === xdr source ============================================================
//
// enum PreconditionType
// {
// PRECOND_NONE = 0,
// PRECOND_TIME = 1,
// PRECOND_V2 = 2
// };
//
// ===========================================================================
xdr.enum("PreconditionType", {
precondNone: 0,
precondTime: 1,
precondV2: 2,
});
// === xdr source ============================================================
//
// union Preconditions switch (PreconditionType type)
// {
// case PRECOND_NONE:
// void;
// case PRECOND_TIME:
// TimeBounds timeBounds;
// case PRECOND_V2:
// PreconditionsV2 v2;
// };
//
// ===========================================================================
xdr.union("Preconditions", {
switchOn: xdr.lookup("PreconditionType"),
switchName: "type",
switches: [
["precondNone", xdr.void()],
["precondTime", "timeBounds"],
["precondV2", "v2"],
],
arms: {
timeBounds: xdr.lookup("TimeBounds"),
v2: xdr.lookup("PreconditionsV2"),
},
});
// === xdr source ============================================================
//
// const MAX_OPS_PER_TX = 100;
//
// ===========================================================================
xdr.const("MAX_OPS_PER_TX", 100);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionV0Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct TransactionV0
// {
// uint256 sourceAccountEd25519;
// uint32 fee;
// SequenceNumber seqNum;
// TimeBounds* timeBounds;
// Memo memo;
// Operation operations<MAX_OPS_PER_TX>;
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionV0", [
["sourceAccountEd25519", xdr.lookup("Uint256")],
["fee", xdr.lookup("Uint32")],
["seqNum", xdr.lookup("SequenceNumber")],
["timeBounds", xdr.option(xdr.lookup("TimeBounds"))],
["memo", xdr.lookup("Memo")],
["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))],
["ext", xdr.lookup("TransactionV0Ext")],
]);
// === xdr source ============================================================
//
// struct TransactionV0Envelope
// {
// TransactionV0 tx;
// /* Each decorated signature is a signature over the SHA256 hash of
// * a TransactionSignaturePayload */
// DecoratedSignature signatures<20>;
// };
//
// ===========================================================================
xdr.struct("TransactionV0Envelope", [
["tx", xdr.lookup("TransactionV0")],
["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)],
]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct Transaction
// {
// // account used to run the transaction
// MuxedAccount sourceAccount;
//
// // the fee the sourceAccount will pay
// uint32 fee;
//
// // sequence number to consume in the account
// SequenceNumber seqNum;
//
// // validity conditions
// Preconditions cond;
//
// Memo memo;
//
// Operation operations<MAX_OPS_PER_TX>;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("Transaction", [
["sourceAccount", xdr.lookup("MuxedAccount")],
["fee", xdr.lookup("Uint32")],
["seqNum", xdr.lookup("SequenceNumber")],
["cond", xdr.lookup("Preconditions")],
["memo", xdr.lookup("Memo")],
["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))],
["ext", xdr.lookup("TransactionExt")],
]);
// === xdr source ============================================================
//
// struct TransactionV1Envelope
// {
// Transaction tx;
// /* Each decorated signature is a signature over the SHA256 hash of
// * a TransactionSignaturePayload */
// DecoratedSignature signatures<20>;
// };
//
// ===========================================================================
xdr.struct("TransactionV1Envelope", [
["tx", xdr.lookup("Transaction")],
["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)],
]);
// === xdr source ============================================================
//
// union switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_TX:
// TransactionV1Envelope v1;
// }
//
// ===========================================================================
xdr.union("FeeBumpTransactionInnerTx", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [
["envelopeTypeTx", "v1"],
],
arms: {
v1: xdr.lookup("TransactionV1Envelope"),
},
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("FeeBumpTransactionExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct FeeBumpTransaction
// {
// MuxedAccount feeSource;
// int64 fee;
// union switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_TX:
// TransactionV1Envelope v1;
// }
// innerTx;
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("FeeBumpTransaction", [
["feeSource", xdr.lookup("MuxedAccount")],
["fee", xdr.lookup("Int64")],
["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")],
["ext", xdr.lookup("FeeBumpTransactionExt")],
]);
// === xdr source ============================================================
//
// struct FeeBumpTransactionEnvelope
// {
// FeeBumpTransaction tx;
// /* Each decorated signature is a signature over the SHA256 hash of
// * a TransactionSignaturePayload */
// DecoratedSignature signatures<20>;
// };
//
// ===========================================================================
xdr.struct("FeeBumpTransactionEnvelope", [
["tx", xdr.lookup("FeeBumpTransaction")],
["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)],
]);
// === xdr source ============================================================
//
// union TransactionEnvelope switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_TX_V0:
// TransactionV0Envelope v0;
// case ENVELOPE_TYPE_TX:
// TransactionV1Envelope v1;
// case ENVELOPE_TYPE_TX_FEE_BUMP:
// FeeBumpTransactionEnvelope feeBump;
// };
//
// ===========================================================================
xdr.union("TransactionEnvelope", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [
["envelopeTypeTxV0", "v0"],
["envelopeTypeTx", "v1"],
["envelopeTypeTxFeeBump", "feeBump"],
],
arms: {
v0: xdr.lookup("TransactionV0Envelope"),
v1: xdr.lookup("TransactionV1Envelope"),
feeBump: xdr.lookup("FeeBumpTransactionEnvelope"),
},
});
// === xdr source ============================================================
//
// union switch (EnvelopeType type)
// {
// // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0
// case ENVELOPE_TYPE_TX:
// Transaction tx;
// case ENVELOPE_TYPE_TX_FEE_BUMP:
// FeeBumpTransaction feeBump;
// }
//
// ===========================================================================
xdr.union("TransactionSignaturePayloadTaggedTransaction", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [
["envelopeTypeTx", "tx"],
["envelopeTypeTxFeeBump", "feeBump"],
],
arms: {
tx: xdr.lookup("Transaction"),
feeBump: xdr.lookup("FeeBumpTransaction"),
},
});
// === xdr source ============================================================
//
// struct TransactionSignaturePayload
// {
// Hash networkId;
// union switch (EnvelopeType type)
// {
// // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0
// case ENVELOPE_TYPE_TX:
// Transaction tx;
// case ENVELOPE_TYPE_TX_FEE_BUMP:
// FeeBumpTransaction feeBump;
// }
// taggedTransaction;
// };
//
// ===========================================================================
xdr.struct("TransactionSignaturePayload", [
["networkId", xdr.lookup("Hash")],
["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")],
]);
// === xdr source ============================================================
//
// enum ClaimAtomType
// {
// CLAIM_ATOM_TYPE_V0 = 0,
// CLAIM_ATOM_TYPE_ORDER_BOOK = 1,
// CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2
// };
//
// ===========================================================================
xdr.enum("ClaimAtomType", {
claimAtomTypeV0: 0,
claimAtomTypeOrderBook: 1,
claimAtomTypeLiquidityPool: 2,
});
// === xdr source ============================================================
//
// struct ClaimOfferAtomV0
// {
// // emitted to identify the offer
// uint256 sellerEd25519; // Account that owns the offer
// int64 offerID;
//
// // amount and asset taken from the owner
// Asset assetSold;
// int64 amountSold;
//
// // amount and asset sent to the owner
// Asset assetBought;
// int64 amountBought;
// };
//
// ===========================================================================
xdr.struct("ClaimOfferAtomV0", [
["sellerEd25519", xdr.lookup("Uint256")],
["offerId", xdr.lookup("Int64")],
["assetSold", xdr.lookup("Asset")],
["amountSold", xdr.lookup("Int64")],
["assetBought", xdr.lookup("Asset")],
["amountBought", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct ClaimOfferAtom
// {
// // emitted to identify the offer
// AccountID sellerID; // Account that owns the offer
// int64 offerID;
//
// // amount and asset taken from the owner
// Asset assetSold;
// int64 amountSold;
//
// // amount and asset sent to the owner
// Asset assetBought;
// int64 amountBought;
// };
//
// ===========================================================================
xdr.struct("ClaimOfferAtom", [
["sellerId", xdr.lookup("AccountId")],
["offerId", xdr.lookup("Int64")],
["assetSold", xdr.lookup("Asset")],
["amountSold", xdr.lookup("Int64")],
["assetBought", xdr.lookup("Asset")],
["amountBought", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct ClaimLiquidityAtom
// {
// PoolID liquidityPoolID;
//
// // amount and asset taken from the pool
// Asset assetSold;
// int64 amountSold;
//
// // amount and asset sent to the pool
// Asset assetBought;
// int64 amountBought;
// };
//
// ===========================================================================
xdr.struct("ClaimLiquidityAtom", [
["liquidityPoolId", xdr.lookup("PoolId")],
["assetSold", xdr.lookup("Asset")],
["amountSold", xdr.lookup("Int64")],
["assetBought", xdr.lookup("Asset")],
["amountBought", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// union ClaimAtom switch (ClaimAtomType type)
// {
// case CLAIM_ATOM_TYPE_V0:
// ClaimOfferAtomV0 v0;
// case CLAIM_ATOM_TYPE_ORDER_BOOK:
// ClaimOfferAtom orderBook;
// case CLAIM_ATOM_TYPE_LIQUIDITY_POOL:
// ClaimLiquidityAtom liquidityPool;
// };
//
// ===========================================================================
xdr.union("ClaimAtom", {
switchOn: xdr.lookup("ClaimAtomType"),
switchName: "type",
switches: [
["claimAtomTypeV0", "v0"],
["claimAtomTypeOrderBook", "orderBook"],
["claimAtomTypeLiquidityPool", "liquidityPool"],
],
arms: {
v0: xdr.lookup("ClaimOfferAtomV0"),
orderBook: xdr.lookup("ClaimOfferAtom"),
liquidityPool: xdr.lookup("ClaimLiquidityAtom"),
},
});
// === xdr source ============================================================
//
// enum CreateAccountResultCode
// {
// // codes considered as "success" for the operation
// CREATE_ACCOUNT_SUCCESS = 0, // account was created
//
// // codes considered as "failure" for the operation
// CREATE_ACCOUNT_MALFORMED = -1, // invalid destination
// CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account
// CREATE_ACCOUNT_LOW_RESERVE =
// -3, // would create an account below the min reserve
// CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists
// };
//
// ===========================================================================
xdr.enum("CreateAccountResultCode", {
createAccountSuccess: 0,
createAccountMalformed: -1,
createAccountUnderfunded: -2,
createAccountLowReserve: -3,
createAccountAlreadyExist: -4,
});
// === xdr source ============================================================
//
// union CreateAccountResult switch (CreateAccountResultCode code)
// {
// case CREATE_ACCOUNT_SUCCESS:
// void;
// case CREATE_ACCOUNT_MALFORMED:
// case CREATE_ACCOUNT_UNDERFUNDED:
// case CREATE_ACCOUNT_LOW_RESERVE:
// case CREATE_ACCOUNT_ALREADY_EXIST:
// void;
// };
//
// ===========================================================================
xdr.union("CreateAccountResult", {
switchOn: xdr.lookup("CreateAccountResultCode"),
switchName: "code",
switches: [
["createAccountSuccess", xdr.void()],
["createAccountMalformed", xdr.void()],
["createAccountUnderfunded", xdr.void()],
["createAccountLowReserve", xdr.void()],
["createAccountAlreadyExist", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum PaymentResultCode
// {
// // codes considered as "success" for the operation
// PAYMENT_SUCCESS = 0, // payment successfully completed
//
// // codes considered as "failure" for the operation
// PAYMENT_MALFORMED = -1, // bad input
// PAYMENT_UNDERFUNDED = -2, // not enough funds in source account
// PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account
// PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer
// PAYMENT_NO_DESTINATION = -5, // destination account does not exist
// PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset
// PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset
// PAYMENT_LINE_FULL = -8, // destination would go above their limit
// PAYMENT_NO_ISSUER = -9 // missing issuer on asset
// };
//
// ===========================================================================
xdr.enum("PaymentResultCode", {
paymentSuccess: 0,
paymentMalformed: -1,
paymentUnderfunded: -2,
paymentSrcNoTrust: -3,
paymentSrcNotAuthorized: -4,
paymentNoDestination: -5,
paymentNoTrust: -6,
paymentNotAuthorized: -7,
paymentLineFull: -8,
paymentNoIssuer: -9,
});
// === xdr source ============================================================
//
// union PaymentResult switch (PaymentResultCode code)
// {
// case PAYMENT_SUCCESS:
// void;
// case PAYMENT_MALFORMED:
// case PAYMENT_UNDERFUNDED:
// case PAYMENT_SRC_NO_TRUST:
// case PAYMENT_SRC_NOT_AUTHORIZED:
// case PAYMENT_NO_DESTINATION:
// case PAYMENT_NO_TRUST:
// case PAYMENT_NOT_AUTHORIZED:
// case PAYMENT_LINE_FULL:
// case PAYMENT_NO_ISSUER:
// void;
// };
//
// ===========================================================================
xdr.union("PaymentResult", {
switchOn: xdr.lookup("PaymentResultCode"),
switchName: "code",
switches: [
["paymentSuccess", xdr.void()],
["paymentMalformed", xdr.void()],
["paymentUnderfunded", xdr.void()],
["paymentSrcNoTrust", xdr.void()],
["paymentSrcNotAuthorized", xdr.void()],
["paymentNoDestination", xdr.void()],
["paymentNoTrust", xdr.void()],
["paymentNotAuthorized", xdr.void()],
["paymentLineFull", xdr.void()],
["paymentNoIssuer", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum PathPaymentStrictReceiveResultCode
// {
// // codes considered as "success" for the operation
// PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success
//
// // codes considered as "failure" for the operation
// PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input
// PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED =
// -2, // not enough funds in source account
// PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST =
// -3, // no trust line on source account
// PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED =
// -4, // source not authorized to transfer
// PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION =
// -5, // destination account does not exist
// PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST =
// -6, // dest missing a trust line for asset
// PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED =
// -7, // dest not authorized to hold asset
// PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL =
// -8, // dest would go above their limit
// PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset
// PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS =
// -10, // not enough offers to satisfy path
// PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF =
// -11, // would cross one of its own offers
// PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax
// };
//
// ===========================================================================
xdr.enum("PathPaymentStrictReceiveResultCode", {
pathPaymentStrictReceiveSuccess: 0,
pathPaymentStrictReceiveMalformed: -1,
pathPaymentStrictReceiveUnderfunded: -2,
pathPaymentStrictReceiveSrcNoTrust: -3,
pathPaymentStrictReceiveSrcNotAuthorized: -4,
pathPaymentStrictReceiveNoDestination: -5,
pathPaymentStrictReceiveNoTrust: -6,
pathPaymentStrictReceiveNotAuthorized: -7,
pathPaymentStrictReceiveLineFull: -8,
pathPaymentStrictReceiveNoIssuer: -9,
pathPaymentStrictReceiveTooFewOffers: -10,
pathPaymentStrictReceiveOfferCrossSelf: -11,
pathPaymentStrictReceiveOverSendmax: -12,
});
// === xdr source ============================================================
//
// struct SimplePaymentResult
// {
// AccountID destination;
// Asset asset;
// int64 amount;
// };
//
// ===========================================================================
xdr.struct("SimplePaymentResult", [
["destination", xdr.lookup("AccountId")],
["asset", xdr.lookup("Asset")],
["amount", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// }
//
// ===========================================================================
xdr.struct("PathPaymentStrictReceiveResultSuccess", [
["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)],
["last", xdr.lookup("SimplePaymentResult")],
]);
// === xdr source ============================================================
//
// union PathPaymentStrictReceiveResult switch (
// PathPaymentStrictReceiveResultCode code)
// {
// case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS:
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// } success;
// case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED:
// case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED:
// case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST:
// case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION:
// case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST:
// case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL:
// void;
// case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER:
// Asset noIssuer; // the asset that caused the error
// case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS:
// case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF:
// case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX:
// void;
// };
//
// ===========================================================================
xdr.union("PathPaymentStrictReceiveResult", {
switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"),
switchName: "code",
switches: [
["pathPaymentStrictReceiveSuccess", "success"],
["pathPaymentStrictReceiveMalformed", xdr.void()],
["pathPaymentStrictReceiveUnderfunded", xdr.void()],
["pathPaymentStrictReceiveSrcNoTrust", xdr.void()],
["pathPaymentStrictReceiveSrcNotAuthorized", xdr.void()],
["pathPaymentStrictReceiveNoDestination", xdr.void()],
["pathPaymentStrictReceiveNoTrust", xdr.void()],
["pathPaymentStrictReceiveNotAuthorized", xdr.void()],
["pathPaymentStrictReceiveLineFull", xdr.void()],
["pathPaymentStrictReceiveNoIssuer", "noIssuer"],
["pathPaymentStrictReceiveTooFewOffers", xdr.void()],
["pathPaymentStrictReceiveOfferCrossSelf", xdr.void()],
["pathPaymentStrictReceiveOverSendmax", xdr.void()],
],
arms: {
success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"),
noIssuer: xdr.lookup("Asset"),
},
});
// === xdr source ============================================================
//
// enum PathPaymentStrictSendResultCode
// {
// // codes considered as "success" for the operation
// PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success
//
// // codes considered as "failure" for the operation
// PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input
// PATH_PAYMENT_STRICT_SEND_UNDERFUNDED =
// -2, // not enough funds in source account
// PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST =
// -3, // no trust line on source account
// PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED =
// -4, // source not authorized to transfer
// PATH_PAYMENT_STRICT_SEND_NO_DESTINATION =
// -5, // destination account does not exist
// PATH_PAYMENT_STRICT_SEND_NO_TRUST =
// -6, // dest missing a trust line for asset
// PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED =
// -7, // dest not authorized to hold asset
// PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit
// PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset
// PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS =
// -10, // not enough offers to satisfy path
// PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF =
// -11, // would cross one of its own offers
// PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin
// };
//
// ===========================================================================
xdr.enum("PathPaymentStrictSendResultCode", {
pathPaymentStrictSendSuccess: 0,
pathPaymentStrictSendMalformed: -1,
pathPaymentStrictSendUnderfunded: -2,
pathPaymentStrictSendSrcNoTrust: -3,
pathPaymentStrictSendSrcNotAuthorized: -4,
pathPaymentStrictSendNoDestination: -5,
pathPaymentStrictSendNoTrust: -6,
pathPaymentStrictSendNotAuthorized: -7,
pathPaymentStrictSendLineFull: -8,
pathPaymentStrictSendNoIssuer: -9,
pathPaymentStrictSendTooFewOffers: -10,
pathPaymentStrictSendOfferCrossSelf: -11,
pathPaymentStrictSendUnderDestmin: -12,
});
// === xdr source ============================================================
//
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// }
//
// ===========================================================================
xdr.struct("PathPaymentStrictSendResultSuccess", [
["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)],
["last", xdr.lookup("SimplePaymentResult")],
]);
// === xdr source ============================================================
//
// union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code)
// {
// case PATH_PAYMENT_STRICT_SEND_SUCCESS:
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// } success;
// case PATH_PAYMENT_STRICT_SEND_MALFORMED:
// case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED:
// case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST:
// case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION:
// case PATH_PAYMENT_STRICT_SEND_NO_TRUST:
// case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_SEND_LINE_FULL:
// void;
// case PATH_PAYMENT_STRICT_SEND_NO_ISSUER:
// Asset noIssuer; // the asset that caused the error
// case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS:
// case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF:
// case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN:
// void;
// };
//
// ===========================================================================
xdr.union("PathPaymentStrictSendResult", {
switchOn: xdr.lookup("PathPaymentStrictSendResultCode"),
switchName: "code",
switches: [
["pathPaymentStrictSendSuccess", "success"],
["pathPaymentStrictSendMalformed", xdr.void()],
["pathPaymentStrictSendUnderfunded", xdr.void()],
["pathPaymentStrictSendSrcNoTrust", xdr.void()],
["pathPaymentStrictSendSrcNotAuthorized", xdr.void()],
["pathPaymentStrictSendNoDestination", xdr.void()],
["pathPaymentStrictSendNoTrust", xdr.void()],
["pathPaymentStrictSendNotAuthorized", xdr.void()],
["pathPaymentStrictSendLineFull", xdr.void()],
["pathPaymentStrictSendNoIssuer", "noIssuer"],
["pathPaymentStrictSendTooFewOffers", xdr.void()],
["pathPaymentStrictSendOfferCrossSelf", xdr.void()],
["pathPaymentStrictSendUnderDestmin", xdr.void()],
],
arms: {
success: xdr.lookup("PathPaymentStrictSendResultSuccess"),
noIssuer: xdr.lookup("Asset"),
},
});
// === xdr source ============================================================
//
// enum ManageSellOfferResultCode
// {
// // codes considered as "success" for the operation
// MANAGE_SELL_OFFER_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid
// MANAGE_SELL_OFFER_SELL_NO_TRUST =
// -2, // no trust line for what we're selling
// MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying
// MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell
// MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy
// MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying
// MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell
// MANAGE_SELL_OFFER_CROSS_SELF =
// -8, // would cross an offer from the same user
// MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling
// MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying
//
// // update errors
// MANAGE_SELL_OFFER_NOT_FOUND =
// -11, // offerID does not match an existing offer
//
// MANAGE_SELL_OFFER_LOW_RESERVE =
// -12 // not enough funds to create a new Offer
// };
//
// ===========================================================================
xdr.enum("ManageSellOfferResultCode", {
manageSellOfferSuccess: 0,
manageSellOfferMalformed: -1,
manageSellOfferSellNoTrust: -2,
manageSellOfferBuyNoTrust: -3,
manageSellOfferSellNotAuthorized: -4,
manageSellOfferBuyNotAuthorized: -5,
manageSellOfferLineFull: -6,
manageSellOfferUnderfunded: -7,
manageSellOfferCrossSelf: -8,
manageSellOfferSellNoIssuer: -9,
manageSellOfferBuyNoIssuer: -10,
manageSellOfferNotFound: -11,
manageSellOfferLowReserve: -12,
});
// === xdr source ============================================================
//
// enum ManageOfferEffect
// {
// MANAGE_OFFER_CREATED = 0,
// MANAGE_OFFER_UPDATED = 1,
// MANAGE_OFFER_DELETED = 2
// };
//
// ===========================================================================
xdr.enum("ManageOfferEffect", {
manageOfferCreated: 0,
manageOfferUpdated: 1,
manageOfferDeleted: 2,
});
// === xdr source ============================================================
//
// union switch (ManageOfferEffect effect)
// {
// case MANAGE_OFFER_CREATED:
// case MANAGE_OFFER_UPDATED:
// OfferEntry offer;
// case MANAGE_OFFER_DELETED:
// void;
// }
//
// ===========================================================================
xdr.union("ManageOfferSuccessResultOffer", {
switchOn: xdr.lookup("ManageOfferEffect"),
switchName: "effect",
switches: [
["manageOfferCreated", "offer"],
["manageOfferUpdated", "offer"],
["manageOfferDeleted", xdr.void()],
],
arms: {
offer: xdr.lookup("OfferEntry"),
},
});
// === xdr source ============================================================
//
// struct ManageOfferSuccessResult
// {
// // offers that got claimed while creating this offer
// ClaimAtom offersClaimed<>;
//
// union switch (ManageOfferEffect effect)
// {
// case MANAGE_OFFER_CREATED:
// case MANAGE_OFFER_UPDATED:
// OfferEntry offer;
// case MANAGE_OFFER_DELETED:
// void;
// }
// offer;
// };
//
// ===========================================================================
xdr.struct("ManageOfferSuccessResult", [
["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)],
["offer", xdr.lookup("ManageOfferSuccessResultOffer")],
]);
// === xdr source ============================================================
//
// union ManageSellOfferResult switch (ManageSellOfferResultCode code)
// {
// case MANAGE_SELL_OFFER_SUCCESS:
// ManageOfferSuccessResult success;
// case MANAGE_SELL_OFFER_MALFORMED:
// case MANAGE_SELL_OFFER_SELL_NO_TRUST:
// case MANAGE_SELL_OFFER_BUY_NO_TRUST:
// case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED:
// case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED:
// case MANAGE_SELL_OFFER_LINE_FULL:
// case MANAGE_SELL_OFFER_UNDERFUNDED:
// case MANAGE_SELL_OFFER_CROSS_SELF:
// case MANAGE_SELL_OFFER_SELL_NO_ISSUER:
// case MANAGE_SELL_OFFER_BUY_NO_ISSUER:
// case MANAGE_SELL_OFFER_NOT_FOUND:
// case MANAGE_SELL_OFFER_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("ManageSellOfferResult", {
switchOn: xdr.lookup("ManageSellOfferResultCode"),
switchName: "code",
switches: [
["manageSellOfferSuccess", "success"],
["manageSellOfferMalformed", xdr.void()],
["manageSellOfferSellNoTrust", xdr.void()],
["manageSellOfferBuyNoTrust", xdr.void()],
["manageSellOfferSellNotAuthorized", xdr.void()],
["manageSellOfferBuyNotAuthorized", xdr.void()],
["manageSellOfferLineFull", xdr.void()],
["manageSellOfferUnderfunded", xdr.void()],
["manageSellOfferCrossSelf", xdr.void()],
["manageSellOfferSellNoIssuer", xdr.void()],
["manageSellOfferBuyNoIssuer", xdr.void()],
["manageSellOfferNotFound", xdr.void()],
["manageSellOfferLowReserve", xdr.void()],
],
arms: {
success: xdr.lookup("ManageOfferSuccessResult"),
},
});
// === xdr source ============================================================
//
// enum ManageBuyOfferResultCode
// {
// // codes considered as "success" for the operation
// MANAGE_BUY_OFFER_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid
// MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling
// MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying
// MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell
// MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy
// MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying
// MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell
// MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user
// MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling
// MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying
//
// // update errors
// MANAGE_BUY_OFFER_NOT_FOUND =
// -11, // offerID does not match an existing offer
//
// MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer
// };
//
// ===========================================================================
xdr.enum("ManageBuyOfferResultCode", {
manageBuyOfferSuccess: 0,
manageBuyOfferMalformed: -1,
manageBuyOfferSellNoTrust: -2,
manageBuyOfferBuyNoTrust: -3,
manageBuyOfferSellNotAuthorized: -4,
manageBuyOfferBuyNotAuthorized: -5,
manageBuyOfferLineFull: -6,
manageBuyOfferUnderfunded: -7,
manageBuyOfferCrossSelf: -8,
manageBuyOfferSellNoIssuer: -9,
manageBuyOfferBuyNoIssuer: -10,
manageBuyOfferNotFound: -11,
manageBuyOfferLowReserve: -12,
});
// === xdr source ============================================================
//
// union ManageBuyOfferResult switch (ManageBuyOfferResultCode code)
// {
// case MANAGE_BUY_OFFER_SUCCESS:
// ManageOfferSuccessResult success;
// case MANAGE_BUY_OFFER_MALFORMED:
// case MANAGE_BUY_OFFER_SELL_NO_TRUST:
// case MANAGE_BUY_OFFER_BUY_NO_TRUST:
// case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED:
// case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED:
// case MANAGE_BUY_OFFER_LINE_FULL:
// case MANAGE_BUY_OFFER_UNDERFUNDED:
// case MANAGE_BUY_OFFER_CROSS_SELF:
// case MANAGE_BUY_OFFER_SELL_NO_ISSUER:
// case MANAGE_BUY_OFFER_BUY_NO_ISSUER:
// case MANAGE_BUY_OFFER_NOT_FOUND:
// case MANAGE_BUY_OFFER_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("ManageBuyOfferResult", {
switchOn: xdr.lookup("ManageBuyOfferResultCode"),
switchName: "code",
switches: [
["manageBuyOfferSuccess", "success"],
["manageBuyOfferMalformed", xdr.void()],
["manageBuyOfferSellNoTrust", xdr.void()],
["manageBuyOfferBuyNoTrust", xdr.void()],
["manageBuyOfferSellNotAuthorized", xdr.void()],
["manageBuyOfferBuyNotAuthorized", xdr.void()],
["manageBuyOfferLineFull", xdr.void()],
["manageBuyOfferUnderfunded", xdr.void()],
["manageBuyOfferCrossSelf", xdr.void()],
["manageBuyOfferSellNoIssuer", xdr.void()],
["manageBuyOfferBuyNoIssuer", xdr.void()],
["manageBuyOfferNotFound", xdr.void()],
["manageBuyOfferLowReserve", xdr.void()],
],
arms: {
success: xdr.lookup("ManageOfferSuccessResult"),
},
});
// === xdr source ============================================================
//
// enum SetOptionsResultCode
// {
// // codes considered as "success" for the operation
// SET_OPTIONS_SUCCESS = 0,
// // codes considered as "failure" for the operation
// SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer
// SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached
// SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags
// SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist
// SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option
// SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag
// SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold
// SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey
// SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain
// SET_OPTIONS_AUTH_REVOCABLE_REQUIRED =
// -10 // auth revocable is required for clawback
// };
//
// ===========================================================================
xdr.enum("SetOptionsResultCode", {
setOptionsSuccess: 0,
setOptionsLowReserve: -1,
setOptionsTooManySigners: -2,
setOptionsBadFlags: -3,
setOptionsInvalidInflation: -4,
setOptionsCantChange: -5,
setOptionsUnknownFlag: -6,
setOptionsThresholdOutOfRange: -7,
setOptionsBadSigner: -8,
setOptionsInvalidHomeDomain: -9,
setOptionsAuthRevocableRequired: -10,
});
// === xdr source ============================================================
//
// union SetOptionsResult switch (SetOptionsResultCode code)
// {
// case SET_OPTIONS_SUCCESS:
// void;
// case SET_OPTIONS_LOW_RESERVE:
// case SET_OPTIONS_TOO_MANY_SIGNERS:
// case SET_OPTIONS_BAD_FLAGS:
// case SET_OPTIONS_INVALID_INFLATION:
// case SET_OPTIONS_CANT_CHANGE:
// case SET_OPTIONS_UNKNOWN_FLAG:
// case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE:
// case SET_OPTIONS_BAD_SIGNER:
// case SET_OPTIONS_INVALID_HOME_DOMAIN:
// case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED:
// void;
// };
//
// ===========================================================================
xdr.union("SetOptionsResult", {
switchOn: xdr.lookup("SetOptionsResultCode"),
switchName: "code",
switches: [
["setOptionsSuccess", xdr.void()],
["setOptionsLowReserve", xdr.void()],
["setOptionsTooManySigners", xdr.void()],
["setOptionsBadFlags", xdr.void()],
["setOptionsInvalidInflation", xdr.void()],
["setOptionsCantChange", xdr.void()],
["setOptionsUnknownFlag", xdr.void()],
["setOptionsThresholdOutOfRange", xdr.void()],
["setOptionsBadSigner", xdr.void()],
["setOptionsInvalidHomeDomain", xdr.void()],
["setOptionsAuthRevocableRequired", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum ChangeTrustResultCode
// {
// // codes considered as "success" for the operation
// CHANGE_TRUST_SUCCESS = 0,
// // codes considered as "failure" for the operation
// CHANGE_TRUST_MALFORMED = -1, // bad input
// CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer
// CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance
// // cannot create with a limit of 0
// CHANGE_TRUST_LOW_RESERVE =
// -4, // not enough funds to create a new trust line,
// CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed
// CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool
// CHANGE_TRUST_CANNOT_DELETE =
// -7, // Asset trustline is still referenced in a pool
// CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES =
// -8 // Asset trustline is deauthorized
// };
//
// ===========================================================================
xdr.enum("ChangeTrustResultCode", {
changeTrustSuccess: 0,
changeTrustMalformed: -1,
changeTrustNoIssuer: -2,
changeTrustInvalidLimit: -3,
changeTrustLowReserve: -4,
changeTrustSelfNotAllowed: -5,
changeTrustTrustLineMissing: -6,
changeTrustCannotDelete: -7,
changeTrustNotAuthMaintainLiabilities: -8,
});
// === xdr source ============================================================
//
// union ChangeTrustResult switch (ChangeTrustResultCode code)
// {
// case CHANGE_TRUST_SUCCESS:
// void;
// case CHANGE_TRUST_MALFORMED:
// case CHANGE_TRUST_NO_ISSUER:
// case CHANGE_TRUST_INVALID_LIMIT:
// case CHANGE_TRUST_LOW_RESERVE:
// case CHANGE_TRUST_SELF_NOT_ALLOWED:
// case CHANGE_TRUST_TRUST_LINE_MISSING:
// case CHANGE_TRUST_CANNOT_DELETE:
// case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES:
// void;
// };
//
// ===========================================================================
xdr.union("ChangeTrustResult", {
switchOn: xdr.lookup("ChangeTrustResultCode"),
switchName: "code",
switches: [
["changeTrustSuccess", xdr.void()],
["changeTrustMalformed", xdr.void()],
["changeTrustNoIssuer", xdr.void()],
["changeTrustInvalidLimit", xdr.void()],
["changeTrustLowReserve", xdr.void()],
["changeTrustSelfNotAllowed", xdr.void()],
["changeTrustTrustLineMissing", xdr.void()],
["changeTrustCannotDelete", xdr.void()],
["changeTrustNotAuthMaintainLiabilities", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum AllowTrustResultCode
// {
// // codes considered as "success" for the operation
// ALLOW_TRUST_SUCCESS = 0,
// // codes considered as "failure" for the operation
// ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM
// ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline
// // source account does not require trust
// ALLOW_TRUST_TRUST_NOT_REQUIRED = -3,
// ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust,
// ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed
// ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created
// // on revoke due to low reserves
// };
//
// ===========================================================================
xdr.enum("AllowTrustResultCode", {
allowTrustSuccess: 0,
allowTrustMalformed: -1,
allowTrustNoTrustLine: -2,
allowTrustTrustNotRequired: -3,
allowTrustCantRevoke: -4,
allowTrustSelfNotAllowed: -5,
allowTrustLowReserve: -6,
});
// === xdr source ============================================================
//
// union AllowTrustResult switch (AllowTrustResultCode code)
// {
// case ALLOW_TRUST_SUCCESS:
// void;
// case ALLOW_TRUST_MALFORMED:
// case ALLOW_TRUST_NO_TRUST_LINE:
// case ALLOW_TRUST_TRUST_NOT_REQUIRED:
// case ALLOW_TRUST_CANT_REVOKE:
// case ALLOW_TRUST_SELF_NOT_ALLOWED:
// case ALLOW_TRUST_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("AllowTrustResult", {
switchOn: xdr.lookup("AllowTrustResultCode"),
switchName: "code",
switches: [
["allowTrustSuccess", xdr.void()],
["allowTrustMalformed", xdr.void()],
["allowTrustNoTrustLine", xdr.void()],
["allowTrustTrustNotRequired", xdr.void()],
["allowTrustCantRevoke", xdr.void()],
["allowTrustSelfNotAllowed", xdr.void()],
["allowTrustLowReserve", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum AccountMergeResultCode
// {
// // codes considered as "success" for the operation
// ACCOUNT_MERGE_SUCCESS = 0,
// // codes considered as "failure" for the operation
// ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself
// ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist
// ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set
// ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers
// ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed
// ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to
// // destination balance
// ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor
// };
//
// ===========================================================================
xdr.enum("AccountMergeResultCode", {
accountMergeSuccess: 0,
accountMergeMalformed: -1,
accountMergeNoAccount: -2,
accountMergeImmutableSet: -3,
accountMergeHasSubEntries: -4,
accountMergeSeqnumTooFar: -5,
accountMergeDestFull: -6,
accountMergeIsSponsor: -7,
});
// === xdr source ============================================================
//
// union AccountMergeResult switch (AccountMergeResultCode code)
// {
// case ACCOUNT_MERGE_SUCCESS:
// int64 sourceAccountBalance; // how much got transferred from source account
// case ACCOUNT_MERGE_MALFORMED:
// case ACCOUNT_MERGE_NO_ACCOUNT:
// case ACCOUNT_MERGE_IMMUTABLE_SET:
// case ACCOUNT_MERGE_HAS_SUB_ENTRIES:
// case ACCOUNT_MERGE_SEQNUM_TOO_FAR:
// case ACCOUNT_MERGE_DEST_FULL:
// case ACCOUNT_MERGE_IS_SPONSOR:
// void;
// };
//
// ===========================================================================
xdr.union("AccountMergeResult", {
switchOn: xdr.lookup("AccountMergeResultCode"),
switchName: "code",
switches: [
["accountMergeSuccess", "sourceAccountBalance"],
["accountMergeMalformed", xdr.void()],
["accountMergeNoAccount", xdr.void()],
["accountMergeImmutableSet", xdr.void()],
["accountMergeHasSubEntries", xdr.void()],
["accountMergeSeqnumTooFar", xdr.void()],
["accountMergeDestFull", xdr.void()],
["accountMergeIsSponsor", xdr.void()],
],
arms: {
sourceAccountBalance: xdr.lookup("Int64"),
},
});
// === xdr source ============================================================
//
// enum InflationResultCode
// {
// // codes considered as "success" for the operation
// INFLATION_SUCCESS = 0,
// // codes considered as "failure" for the operation
// INFLATION_NOT_TIME = -1
// };
//
// ===========================================================================
xdr.enum("InflationResultCode", {
inflationSuccess: 0,
inflationNotTime: -1,
});
// === xdr source ============================================================
//
// struct InflationPayout // or use PaymentResultAtom to limit types?
// {
// AccountID destination;
// int64 amount;
// };
//
// ===========================================================================
xdr.struct("InflationPayout", [
["destination", xdr.lookup("AccountId")],
["amount", xdr.lookup("Int64")],
]);
// === xdr source ============================================================
//
// union InflationResult switch (InflationResultCode code)
// {
// case INFLATION_SUCCESS:
// InflationPayout payouts<>;
// case INFLATION_NOT_TIME:
// void;
// };
//
// ===========================================================================
xdr.union("InflationResult", {
switchOn: xdr.lookup("InflationResultCode"),
switchName: "code",
switches: [
["inflationSuccess", "payouts"],
["inflationNotTime", xdr.void()],
],
arms: {
payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647),
},
});
// === xdr source ============================================================
//
// enum ManageDataResultCode
// {
// // codes considered as "success" for the operation
// MANAGE_DATA_SUCCESS = 0,
// // codes considered as "failure" for the operation
// MANAGE_DATA_NOT_SUPPORTED_YET =
// -1, // The network hasn't moved to this protocol change yet
// MANAGE_DATA_NAME_NOT_FOUND =
// -2, // Trying to remove a Data Entry that isn't there
// MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry
// MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string
// };
//
// ===========================================================================
xdr.enum("ManageDataResultCode", {
manageDataSuccess: 0,
manageDataNotSupportedYet: -1,
manageDataNameNotFound: -2,
manageDataLowReserve: -3,
manageDataInvalidName: -4,
});
// === xdr source ============================================================
//
// union ManageDataResult switch (ManageDataResultCode code)
// {
// case MANAGE_DATA_SUCCESS:
// void;
// case MANAGE_DATA_NOT_SUPPORTED_YET:
// case MANAGE_DATA_NAME_NOT_FOUND:
// case MANAGE_DATA_LOW_RESERVE:
// case MANAGE_DATA_INVALID_NAME:
// void;
// };
//
// ===========================================================================
xdr.union("ManageDataResult", {
switchOn: xdr.lookup("ManageDataResultCode"),
switchName: "code",
switches: [
["manageDataSuccess", xdr.void()],
["manageDataNotSupportedYet", xdr.void()],
["manageDataNameNotFound", xdr.void()],
["manageDataLowReserve", xdr.void()],
["manageDataInvalidName", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum BumpSequenceResultCode
// {
// // codes considered as "success" for the operation
// BUMP_SEQUENCE_SUCCESS = 0,
// // codes considered as "failure" for the operation
// BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds
// };
//
// ===========================================================================
xdr.enum("BumpSequenceResultCode", {
bumpSequenceSuccess: 0,
bumpSequenceBadSeq: -1,
});
// === xdr source ============================================================
//
// union BumpSequenceResult switch (BumpSequenceResultCode code)
// {
// case BUMP_SEQUENCE_SUCCESS:
// void;
// case BUMP_SEQUENCE_BAD_SEQ:
// void;
// };
//
// ===========================================================================
xdr.union("BumpSequenceResult", {
switchOn: xdr.lookup("BumpSequenceResultCode"),
switchName: "code",
switches: [
["bumpSequenceSuccess", xdr.void()],
["bumpSequenceBadSeq", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum CreateClaimableBalanceResultCode
// {
// CREATE_CLAIMABLE_BALANCE_SUCCESS = 0,
// CREATE_CLAIMABLE_BALANCE_MALFORMED = -1,
// CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2,
// CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3,
// CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4,
// CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5
// };
//
// ===========================================================================
xdr.enum("CreateClaimableBalanceResultCode", {
createClaimableBalanceSuccess: 0,
createClaimableBalanceMalformed: -1,
createClaimableBalanceLowReserve: -2,
createClaimableBalanceNoTrust: -3,
createClaimableBalanceNotAuthorized: -4,
createClaimableBalanceUnderfunded: -5,
});
// === xdr source ============================================================
//
// union CreateClaimableBalanceResult switch (
// CreateClaimableBalanceResultCode code)
// {
// case CREATE_CLAIMABLE_BALANCE_SUCCESS:
// ClaimableBalanceID balanceID;
// case CREATE_CLAIMABLE_BALANCE_MALFORMED:
// case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE:
// case CREATE_CLAIMABLE_BALANCE_NO_TRUST:
// case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED:
// case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED:
// void;
// };
//
// ===========================================================================
xdr.union("CreateClaimableBalanceResult", {
switchOn: xdr.lookup("CreateClaimableBalanceResultCode"),
switchName: "code",
switches: [
["createClaimableBalanceSuccess", "balanceId"],
["createClaimableBalanceMalformed", xdr.void()],
["createClaimableBalanceLowReserve", xdr.void()],
["createClaimableBalanceNoTrust", xdr.void()],
["createClaimableBalanceNotAuthorized", xdr.void()],
["createClaimableBalanceUnderfunded", xdr.void()],
],
arms: {
balanceId: xdr.lookup("ClaimableBalanceId"),
},
});
// === xdr source ============================================================
//
// enum ClaimClaimableBalanceResultCode
// {
// CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0,
// CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1,
// CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2,
// CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3,
// CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4,
// CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5
// };
//
// ===========================================================================
xdr.enum("ClaimClaimableBalanceResultCode", {
claimClaimableBalanceSuccess: 0,
claimClaimableBalanceDoesNotExist: -1,
claimClaimableBalanceCannotClaim: -2,
claimClaimableBalanceLineFull: -3,
claimClaimableBalanceNoTrust: -4,
claimClaimableBalanceNotAuthorized: -5,
});
// === xdr source ============================================================
//
// union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code)
// {
// case CLAIM_CLAIMABLE_BALANCE_SUCCESS:
// void;
// case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST:
// case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM:
// case CLAIM_CLAIMABLE_BALANCE_LINE_FULL:
// case CLAIM_CLAIMABLE_BALANCE_NO_TRUST:
// case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED:
// void;
// };
//
// ===========================================================================
xdr.union("ClaimClaimableBalanceResult", {
switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"),
switchName: "code",
switches: [
["claimClaimableBalanceSuccess", xdr.void()],
["claimClaimableBalanceDoesNotExist", xdr.void()],
["claimClaimableBalanceCannotClaim", xdr.void()],
["claimClaimableBalanceLineFull", xdr.void()],
["claimClaimableBalanceNoTrust", xdr.void()],
["claimClaimableBalanceNotAuthorized", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum BeginSponsoringFutureReservesResultCode
// {
// // codes considered as "success" for the operation
// BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1,
// BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2,
// BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3
// };
//
// ===========================================================================
xdr.enum("BeginSponsoringFutureReservesResultCode", {
beginSponsoringFutureReservesSuccess: 0,
beginSponsoringFutureReservesMalformed: -1,
beginSponsoringFutureReservesAlreadySponsored: -2,
beginSponsoringFutureReservesRecursive: -3,
});
// === xdr source ============================================================
//
// union BeginSponsoringFutureReservesResult switch (
// BeginSponsoringFutureReservesResultCode code)
// {
// case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS:
// void;
// case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED:
// case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED:
// case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE:
// void;
// };
//
// ===========================================================================
xdr.union("BeginSponsoringFutureReservesResult", {
switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"),
switchName: "code",
switches: [
["beginSponsoringFutureReservesSuccess", xdr.void()],
["beginSponsoringFutureReservesMalformed", xdr.void()],
["beginSponsoringFutureReservesAlreadySponsored", xdr.void()],
["beginSponsoringFutureReservesRecursive", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum EndSponsoringFutureReservesResultCode
// {
// // codes considered as "success" for the operation
// END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1
// };
//
// ===========================================================================
xdr.enum("EndSponsoringFutureReservesResultCode", {
endSponsoringFutureReservesSuccess: 0,
endSponsoringFutureReservesNotSponsored: -1,
});
// === xdr source ============================================================
//
// union EndSponsoringFutureReservesResult switch (
// EndSponsoringFutureReservesResultCode code)
// {
// case END_SPONSORING_FUTURE_RESERVES_SUCCESS:
// void;
// case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED:
// void;
// };
//
// ===========================================================================
xdr.union("EndSponsoringFutureReservesResult", {
switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"),
switchName: "code",
switches: [
["endSponsoringFutureReservesSuccess", xdr.void()],
["endSponsoringFutureReservesNotSponsored", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum RevokeSponsorshipResultCode
// {
// // codes considered as "success" for the operation
// REVOKE_SPONSORSHIP_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1,
// REVOKE_SPONSORSHIP_NOT_SPONSOR = -2,
// REVOKE_SPONSORSHIP_LOW_RESERVE = -3,
// REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4,
// REVOKE_SPONSORSHIP_MALFORMED = -5
// };
//
// ===========================================================================
xdr.enum("RevokeSponsorshipResultCode", {
revokeSponsorshipSuccess: 0,
revokeSponsorshipDoesNotExist: -1,
revokeSponsorshipNotSponsor: -2,
revokeSponsorshipLowReserve: -3,
revokeSponsorshipOnlyTransferable: -4,
revokeSponsorshipMalformed: -5,
});
// === xdr source ============================================================
//
// union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code)
// {
// case REVOKE_SPONSORSHIP_SUCCESS:
// void;
// case REVOKE_SPONSORSHIP_DOES_NOT_EXIST:
// case REVOKE_SPONSORSHIP_NOT_SPONSOR:
// case REVOKE_SPONSORSHIP_LOW_RESERVE:
// case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE:
// case REVOKE_SPONSORSHIP_MALFORMED:
// void;
// };
//
// ===========================================================================
xdr.union("RevokeSponsorshipResult", {
switchOn: xdr.lookup("RevokeSponsorshipResultCode"),
switchName: "code",
switches: [
["revokeSponsorshipSuccess", xdr.void()],
["revokeSponsorshipDoesNotExist", xdr.void()],
["revokeSponsorshipNotSponsor", xdr.void()],
["revokeSponsorshipLowReserve", xdr.void()],
["revokeSponsorshipOnlyTransferable", xdr.void()],
["revokeSponsorshipMalformed", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum ClawbackResultCode
// {
// // codes considered as "success" for the operation
// CLAWBACK_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// CLAWBACK_MALFORMED = -1,
// CLAWBACK_NOT_CLAWBACK_ENABLED = -2,
// CLAWBACK_NO_TRUST = -3,
// CLAWBACK_UNDERFUNDED = -4
// };
//
// ===========================================================================
xdr.enum("ClawbackResultCode", {
clawbackSuccess: 0,
clawbackMalformed: -1,
clawbackNotClawbackEnabled: -2,
clawbackNoTrust: -3,
clawbackUnderfunded: -4,
});
// === xdr source ============================================================
//
// union ClawbackResult switch (ClawbackResultCode code)
// {
// case CLAWBACK_SUCCESS:
// void;
// case CLAWBACK_MALFORMED:
// case CLAWBACK_NOT_CLAWBACK_ENABLED:
// case CLAWBACK_NO_TRUST:
// case CLAWBACK_UNDERFUNDED:
// void;
// };
//
// ===========================================================================
xdr.union("ClawbackResult", {
switchOn: xdr.lookup("ClawbackResultCode"),
switchName: "code",
switches: [
["clawbackSuccess", xdr.void()],
["clawbackMalformed", xdr.void()],
["clawbackNotClawbackEnabled", xdr.void()],
["clawbackNoTrust", xdr.void()],
["clawbackUnderfunded", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum ClawbackClaimableBalanceResultCode
// {
// // codes considered as "success" for the operation
// CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1,
// CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2,
// CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3
// };
//
// ===========================================================================
xdr.enum("ClawbackClaimableBalanceResultCode", {
clawbackClaimableBalanceSuccess: 0,
clawbackClaimableBalanceDoesNotExist: -1,
clawbackClaimableBalanceNotIssuer: -2,
clawbackClaimableBalanceNotClawbackEnabled: -3,
});
// === xdr source ============================================================
//
// union ClawbackClaimableBalanceResult switch (
// ClawbackClaimableBalanceResultCode code)
// {
// case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS:
// void;
// case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST:
// case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER:
// case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED:
// void;
// };
//
// ===========================================================================
xdr.union("ClawbackClaimableBalanceResult", {
switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"),
switchName: "code",
switches: [
["clawbackClaimableBalanceSuccess", xdr.void()],
["clawbackClaimableBalanceDoesNotExist", xdr.void()],
["clawbackClaimableBalanceNotIssuer", xdr.void()],
["clawbackClaimableBalanceNotClawbackEnabled", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum SetTrustLineFlagsResultCode
// {
// // codes considered as "success" for the operation
// SET_TRUST_LINE_FLAGS_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// SET_TRUST_LINE_FLAGS_MALFORMED = -1,
// SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2,
// SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3,
// SET_TRUST_LINE_FLAGS_INVALID_STATE = -4,
// SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created
// // on revoke due to low reserves
// };
//
// ===========================================================================
xdr.enum("SetTrustLineFlagsResultCode", {
setTrustLineFlagsSuccess: 0,
setTrustLineFlagsMalformed: -1,
setTrustLineFlagsNoTrustLine: -2,
setTrustLineFlagsCantRevoke: -3,
setTrustLineFlagsInvalidState: -4,
setTrustLineFlagsLowReserve: -5,
});
// === xdr source ============================================================
//
// union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code)
// {
// case SET_TRUST_LINE_FLAGS_SUCCESS:
// void;
// case SET_TRUST_LINE_FLAGS_MALFORMED:
// case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE:
// case SET_TRUST_LINE_FLAGS_CANT_REVOKE:
// case SET_TRUST_LINE_FLAGS_INVALID_STATE:
// case SET_TRUST_LINE_FLAGS_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("SetTrustLineFlagsResult", {
switchOn: xdr.lookup("SetTrustLineFlagsResultCode"),
switchName: "code",
switches: [
["setTrustLineFlagsSuccess", xdr.void()],
["setTrustLineFlagsMalformed", xdr.void()],
["setTrustLineFlagsNoTrustLine", xdr.void()],
["setTrustLineFlagsCantRevoke", xdr.void()],
["setTrustLineFlagsInvalidState", xdr.void()],
["setTrustLineFlagsLowReserve", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum LiquidityPoolDepositResultCode
// {
// // codes considered as "success" for the operation
// LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input
// LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the
// // assets
// LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the
// // assets
// LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of
// // the assets
// LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't
// // have sufficient limit
// LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds
// LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full
// };
//
// ===========================================================================
xdr.enum("LiquidityPoolDepositResultCode", {
liquidityPoolDepositSuccess: 0,
liquidityPoolDepositMalformed: -1,
liquidityPoolDepositNoTrust: -2,
liquidityPoolDepositNotAuthorized: -3,
liquidityPoolDepositUnderfunded: -4,
liquidityPoolDepositLineFull: -5,
liquidityPoolDepositBadPrice: -6,
liquidityPoolDepositPoolFull: -7,
});
// === xdr source ============================================================
//
// union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code)
// {
// case LIQUIDITY_POOL_DEPOSIT_SUCCESS:
// void;
// case LIQUIDITY_POOL_DEPOSIT_MALFORMED:
// case LIQUIDITY_POOL_DEPOSIT_NO_TRUST:
// case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED:
// case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED:
// case LIQUIDITY_POOL_DEPOSIT_LINE_FULL:
// case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE:
// case LIQUIDITY_POOL_DEPOSIT_POOL_FULL:
// void;
// };
//
// ===========================================================================
xdr.union("LiquidityPoolDepositResult", {
switchOn: xdr.lookup("LiquidityPoolDepositResultCode"),
switchName: "code",
switches: [
["liquidityPoolDepositSuccess", xdr.void()],
["liquidityPoolDepositMalformed", xdr.void()],
["liquidityPoolDepositNoTrust", xdr.void()],
["liquidityPoolDepositNotAuthorized", xdr.void()],
["liquidityPoolDepositUnderfunded", xdr.void()],
["liquidityPoolDepositLineFull", xdr.void()],
["liquidityPoolDepositBadPrice", xdr.void()],
["liquidityPoolDepositPoolFull", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum LiquidityPoolWithdrawResultCode
// {
// // codes considered as "success" for the operation
// LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input
// LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the
// // assets
// LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the
// // pool share
// LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one
// // of the assets
// LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough
// };
//
// ===========================================================================
xdr.enum("LiquidityPoolWithdrawResultCode", {
liquidityPoolWithdrawSuccess: 0,
liquidityPoolWithdrawMalformed: -1,
liquidityPoolWithdrawNoTrust: -2,
liquidityPoolWithdrawUnderfunded: -3,
liquidityPoolWithdrawLineFull: -4,
liquidityPoolWithdrawUnderMinimum: -5,
});
// === xdr source ============================================================
//
// union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code)
// {
// case LIQUIDITY_POOL_WITHDRAW_SUCCESS:
// void;
// case LIQUIDITY_POOL_WITHDRAW_MALFORMED:
// case LIQUIDITY_POOL_WITHDRAW_NO_TRUST:
// case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED:
// case LIQUIDITY_POOL_WITHDRAW_LINE_FULL:
// case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM:
// void;
// };
//
// ===========================================================================
xdr.union("LiquidityPoolWithdrawResult", {
switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"),
switchName: "code",
switches: [
["liquidityPoolWithdrawSuccess", xdr.void()],
["liquidityPoolWithdrawMalformed", xdr.void()],
["liquidityPoolWithdrawNoTrust", xdr.void()],
["liquidityPoolWithdrawUnderfunded", xdr.void()],
["liquidityPoolWithdrawLineFull", xdr.void()],
["liquidityPoolWithdrawUnderMinimum", xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum OperationResultCode
// {
// opINNER = 0, // inner object result is valid
//
// opBAD_AUTH = -1, // too few valid signatures / wrong network
// opNO_ACCOUNT = -2, // source account was not found
// opNOT_SUPPORTED = -3, // operation not supported at this time
// opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached
// opEXCEEDED_WORK_LIMIT = -5, // operation did too much work
// opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries
// };
//
// ===========================================================================
xdr.enum("OperationResultCode", {
opInner: 0,
opBadAuth: -1,
opNoAccount: -2,
opNotSupported: -3,
opTooManySubentries: -4,
opExceededWorkLimit: -5,
opTooManySponsoring: -6,
});
// === xdr source ============================================================
//
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountResult createAccountResult;
// case PAYMENT:
// PaymentResult paymentResult;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult;
// case MANAGE_SELL_OFFER:
// ManageSellOfferResult manageSellOfferResult;
// case CREATE_PASSIVE_SELL_OFFER:
// ManageSellOfferResult createPassiveSellOfferResult;
// case SET_OPTIONS:
// SetOptionsResult setOptionsResult;
// case CHANGE_TRUST:
// ChangeTrustResult changeTrustResult;
// case ALLOW_TRUST:
// AllowTrustResult allowTrustResult;
// case ACCOUNT_MERGE:
// AccountMergeResult accountMergeResult;
// case INFLATION:
// InflationResult inflationResult;
// case MANAGE_DATA:
// ManageDataResult manageDataResult;
// case BUMP_SEQUENCE:
// BumpSequenceResult bumpSeqResult;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferResult manageBuyOfferResult;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendResult pathPaymentStrictSendResult;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceResult createClaimableBalanceResult;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceResult claimClaimableBalanceResult;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult;
// case END_SPONSORING_FUTURE_RESERVES:
// EndSponsoringFutureReservesResult endSponsoringFutureReservesResult;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipResult revokeSponsorshipResult;
// case CLAWBACK:
// ClawbackResult clawbackResult;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceResult clawbackClaimableBalanceResult;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsResult setTrustLineFlagsResult;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositResult liquidityPoolDepositResult;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawResult liquidityPoolWithdrawResult;
// }
//
// ===========================================================================
xdr.union("OperationResultTr", {
switchOn: xdr.lookup("OperationType"),
switchName: "type",
switches: [
["createAccount", "createAccountResult"],
["payment", "paymentResult"],
["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"],
["manageSellOffer", "manageSellOfferResult"],
["createPassiveSellOffer", "createPassiveSellOfferResult"],
["setOptions", "setOptionsResult"],
["changeTrust", "changeTrustResult"],
["allowTrust", "allowTrustResult"],
["accountMerge", "accountMergeResult"],
["inflation", "inflationResult"],
["manageData", "manageDataResult"],
["bumpSequence", "bumpSeqResult"],
["manageBuyOffer", "manageBuyOfferResult"],
["pathPaymentStrictSend", "pathPaymentStrictSendResult"],
["createClaimableBalance", "createClaimableBalanceResult"],
["claimClaimableBalance", "claimClaimableBalanceResult"],
["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"],
["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"],
["revokeSponsorship", "revokeSponsorshipResult"],
["clawback", "clawbackResult"],
["clawbackClaimableBalance", "clawbackClaimableBalanceResult"],
["setTrustLineFlags", "setTrustLineFlagsResult"],
["liquidityPoolDeposit", "liquidityPoolDepositResult"],
["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"],
],
arms: {
createAccountResult: xdr.lookup("CreateAccountResult"),
paymentResult: xdr.lookup("PaymentResult"),
pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"),
manageSellOfferResult: xdr.lookup("ManageSellOfferResult"),
createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"),
setOptionsResult: xdr.lookup("SetOptionsResult"),
changeTrustResult: xdr.lookup("ChangeTrustResult"),
allowTrustResult: xdr.lookup("AllowTrustResult"),
accountMergeResult: xdr.lookup("AccountMergeResult"),
inflationResult: xdr.lookup("InflationResult"),
manageDataResult: xdr.lookup("ManageDataResult"),
bumpSeqResult: xdr.lookup("BumpSequenceResult"),
manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"),
pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"),
createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"),
claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"),
beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"),
endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"),
revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"),
clawbackResult: xdr.lookup("ClawbackResult"),
clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"),
setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"),
liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"),
liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"),
},
});
// === xdr source ============================================================
//
// union OperationResult switch (OperationResultCode code)
// {
// case opINNER:
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountResult createAccountResult;
// case PAYMENT:
// PaymentResult paymentResult;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult;
// case MANAGE_SELL_OFFER:
// ManageSellOfferResult manageSellOfferResult;
// case CREATE_PASSIVE_SELL_OFFER:
// ManageSellOfferResult createPassiveSellOfferResult;
// case SET_OPTIONS:
// SetOptionsResult setOptionsResult;
// case CHANGE_TRUST:
// ChangeTrustResult changeTrustResult;
// case ALLOW_TRUST:
// AllowTrustResult allowTrustResult;
// case ACCOUNT_MERGE:
// AccountMergeResult accountMergeResult;
// case INFLATION:
// InflationResult inflationResult;
// case MANAGE_DATA:
// ManageDataResult manageDataResult;
// case BUMP_SEQUENCE:
// BumpSequenceResult bumpSeqResult;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferResult manageBuyOfferResult;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendResult pathPaymentStrictSendResult;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceResult createClaimableBalanceResult;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceResult claimClaimableBalanceResult;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult;
// case END_SPONSORING_FUTURE_RESERVES:
// EndSponsoringFutureReservesResult endSponsoringFutureReservesResult;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipResult revokeSponsorshipResult;
// case CLAWBACK:
// ClawbackResult clawbackResult;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceResult clawbackClaimableBalanceResult;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsResult setTrustLineFlagsResult;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositResult liquidityPoolDepositResult;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawResult liquidityPoolWithdrawResult;
// }
// tr;
// case opBAD_AUTH:
// case opNO_ACCOUNT:
// case opNOT_SUPPORTED:
// case opTOO_MANY_SUBENTRIES:
// case opEXCEEDED_WORK_LIMIT:
// case opTOO_MANY_SPONSORING:
// void;
// };
//
// ===========================================================================
xdr.union("OperationResult", {
switchOn: xdr.lookup("OperationResultCode"),
switchName: "code",
switches: [
["opInner", "tr"],
["opBadAuth", xdr.void()],
["opNoAccount", xdr.void()],
["opNotSupported", xdr.void()],
["opTooManySubentries", xdr.void()],
["opExceededWorkLimit", xdr.void()],
["opTooManySponsoring", xdr.void()],
],
arms: {
tr: xdr.lookup("OperationResultTr"),
},
});
// === xdr source ============================================================
//
// enum TransactionResultCode
// {
// txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded
// txSUCCESS = 0, // all operations succeeded
//
// txFAILED = -1, // one of the operations failed (none were applied)
//
// txTOO_EARLY = -2, // ledger closeTime before minTime
// txTOO_LATE = -3, // ledger closeTime after maxTime
// txMISSING_OPERATION = -4, // no operation was specified
// txBAD_SEQ = -5, // sequence number does not match source account
//
// txBAD_AUTH = -6, // too few valid signatures / wrong network
// txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve
// txNO_ACCOUNT = -8, // source account not found
// txINSUFFICIENT_FEE = -9, // fee is too small
// txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction
// txINTERNAL_ERROR = -11, // an unknown error occurred
//
// txNOT_SUPPORTED = -12, // transaction type not supported
// txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed
// txBAD_SPONSORSHIP = -14, // sponsorship not confirmed
// txBAD_MIN_SEQ_AGE_OR_GAP =
// -15, // minSeqAge or minSeqLedgerGap conditions not met
// txMALFORMED = -16 // precondition is invalid
// };
//
// ===========================================================================
xdr.enum("TransactionResultCode", {
txFeeBumpInnerSuccess: 1,
txSuccess: 0,
txFailed: -1,
txTooEarly: -2,
txTooLate: -3,
txMissingOperation: -4,
txBadSeq: -5,
txBadAuth: -6,
txInsufficientBalance: -7,
txNoAccount: -8,
txInsufficientFee: -9,
txBadAuthExtra: -10,
txInternalError: -11,
txNotSupported: -12,
txFeeBumpInnerFailed: -13,
txBadSponsorship: -14,
txBadMinSeqAgeOrGap: -15,
txMalformed: -16,
});
// === xdr source ============================================================
//
// union switch (TransactionResultCode code)
// {
// // txFEE_BUMP_INNER_SUCCESS is not included
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // txFEE_BUMP_INNER_FAILED is not included
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
//
// ===========================================================================
xdr.union("InnerTransactionResultResult", {
switchOn: xdr.lookup("TransactionResultCode"),
switchName: "code",
switches: [
["txSuccess", "results"],
["txFailed", "results"],
["txTooEarly", xdr.void()],
["txTooLate", xdr.void()],
["txMissingOperation", xdr.void()],
["txBadSeq", xdr.void()],
["txBadAuth", xdr.void()],
["txInsufficientBalance", xdr.void()],
["txNoAccount", xdr.void()],
["txInsufficientFee", xdr.void()],
["txBadAuthExtra", xdr.void()],
["txInternalError", xdr.void()],
["txNotSupported", xdr.void()],
["txBadSponsorship", xdr.void()],
["txBadMinSeqAgeOrGap", xdr.void()],
["txMalformed", xdr.void()],
],
arms: {
results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647),
},
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("InnerTransactionResultExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct InnerTransactionResult
// {
// // Always 0. Here for binary compatibility.
// int64 feeCharged;
//
// union switch (TransactionResultCode code)
// {
// // txFEE_BUMP_INNER_SUCCESS is not included
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // txFEE_BUMP_INNER_FAILED is not included
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
// result;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("InnerTransactionResult", [
["feeCharged", xdr.lookup("Int64")],
["result", xdr.lookup("InnerTransactionResultResult")],
["ext", xdr.lookup("InnerTransactionResultExt")],
]);
// === xdr source ============================================================
//
// struct InnerTransactionResultPair
// {
// Hash transactionHash; // hash of the inner transaction
// InnerTransactionResult result; // result for the inner transaction
// };
//
// ===========================================================================
xdr.struct("InnerTransactionResultPair", [
["transactionHash", xdr.lookup("Hash")],
["result", xdr.lookup("InnerTransactionResult")],
]);
// === xdr source ============================================================
//
// union switch (TransactionResultCode code)
// {
// case txFEE_BUMP_INNER_SUCCESS:
// case txFEE_BUMP_INNER_FAILED:
// InnerTransactionResultPair innerResultPair;
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // case txFEE_BUMP_INNER_FAILED: handled above
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionResultResult", {
switchOn: xdr.lookup("TransactionResultCode"),
switchName: "code",
switches: [
["txFeeBumpInnerSuccess", "innerResultPair"],
["txFeeBumpInnerFailed", "innerResultPair"],
["txSuccess", "results"],
["txFailed", "results"],
["txTooEarly", xdr.void()],
["txTooLate", xdr.void()],
["txMissingOperation", xdr.void()],
["txBadSeq", xdr.void()],
["txBadAuth", xdr.void()],
["txInsufficientBalance", xdr.void()],
["txNoAccount", xdr.void()],
["txInsufficientFee", xdr.void()],
["txBadAuthExtra", xdr.void()],
["txInternalError", xdr.void()],
["txNotSupported", xdr.void()],
["txBadSponsorship", xdr.void()],
["txBadMinSeqAgeOrGap", xdr.void()],
["txMalformed", xdr.void()],
],
arms: {
innerResultPair: xdr.lookup("InnerTransactionResultPair"),
results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647),
},
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionResultExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// struct TransactionResult
// {
// int64 feeCharged; // actual fee charged for the transaction
//
// union switch (TransactionResultCode code)
// {
// case txFEE_BUMP_INNER_SUCCESS:
// case txFEE_BUMP_INNER_FAILED:
// InnerTransactionResultPair innerResultPair;
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // case txFEE_BUMP_INNER_FAILED: handled above
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
// result;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionResult", [
["feeCharged", xdr.lookup("Int64")],
["result", xdr.lookup("TransactionResultResult")],
["ext", xdr.lookup("TransactionResultExt")],
]);
// === xdr source ============================================================
//
// typedef opaque Hash[32];
//
// ===========================================================================
xdr.typedef("Hash", xdr.opaque(32));
// === xdr source ============================================================
//
// typedef opaque uint256[32];
//
// ===========================================================================
xdr.typedef("Uint256", xdr.opaque(32));
// === xdr source ============================================================
//
// typedef unsigned int uint32;
//
// ===========================================================================
xdr.typedef("Uint32", xdr.uint());
// === xdr source ============================================================
//
// typedef int int32;
//
// ===========================================================================
xdr.typedef("Int32", xdr.int());
// === xdr source ============================================================
//
// typedef unsigned hyper uint64;
//
// ===========================================================================
xdr.typedef("Uint64", xdr.uhyper());
// === xdr source ============================================================
//
// typedef hyper int64;
//
// ===========================================================================
xdr.typedef("Int64", xdr.hyper());
// === xdr source ============================================================
//
// union ExtensionPoint switch (int v)
// {
// case 0:
// void;
// };
//
// ===========================================================================
xdr.union("ExtensionPoint", {
switchOn: xdr.int(),
switchName: "v",
switches: [
[0, xdr.void()],
],
arms: {
},
});
// === xdr source ============================================================
//
// enum CryptoKeyType
// {
// KEY_TYPE_ED25519 = 0,
// KEY_TYPE_PRE_AUTH_TX = 1,
// KEY_TYPE_HASH_X = 2,
// KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3,
// // MUXED enum values for supported type are derived from the enum values
// // above by ORing them with 0x100
// KEY_TYPE_MUXED_ED25519 = 0x100
// };
//
// ===========================================================================
xdr.enum("CryptoKeyType", {
keyTypeEd25519: 0,
keyTypePreAuthTx: 1,
keyTypeHashX: 2,
keyTypeEd25519SignedPayload: 3,
keyTypeMuxedEd25519: 256,
});
// === xdr source ============================================================
//
// enum PublicKeyType
// {
// PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519
// };
//
// ===========================================================================
xdr.enum("PublicKeyType", {
publicKeyTypeEd25519: 0,
});
// === xdr source ============================================================
//
// enum SignerKeyType
// {
// SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519,
// SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX,
// SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X,
// SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD
// };
//
// ===========================================================================
xdr.enum("SignerKeyType", {
signerKeyTypeEd25519: 0,
signerKeyTypePreAuthTx: 1,
signerKeyTypeHashX: 2,
signerKeyTypeEd25519SignedPayload: 3,
});
// === xdr source ============================================================
//
// union PublicKey switch (PublicKeyType type)
// {
// case PUBLIC_KEY_TYPE_ED25519:
// uint256 ed25519;
// };
//
// ===========================================================================
xdr.union("PublicKey", {
switchOn: xdr.lookup("PublicKeyType"),
switchName: "type",
switches: [
["publicKeyTypeEd25519", "ed25519"],
],
arms: {
ed25519: xdr.lookup("Uint256"),
},
});
// === xdr source ============================================================
//
// struct
// {
// /* Public key that must sign the payload. */
// uint256 ed25519;
// /* Payload to be raw signed by ed25519. */
// opaque payload<64>;
// }
//
// ===========================================================================
xdr.struct("SignerKeyEd25519SignedPayload", [
["ed25519", xdr.lookup("Uint256")],
["payload", xdr.varOpaque(64)],
]);
// === xdr source ============================================================
//
// union SignerKey switch (SignerKeyType type)
// {
// case SIGNER_KEY_TYPE_ED25519:
// uint256 ed25519;
// case SIGNER_KEY_TYPE_PRE_AUTH_TX:
// /* SHA-256 Hash of TransactionSignaturePayload structure */
// uint256 preAuthTx;
// case SIGNER_KEY_TYPE_HASH_X:
// /* Hash of random 256 bit preimage X */
// uint256 hashX;
// case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD:
// struct
// {
// /* Public key that must sign the payload. */
// uint256 ed25519;
// /* Payload to be raw signed by ed25519. */
// opaque payload<64>;
// } ed25519SignedPayload;
// };
//
// ===========================================================================
xdr.union("SignerKey", {
switchOn: xdr.lookup("SignerKeyType"),
switchName: "type",
switches: [
["signerKeyTypeEd25519", "ed25519"],
["signerKeyTypePreAuthTx", "preAuthTx"],
["signerKeyTypeHashX", "hashX"],
["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"],
],
arms: {
ed25519: xdr.lookup("Uint256"),
preAuthTx: xdr.lookup("Uint256"),
hashX: xdr.lookup("Uint256"),
ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload"),
},
});
// === xdr source ============================================================
//
// typedef opaque Signature<64>;
//
// ===========================================================================
xdr.typedef("Signature", xdr.varOpaque(64));
// === xdr source ============================================================
//
// typedef opaque SignatureHint[4];
//
// ===========================================================================
xdr.typedef("SignatureHint", xdr.opaque(4));
// === xdr source ============================================================
//
// typedef PublicKey NodeID;
//
// ===========================================================================
xdr.typedef("NodeId", xdr.lookup("PublicKey"));
// === xdr source ============================================================
//
// struct Curve25519Secret
// {
// opaque key[32];
// };
//
// ===========================================================================
xdr.struct("Curve25519Secret", [
["key", xdr.opaque(32)],
]);
// === xdr source ============================================================
//
// struct Curve25519Public
// {
// opaque key[32];
// };
//
// ===========================================================================
xdr.struct("Curve25519Public", [
["key", xdr.opaque(32)],
]);
// === xdr source ============================================================
//
// struct HmacSha256Key
// {
// opaque key[32];
// };
//
// ===========================================================================
xdr.struct("HmacSha256Key", [
["key", xdr.opaque(32)],
]);
// === xdr source ============================================================
//
// struct HmacSha256Mac
// {
// opaque mac[32];
// };
//
// ===========================================================================
xdr.struct("HmacSha256Mac", [
["mac", xdr.opaque(32)],
]);
});
export default types;
| {
"content_hash": "5c35265cc40a7f03fafc51d1f81d198c",
"timestamp": "",
"source": "github",
"line_count": 7086,
"max_line_length": 104,
"avg_line_length": 31.818233135760654,
"alnum_prop": 0.48931093212220134,
"repo_name": "stellar/js-stellar-base",
"id": "26852ebb876418d6b3193277cecd808cec74c867",
"size": "225464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/generated/curr_generated.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "923867"
},
{
"name": "Makefile",
"bytes": "2728"
},
{
"name": "RPC",
"bytes": "180948"
},
{
"name": "TypeScript",
"bytes": "15229"
}
],
"symlink_target": ""
} |
<?php
class Valdecode_CookieLaw_Model_Config_Behaviour
{
public function toOptionArray()
{
return array(
array('value' => 365, 'label' => 'Never show again'),
array('value' => 1, 'label' => 'Hide for the rest of the day'),
array('value' => 0, 'label' => 'Hide for the rest of the session')
);
}
}
| {
"content_hash": "64e662b24e6b275bed507cb41d637251",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 78,
"avg_line_length": 25.928571428571427,
"alnum_prop": 0.5399449035812672,
"repo_name": "valdecode/magento-cookielaw",
"id": "567c11efd53fce95975c613d86b30bbd1cf5dbda",
"size": "562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/code/community/Valdecode/CookieLaw/Model/Config/Behaviour.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4540"
},
{
"name": "HTML",
"bytes": "2897"
},
{
"name": "PHP",
"bytes": "4969"
}
],
"symlink_target": ""
} |
package org.ovirt.engine.ui.common.widget.uicommon.vm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.VmGuestAgentInterface;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.ui.common.CommonApplicationConstants;
import org.ovirt.engine.ui.common.CommonApplicationMessages;
import org.ovirt.engine.ui.common.CommonApplicationTemplates;
import org.ovirt.engine.ui.common.gin.AssetProvider;
import org.ovirt.engine.ui.common.widget.editor.EntityModelCellTable;
import org.ovirt.engine.ui.common.widget.table.column.AbstractNullableNumberColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractRxTxRateColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractSafeHtmlColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractSumUpColumn;
import org.ovirt.engine.ui.common.widget.table.column.AbstractTextColumn;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.VmInterfaceListModel;
import org.ovirt.engine.ui.uicompat.external.StringUtils;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.view.client.NoSelectionModel;
public class VmInterfaceInfoPanel extends TabLayoutPanel {
private final VmInterfaceListModel vmInterfaceListModel;
private EntityModelCellTable<ListModel> statisticsTable;
private EntityModelCellTable<ListModel> guestAgentDataTable;
private final static CommonApplicationTemplates templates = AssetProvider.getTemplates();
private final static CommonApplicationConstants constants = AssetProvider.getConstants();
private final static CommonApplicationMessages messages = AssetProvider.getMessages();
public VmInterfaceInfoPanel(VmInterfaceListModel vmInterfaceListModel) {
super(CommonApplicationTemplates.TAB_BAR_HEIGHT, Unit.PX);
this.vmInterfaceListModel = vmInterfaceListModel;
initPanel();
addStyle();
}
private void initPanel() {
// Initialize Tables
initStatitsticsTable();
initGuestAgentDataTable();
// Add Tabs
add(new ScrollPanel(statisticsTable), constants.statistics());
add(new ScrollPanel(guestAgentDataTable), constants.guestAgentData());
}
public void updatePanel(VmNetworkInterface nic) {
updateTabsData(nic);
}
private void addStyle() {
getElement().getStyle().setPosition(Position.STATIC);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void updateTabsData(VmNetworkInterface nic) {
statisticsTable.setRowData((List) Arrays.asList(nic));
guestAgentDataTable.setRowData(vmInterfaceListModel.getSelectionGuestAgentData() != null ? (List) vmInterfaceListModel.getSelectionGuestAgentData()
: new ArrayList<EntityModel>());
}
private void initStatitsticsTable() {
statisticsTable = new EntityModelCellTable<ListModel>(false, true);
statisticsTable.enableColumnResizing();
AbstractTextColumn<VmNetworkInterface> rxColumn = new AbstractRxTxRateColumn<VmNetworkInterface>() {
@Override
protected Double getRate(VmNetworkInterface object) {
return object.getStatistics().getReceiveRate();
}
@Override
protected Double getSpeed(VmNetworkInterface object) {
if (object.getSpeed() != null) {
return object.getSpeed().doubleValue();
} else {
return null;
}
}
};
statisticsTable.addColumn(rxColumn,
templates.sub(constants.rxRate(), constants.mbps()), "100px"); //$NON-NLS-1$
AbstractTextColumn<VmNetworkInterface> txColumn = new AbstractRxTxRateColumn<VmNetworkInterface>() {
@Override
protected Double getRate(VmNetworkInterface object) {
return object.getStatistics().getTransmitRate();
}
@Override
protected Double getSpeed(VmNetworkInterface object) {
if (object.getSpeed() != null) {
return object.getSpeed().doubleValue();
} else {
return null;
}
}
};
statisticsTable.addColumn(txColumn,
templates.sub(constants.txRate(), constants.mbps()), "100px"); //$NON-NLS-1$
AbstractNullableNumberColumn<VmNetworkInterface> totalRxColumn = new AbstractNullableNumberColumn<VmNetworkInterface>() {
@Override
protected Number getRawValue(VmNetworkInterface object) {
return object != null ? object.getStatistics().getReceivedBytes() : null;
}
};
statisticsTable.addColumn(totalRxColumn, templates.sub(constants.rxTotal(), constants.bytes()), "150px"); //$NON-NLS-1$
AbstractNullableNumberColumn<VmNetworkInterface> totalTxColumn = new AbstractNullableNumberColumn<VmNetworkInterface>() {
@Override
protected Number getRawValue(VmNetworkInterface object) {
return object != null ? object.getStatistics().getTransmittedBytes() : null;
}
};
statisticsTable.addColumn(totalTxColumn, templates.sub(constants.txTotal(), constants.bytes()), "150px"); //$NON-NLS-1$
AbstractTextColumn<VmNetworkInterface> dropsColumn = new AbstractSumUpColumn<VmNetworkInterface>() {
@Override
protected Double[] getRawValue(VmNetworkInterface object) {
Double receiveDropRate = object != null ? object.getStatistics().getReceiveDropRate() : null;
Double transmitDropRate = object != null ? object.getStatistics().getTransmitDropRate() : null;
return new Double[] { receiveDropRate, transmitDropRate };
}
};
statisticsTable.addColumn(dropsColumn,
templates.sub(constants.dropsInterface(), constants.pkts()), "100px"); //$NON-NLS-1$
statisticsTable.setRowData(new ArrayList<EntityModel>());
statisticsTable.setWidth("100%", true); //$NON-NLS-1$
statisticsTable.setSelectionModel(new NoSelectionModel());
}
private void initGuestAgentDataTable() {
guestAgentDataTable = new EntityModelCellTable<ListModel>(false, true);
guestAgentDataTable.enableColumnResizing();
AbstractTextColumn<VmGuestAgentInterface> nameColumn = new AbstractTextColumn<VmGuestAgentInterface>() {
@Override
public String getValue(VmGuestAgentInterface object) {
return object.getInterfaceName();
}
};
guestAgentDataTable.addColumn(nameColumn,
constants.nameVmGuestAgent(), "100px"); //$NON-NLS-1$
AbstractSafeHtmlColumn<VmGuestAgentInterface> ipv4Column =
new AbstractSafeHtmlColumn<VmGuestAgentInterface>() {
@Override
public SafeHtml getValue(VmGuestAgentInterface object) {
if (object.getIpv4Addresses() == null || object.getIpv4Addresses().size() == 0) {
return SafeHtmlUtils.fromTrustedString(""); //$NON-NLS-1$
}
if (object.getIpv4Addresses().size() == 1) {
return SafeHtmlUtils.fromTrustedString(object.getIpv4Addresses().get(0));
}
return SafeHtmlUtils.fromTrustedString(messages.addressesVmGuestAgent(object.getIpv4Addresses()
.size()));
}
@Override
public String getTooltip(VmGuestAgentInterface object) {
return StringUtils.join(object.getIpv4Addresses(), ", "); //$NON-NLS-1$
}
};
guestAgentDataTable.addColumn(ipv4Column,
constants.ipv4VmGuestAgent(), "100px"); //$NON-NLS-1$
AbstractSafeHtmlColumn<VmGuestAgentInterface> ipv6Column =
new AbstractSafeHtmlColumn<VmGuestAgentInterface>() {
@Override
public SafeHtml getValue(VmGuestAgentInterface object) {
if (object.getIpv6Addresses() == null || object.getIpv6Addresses().size() == 0) {
return SafeHtmlUtils.fromTrustedString(""); //$NON-NLS-1$
}
if (object.getIpv6Addresses().size() == 1) {
return SafeHtmlUtils.fromTrustedString(object.getIpv6Addresses().get(0));
}
return SafeHtmlUtils.fromTrustedString(messages.addressesVmGuestAgent(object.getIpv6Addresses()
.size()));
}
@Override
public String getTooltip(VmGuestAgentInterface object) {
return StringUtils.join(object.getIpv6Addresses(), ", "); //$NON-NLS-1$
}
};
guestAgentDataTable.addColumn(ipv6Column,
constants.ipv6VmGuestAgent(), "150px"); //$NON-NLS-1$
AbstractTextColumn<VmGuestAgentInterface> macColumn = new AbstractTextColumn<VmGuestAgentInterface>() {
@Override
public String getValue(VmGuestAgentInterface object) {
return object.getMacAddress();
}
};
guestAgentDataTable.addColumn(macColumn,
constants.macVmGuestAgent(), "150px"); //$NON-NLS-1$
guestAgentDataTable.setRowData(new ArrayList<EntityModel>());
guestAgentDataTable.setWidth("100%", true); //$NON-NLS-1$
guestAgentDataTable.setSelectionModel(new NoSelectionModel());
}
}
| {
"content_hash": "ce3f25c7a5a58e81ae23acd105db32c3",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 155,
"avg_line_length": 43.693617021276594,
"alnum_prop": 0.6472536034281262,
"repo_name": "walteryang47/ovirt-engine",
"id": "e36239d238fceb7c96bd5ccf375fbdd30f2bfa89",
"size": "10268",
"binary": false,
"copies": "4",
"ref": "refs/heads/eayunos-4.2",
"path": "frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/uicommon/vm/VmInterfaceInfoPanel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "68312"
},
{
"name": "HTML",
"bytes": "16218"
},
{
"name": "Java",
"bytes": "35067647"
},
{
"name": "JavaScript",
"bytes": "69948"
},
{
"name": "Makefile",
"bytes": "24723"
},
{
"name": "PLSQL",
"bytes": "533"
},
{
"name": "PLpgSQL",
"bytes": "796728"
},
{
"name": "Python",
"bytes": "970860"
},
{
"name": "Roff",
"bytes": "10764"
},
{
"name": "Shell",
"bytes": "163853"
},
{
"name": "XSLT",
"bytes": "54683"
}
],
"symlink_target": ""
} |
// Package eventtoken includes utility methods for event token
// handling.
package eventtoken
import (
"vitess.io/vitess/go/mysql"
querypb "vitess.io/vitess/go/vt/proto/query"
)
// Fresher compares two event tokens. It returns a negative number if
// ev1<ev2, zero if they're equal, and a positive number if
// ev1>ev2. In case of doubt (we don't have enough information to know
// for sure), it returns a negative number.
func Fresher(ev1, ev2 *querypb.EventToken) int {
if ev1 == nil || ev2 == nil {
// Either one is nil, we don't know.
return -1
}
if ev1.Timestamp != ev2.Timestamp {
// The timestamp is enough to set them apart.
return int(ev1.Timestamp - ev2.Timestamp)
}
if ev1.Shard != "" && ev1.Shard == ev2.Shard {
// They come from the same shard. See if we have positions.
if ev1.Position == "" || ev2.Position == "" {
return -1
}
// We can parse them.
pos1, err := mysql.DecodePosition(ev1.Position)
if err != nil {
return -1
}
pos2, err := mysql.DecodePosition(ev2.Position)
if err != nil {
return -1
}
// Then compare.
if pos1.Equal(pos2) {
return 0
}
if pos1.AtLeast(pos2) {
return 1
}
return -1
}
// We do not know.
return -1
}
| {
"content_hash": "37d0e06edb228c0e77d7442478d410d2",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 70,
"avg_line_length": 22.181818181818183,
"alnum_prop": 0.6524590163934426,
"repo_name": "mahak/vitess",
"id": "2fe908527d2b89450554a1272c80b77209ad2818",
"size": "1785",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "go/vt/binlog/eventtoken/compare.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "198"
},
{
"name": "CSS",
"bytes": "18852"
},
{
"name": "Dockerfile",
"bytes": "28594"
},
{
"name": "Go",
"bytes": "23060389"
},
{
"name": "HCL",
"bytes": "959"
},
{
"name": "HTML",
"bytes": "25753"
},
{
"name": "Java",
"bytes": "990163"
},
{
"name": "JavaScript",
"bytes": "33028"
},
{
"name": "Jsonnet",
"bytes": "121075"
},
{
"name": "Makefile",
"bytes": "23322"
},
{
"name": "Perl",
"bytes": "3161"
},
{
"name": "Python",
"bytes": "1955"
},
{
"name": "SCSS",
"bytes": "41351"
},
{
"name": "Shell",
"bytes": "184185"
},
{
"name": "Smarty",
"bytes": "30493"
},
{
"name": "TypeScript",
"bytes": "711819"
},
{
"name": "Yacc",
"bytes": "162805"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="PreferencePanel">
<item name="layout_marginTop">@dimen/preference_screen_top_margin</item>
<item name="layout_marginBottom">@dimen/preference_screen_bottom_margin</item>
<item name="layout_marginStart">@dimen/preference_screen_side_margin</item>
<item name="layout_marginEnd">@dimen/preference_screen_side_margin</item>
</style>
</resources>
| {
"content_hash": "f62fb025b606adbc1e285342e79f6807",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 86,
"avg_line_length": 49.55555555555556,
"alnum_prop": 0.6928251121076233,
"repo_name": "Liberations/Flyme5_devices_base_cm",
"id": "b1a1686e5de2cfa9d196b4098b4e4baddf5c7220",
"size": "446",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "framework-res/res/values-sw720dp-v13/styles.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "96769"
},
{
"name": "Makefile",
"bytes": "11209"
},
{
"name": "Python",
"bytes": "1195"
},
{
"name": "Shell",
"bytes": "55270"
},
{
"name": "Smali",
"bytes": "160321888"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2013 Allogy Interactive.
~
~ Licensed under the Apache License, Version 2.0 (the "License"); you may not
~ use this file except in compliance with the License. You may obtain a copy of
~ the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
~ License for the specific language governing permissions and limitations under
~ the License.
-->
<resources>
<color name="background">#ffffffff</color>
<color name="ab_background_start">#ffba0014</color>
<color name="ab_background_end">#ffde0019</color>
<color name="ab_text">#ffffffff</color>
<color name="ab_text_alt">#ff000000</color>
<color name="ab_separator">#40ffffff</color>
<color name="header_light">#ffd2a582</color>
<color name="header_dark">#ff3c230a</color>
<color name="text">#ff3c230a</color>
<color name="red">#ffff0000</color>
<color name="blue">#ff00ff00</color>
<color name="green">#ff0000ff</color>
<color name="gray">#ff808080</color>
<color name="black">#ff000000</color>
<color name="white">#ffffffff</color>
<color name="separator">#40ffffff</color>
<!-- Content Items -->
<color name="content_header_background">#ff4b4b4b</color>
<color name="content_item_light">#ffc8c8c8</color>
<color name="content_item_dark">#ff4b4b4b</color>
<color name="content_item_highlight">#fffeaf19</color>
<!-- List Items -->
<color name="lesson_start">#ffc8c8c8</color>
<color name="lesson_end">#ffe6e6e6</color>
</resources>
| {
"content_hash": "779de0f51714eaddc4028f749a135efa",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 81,
"avg_line_length": 38.46808510638298,
"alnum_prop": 0.672566371681416,
"repo_name": "Allogy/allogy-legacy-android-app",
"id": "517073b7fd8bb172e25689f633aa56bfce51762a",
"size": "1808",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Allogy/res/values/colors.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1398436"
}
],
"symlink_target": ""
} |
define(['durandal/binder', 'durandal/system', 'knockout'], function (sut, system, ko) {
describe('durandal/binder', function(){
var settings, view;
function sharedBindingBehaviour(createSettings, sutAction) {
var insufficientInfoMessage = 'Insufficient Information to Bind',
unexpectedViewMessage = 'Unexpected View Type',
viewName = 'view name';
beforeEach(function() {
settings = createSettings();
view = {
getAttribute: function () { return viewName; }
};
sut.throwOnErrors = false;
if (!ko.applyBindings.isSpy) {
spyOn(ko, 'applyBindings');
}
spyOn(system, 'log');
});
it('logs and returns with null view', function () {
view = null;
sutAction();
expect(system.log).toHaveBeenCalled();
expect(ko.applyBindings).not.toHaveBeenCalledWith(settings.bindingTarget, view);
});
it('logs and returns with null obj', function () {
settings.bindingTarget = null;
sutAction();
expect(system.log).toHaveBeenCalled();
expect(ko.applyBindings).not.toHaveBeenCalledWith(settings.bindingTarget, view);
});
it('logs and returns with no getAttribute function on view', function () {
view.getAttribute = null;
sutAction();
expect(system.log).toHaveBeenCalled();
expect(ko.applyBindings).not.toHaveBeenCalledWith(settings.bindingTarget, view);
});
it('applies bindings with before and after hooks', function () {
var bindStatus = 0;
spyOn(sut, 'binding').and.callFake(function (dataArg, viewArg) {
expect(dataArg).toBe(settings.data);
expect(viewArg).toBe(view);
expect(bindStatus).toBe(0);
bindStatus = 1;
});
ko.applyBindings.and.callFake(function () {
expect(bindStatus).toBe(1);
bindStatus = 2;
});
spyOn(sut, 'bindingComplete').and.callFake(function (dataArg, viewArg) {
expect(dataArg).toBe(settings.data);
expect(viewArg).toBe(view);
expect(bindStatus).toBe(2);
});
sutAction();
expect(system.log).toHaveBeenCalled();
expect(ko.applyBindings).toHaveBeenCalledWith(settings.bindingTarget, view);
});
it('logs binding error', function () {
ko.applyBindings.and.callFake(function () {
throw new Error('FakeError');
});
sutAction();
expect(system.log).toHaveBeenCalled();
});
describe('with throw errors set', function () {
beforeEach(function() {
sut.throwOnErrors = true;
});
it('throws and returns with null view', function () {
view = null;
expect(function () { sutAction(); }).toThrowError(insufficientInfoMessage);
expect(ko.applyBindings).not.toHaveBeenCalledWith(settings.bindingTarget, view);
});
it('throws and returns with null obj', function () {
settings.bindingTarget = null;
expect(function () { sutAction(); }).toThrowError(insufficientInfoMessage);
expect(ko.applyBindings).not.toHaveBeenCalledWith(settings.bindingTarget, view);
});
it('throws and returns with no getAttribute function on view', function () {
view.getAttribute = null;
expect(function () { sutAction(); }).toThrowError(unexpectedViewMessage);
expect(ko.applyBindings).not.toHaveBeenCalledWith(settings.bindingTarget, view);
});
it('throws binding error', function () {
ko.applyBindings.and.callFake(function () {
throw new Error('FakeError');
});
expect(function () { sutAction(); }).toThrowError(/.*/);
});
});
}
describe('bind', function () {
function createSettings(){
var target = {};
return{
obj:target,
bindingTarget:target,
data:target
};
};
sharedBindingBehaviour(createSettings, function () {
sut.bind(settings.bindingTarget, view);
});
});
describe('bindContext', function () {
describe('child context used', function () {
function createSettings(){
var bindingObject = {};
var bindingContext = {
$data: bindingObject,
createChildContext: function () {
return bindingContext;
}
};
return{
obj:bindingObject,
bindingTarget:bindingContext,
data:bindingObject
};
};
sharedBindingBehaviour(createSettings, function () {
sut.bindContext(settings.bindingTarget, view, settings.data);
});
});
describe('child context not used', function () {
function createSettings(){
var bindingObject = {};
var bindingContext = {
$data: bindingObject,
createChildContext: function () {
return bindingObject;
}
};
return{
obj:bindingObject,
bindingTarget:bindingContext,
data:bindingObject
};
};
sharedBindingBehaviour(createSettings, function () {
sut.bindContext(settings.bindingTarget, view, null);
});
});
});
});
}); | {
"content_hash": "ea7b17586aac4e7e542a5521fc84619f",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 100,
"avg_line_length": 36.278688524590166,
"alnum_prop": 0.46904654315408945,
"repo_name": "davismj/Durandal",
"id": "663b42183c0850da2979be44c8fe31e8529af912",
"size": "6641",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "test/specs/binder.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "214"
},
{
"name": "Batchfile",
"bytes": "1103"
},
{
"name": "C#",
"bytes": "12898"
},
{
"name": "CSS",
"bytes": "47284"
},
{
"name": "CoffeeScript",
"bytes": "1727"
},
{
"name": "HTML",
"bytes": "97494"
},
{
"name": "JavaScript",
"bytes": "7831437"
},
{
"name": "Makefile",
"bytes": "1092"
},
{
"name": "Pascal",
"bytes": "2925"
},
{
"name": "PowerShell",
"bytes": "6176"
},
{
"name": "Puppet",
"bytes": "362"
},
{
"name": "TypeScript",
"bytes": "3464"
}
],
"symlink_target": ""
} |
/// <reference path="../App.js" />
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
$('#send').click(sendFeedback);
});
};
function sendFeedback() {
// Disable the controls while sending data
$('.disable-while-sending').prop('disabled', true);
var dataToPassToService = {
Feedback: $('#feedback').val(),
Rating: $('#rating').val()
};
$.ajax({
url: '../../api/SendFeedback',
type: 'POST',
data: JSON.stringify(dataToPassToService),
contentType: 'application/json;charset=utf-8'
}).done(function (data) {
app.showNotification(data.Status, data.Message);
}).fail(function (status) {
app.showNotification('Error', 'Could not communicate with the server.');
}).always(function () {
$('.disable-while-sending').prop('disabled', false);
});
}
})();
// *********************************************************
//
// Office-Add-in-JavaScript-WebApiService, https://github.com/OfficeDev/Office-Add-in-JavaScript-WebApiService
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ********************************************************* | {
"content_hash": "73582ce539b61c309070fb6a9c710c90",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 110,
"avg_line_length": 36.22857142857143,
"alnum_prop": 0.6214511041009464,
"repo_name": "OfficeDev/Office-Add-in-JavaScript-WebApiService",
"id": "5b492d343c08256719f4c8336cc47381273f74f4",
"size": "2668",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "WebApi SampleWeb/App/Home/Home.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "110"
},
{
"name": "C#",
"bytes": "8163"
},
{
"name": "CSS",
"bytes": "7346"
},
{
"name": "HTML",
"bytes": "3828"
},
{
"name": "JavaScript",
"bytes": "5122266"
}
],
"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.manipulators.add_value_hpp" title="Header <boost/log/utility/manipulators/add_value.hpp>">
<link rel="prev" href="add_value_manip.html" title="Class template add_value_manip">
<link rel="next" href="add_value.html" title="Function add_value">
</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="add_value_manip.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.manipulators.add_value_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="add_value.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.log.operator_idp55965488"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template operator<<</span></h2>
<p>boost::log::operator<< — The operator attaches an attribute value to the log record. </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.manipulators.add_value_hpp" title="Header <boost/log/utility/manipulators/add_value.hpp>">boost/log/utility/manipulators/add_value.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> CharT<span class="special">,</span> <span class="keyword">typename</span> RefT<span class="special">></span>
<span class="identifier">basic_record_ostream</span><span class="special"><</span> <span class="identifier">CharT</span> <span class="special">></span> <span class="special">&</span>
<span class="keyword">operator</span><span class="special"><<</span><span class="special">(</span><span class="identifier">basic_record_ostream</span><span class="special"><</span> <span class="identifier">CharT</span> <span class="special">></span> <span class="special">&</span> strm<span class="special">,</span>
<a class="link" href="add_value_manip.html" title="Class template add_value_manip">add_value_manip</a><span class="special"><</span> <span class="identifier">RefT</span> <span class="special">></span> <span class="keyword">const</span> <span class="special">&</span> manip<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="add_value_manip.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.manipulators.add_value_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="add_value.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "5a883584f38f5997c540d81b2949811e",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 490,
"avg_line_length": 94.36170212765957,
"alnum_prop": 0.6635851183765502,
"repo_name": "mitreaadrian/Soccersim",
"id": "e85529012283296bfd56355f8503d491699ccd86",
"size": "4435",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "boost/boost_1_59_0/libs/log/doc/html/boost/log/operator_idp55965488.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "207316"
},
{
"name": "Batchfile",
"bytes": "9258"
},
{
"name": "C",
"bytes": "823756"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "171147574"
},
{
"name": "CMake",
"bytes": "16644"
},
{
"name": "CSS",
"bytes": "253358"
},
{
"name": "Cuda",
"bytes": "26521"
},
{
"name": "FORTRAN",
"bytes": "1856"
},
{
"name": "HTML",
"bytes": "152513473"
},
{
"name": "JavaScript",
"bytes": "170422"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "Makefile",
"bytes": "188826"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "2764"
},
{
"name": "Objective-C++",
"bytes": "421"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "36132"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Python",
"bytes": "454175"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Shell",
"bytes": "67448"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "XSLT",
"bytes": "548899"
}
],
"symlink_target": ""
} |
<div>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<a class="brand" data-bind="attr: { href: router.visibleRoutes()[0].hash }">
<i class="icon-home"></i>
<span>Durandal</span>
</a>
<ul class="nav" data-bind="foreach: router.visibleRoutes">
<li data-bind="css: { active: isActive }">
<a data-bind="attr: { href: hash }, html: name"></a>
</li>
</ul>
<div class="loader pull-right" data-bind="css: { active: router.isNavigating }">
<i class="icon-spinner icon-2x icon-spin"></i>
</div>
</div>
</div>
<div class="container-fluid page-host" data-bind="compose: {
model: router.activeItem, // wiring the router
afterCompose: router.afterCompose, // wiring the router
transition: 'fade', // use the 'entrance' transition when switching views
cacheViews: true // telling composition to keep views in the dom, and reuse them (only a good idea with singleton view models)
}"></div>
</div>
| {
"content_hash": "608280e03d9f73a498c1086798693078",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 139,
"avg_line_length": 39.52,
"alnum_prop": 0.631578947368421,
"repo_name": "jonjaques/glados",
"id": "00a8efcab553827a91f8da8c9d7d4f98ddb1f8c9",
"size": "990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/samples/shell.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1019996"
}
],
"symlink_target": ""
} |
package org.everit.jetty.server.ecm.internal;
/**
* Constants of SslConnectionFactory attribute priority.
*/
public final class SslConnectionFactoryAttributePriority {
public static final int P01_SERVICE_DESCRIPTION = 1;
public static final int P02_KEYSTORE = 2;
public static final int P03_KEYSTORE_PASSWORD = 3;
public static final int P04_CERT_ALIAS = 4;
public static final int P05_KEY_MANAGER_PASSWORD = 5;
public static final int P06_INCLUDE_PROTOCOLS = 6;
private SslConnectionFactoryAttributePriority() {
}
}
| {
"content_hash": "dadbaf02951e6658a351e804e94c4040",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 58,
"avg_line_length": 23.652173913043477,
"alnum_prop": 0.7573529411764706,
"repo_name": "everit-org/jetty-server-component",
"id": "b4394ccc9bfb5e8a7412ed4d7819497787056d23",
"size": "1170",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "component/src/main/java/org/everit/jetty/server/ecm/internal/SslConnectionFactoryAttributePriority.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "186444"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LojaNinja.Dominio.Usuarios
{
public interface IUsuarioRepositorio
{
Usuario BuscarUsuarioPorAutenticacao(string email, string senha);
void CadastrarUsuario(Usuario usuario);
}
}
| {
"content_hash": "bd3ed16c7b83a2e51fbec3ce1d125560",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 73,
"avg_line_length": 23.857142857142858,
"alnum_prop": 0.7574850299401198,
"repo_name": "SadPandaBear/crescer-2016-1",
"id": "bbbdaa9c819e06bff7d89735dae2aaa27c2477a6",
"size": "336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modulo-05-dotnet/Aula 5/LojaNinja/LojaNinja/LojaNinja.Dominio/Usuarios/IUsuarioRepositorio.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "606"
},
{
"name": "C#",
"bytes": "380974"
},
{
"name": "CSS",
"bytes": "217327"
},
{
"name": "HTML",
"bytes": "209642"
},
{
"name": "Java",
"bytes": "232217"
},
{
"name": "JavaScript",
"bytes": "670092"
},
{
"name": "PLSQL",
"bytes": "9793"
},
{
"name": "PLpgSQL",
"bytes": "1547"
},
{
"name": "PowerShell",
"bytes": "25930"
}
],
"symlink_target": ""
} |
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package ebay.apis.eblbasecomponents;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
/**
*
* This type defines the <b>QuantityRestrictionPerBuyer</b> container, which is
* used by the seller to restrict the quantity of items that may be purchased by one buyer
* during the duration of a fixed-price listing (single or multi-variation).
*
*/
public class QuantityRestrictionPerBuyerInfoType implements Serializable {
private static final long serialVersionUID = -1L;
@Element(name = "MaximumQuantity")
private Integer maximumQuantity;
/**
* public getter
*
*
* This integer value indicates the maximum quantity of items that a single buyer may
* purchase during the duration of a fixed-price listing (single or multi-variation).
* The buyer is blocked from the purchase if that buyer is attempting to purchase a
* quantity of items that will exceed this value. Previous purchases made by the buyer
* are taken into account. For example, if <b>MaximumQuantity</b> is set to
* '5' for an item listing, and <em>Buyer1</em> purchases a quantity of
* three, <em>Buyer1</em> is only allowed to purchase an additional
* quantity of two in subsequent orders on the same item listing.
* <br/><br/>
* This field is required if the <b>QuantityRestrictionPerBuyer</b>
* container is used.
*
*
* @returns java.lang.Integer
*/
public Integer getMaximumQuantity() {
return this.maximumQuantity;
}
/**
* public setter
*
*
* This integer value indicates the maximum quantity of items that a single buyer may
* purchase during the duration of a fixed-price listing (single or multi-variation).
* The buyer is blocked from the purchase if that buyer is attempting to purchase a
* quantity of items that will exceed this value. Previous purchases made by the buyer
* are taken into account. For example, if <b>MaximumQuantity</b> is set to
* '5' for an item listing, and <em>Buyer1</em> purchases a quantity of
* three, <em>Buyer1</em> is only allowed to purchase an additional
* quantity of two in subsequent orders on the same item listing.
* <br/><br/>
* This field is required if the <b>QuantityRestrictionPerBuyer</b>
* container is used.
*
*
* @param java.lang.Integer
*/
public void setMaximumQuantity(Integer maximumQuantity) {
this.maximumQuantity = maximumQuantity;
}
} | {
"content_hash": "3f1b853b00db38cb03a18c796ff709a6",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 90,
"avg_line_length": 37.10144927536232,
"alnum_prop": 0.70078125,
"repo_name": "kzganesan/nano-rest",
"id": "09e3b809c7bda0a7f2e84f693d0edd0dfd39ada1",
"size": "2560",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sample/HelloEBayTrading/src/ebay/apis/eblbasecomponents/QuantityRestrictionPerBuyerInfoType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "13300613"
}
],
"symlink_target": ""
} |
var Component = require("montage/ui/component").Component;
var sharedTmdbService = require("core/tmdb-service").shared;
exports.Details = Component.specialize({
constructor: {
value: function Details() {
this.super();
}
},
_movie: {
value: null
},
movie: {
set: function (val) {
var self = this;
this._movie = val;
if(val != null) {
sharedTmdbService.loadMovie(val)
.then(function (movie) {
self.dispatchBeforeOwnPropertyChange("movie", self._movie);
self._movie = movie;
self.dispatchOwnPropertyChange("movie", self._movie);
return movie;
})
.then(function (movie) {
return sharedTmdbService.loadReleases(movie);
})
.then(function (releases) {
var rating = releases.countries[0].certification;
if (rating.length === 0) {
rating = "none";
}
self._movie.mpaaRating = rating;
})
.done();
}
this.needsDraw = true;
},
get: function () {
return this._movie;
}
},
draw: {
value: function () {
if (this.movie) {
//jshint -W106
var popularity = this.movie.popularity;
//jshint +W106
if (popularity < 25) {
this.popularityIcon.style.backgroundPosition = '0px 0px';
} else if (popularity < 50) {
this.popularityIcon.style.backgroundPosition = '-12px 0px';
} else if (popularity < 75) {
this.popularityIcon.style.backgroundPosition = '-24px 0px';
} else {
this.popularityIcon.style.backgroundPosition = '-36px 0px';
}
if (this._isDetailsExpanded) {
this._element.classList.add("expanded");
} else {
this._element.classList.remove("expanded");
}
}
}
},
handleRentButtonAction: {
value: function () {
window.open( this.movie.links.alternate );
}
},
handleTrailerButtonAction: {
value: function () {
this.dispatchEventNamed("openTrailer", true, true, {title: this.movie.title});
}
},
_isDetailsExpanded: {
value: false
},
handleExpandButtonAction: {
value: function () {
this._isDetailsExpanded = !this._isDetailsExpanded;
this.needsDraw = true;
}
}
});
| {
"content_hash": "b2ebf188890068fc8858eb23d43f91c6",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 90,
"avg_line_length": 29.757894736842104,
"alnum_prop": 0.4651574106827025,
"repo_name": "DigitalSismo/popcorn",
"id": "4dbb1f8cdf4e8230359c2ee6b07de9c7559bda7a",
"size": "2828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ui/details.reel/details.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "25415"
},
{
"name": "JavaScript",
"bytes": "19609"
}
],
"symlink_target": ""
} |
require_relative './shuffleLinesImpl.rb'
require 'open3'
require 'tempfile'
require 'test/unit'
SIZE_OF_RANDOM_TESTING_SMALL = 500
SIZE_OF_RANDOM_TESTING_LARGE = 5000
SIZE_OF_RANDOM_TESTING_FILE = 10
# 実際にbotで使うファイル
TEST_INPUT_FILENAME = "cppFriendsBot.txt"
# 説明用の入力ファイル
TEST_SAMPLE_FILENAME = "shuffleLinesSample.txt"
# 実行ファイル名
TEST_COMMAND_NAME = "ruby -Ku shuffleLines.rb"
# 無視したい警告メッセージ
TEXT_REDUNDANT_PATTERN = "ruby: warning: shebang line ending with \\r may cause problems"
def remove_shebang_message(message)
message.gsub(TEXT_REDUNDANT_PATTERN, '').lstrip
end
class MockInputStream
def initialize(lines)
@lines = lines.dup
end
def gets
@lines.shift
end
end
class MockOutputStream
attr_reader :str
def initialize
@str = ""
end
def puts(line)
@str += line + "\n"
end
def write(line)
@str += line
end
end
class TestMyProgramOption < Test::Unit::TestCase
data(
'short separated' => ["-i", "name"],
'short connected' => ["-iname"],
'long separated' => ["--input", "name"],
'long connected' => ["--input=name"],
'space' => ["-i name"])
def test_inFilename(data)
opt = MyProgramOption.new(data)
assert_equal("name", opt.inFilename)
assert_nil(opt.outFilename)
assert_nil(opt.phrase)
assert_false(opt.checkTweets)
end
data(
'short separated' => ["-o", "name"],
'short connected' => ["-oname"],
'long separated' => ["--output", "name"],
'long connected' => ["--output=name"],
'space' => ["-o name"])
def test_outFilename(data)
opt = MyProgramOption.new(data)
assert_nil(opt.inFilename)
assert_equal("name", opt.outFilename)
assert_nil(opt.phrase)
assert_false(opt.checkTweets)
end
data(
'short separated' => ["-p", "name"],
'short connected' => ["-pname"],
'long separated' => ["--phrase", "name"],
'long connected' => ["--phrase=name"],
'space' => ["-p name"])
def test_phrase(data)
opt = MyProgramOption.new(data)
assert_nil(opt.inFilename)
assert_nil(opt.outFilename)
assert_equal("name", opt.phrase)
assert_false(opt.checkTweets)
end
data(
'short' => [["-p", "It rains"], "It rains"],
'short space' => [["-p", " It rains "], "It rains"],
'long' => [["--phrase", "わ-い たーのしー"], "わ-い たーのしー"],
'long space' => [["--phrase", " わ-い たーのしー "], "わ-い たーのしー"])
def test_sentence(data)
arg, expected = data
opt = MyProgramOption.new(arg)
assert_nil(opt.inFilename)
assert_nil(opt.outFilename)
assert_equal(expected, opt.phrase)
assert_false(opt.checkTweets)
end
data(
'set' => ["-c", true],
'set long' => ["--check", true],
'unset long' => ["--no-check", false])
def test_checkTweets(data)
arg, expected = data
opt = MyProgramOption.new([arg])
assert_nil(opt.inFilename)
assert_nil(opt.outFilename)
assert_nil(opt.phrase)
assert_equal(expected, opt.checkTweets)
end
def test_empty
opt = MyProgramOption.new([])
assert_nil(opt.inFilename)
assert_nil(opt.outFilename)
assert_nil(opt.phrase)
assert_false(opt.checkTweets)
assert_not_nil(opt.checkTweets)
end
def test_mixed
inFilename = "src"
outFilename = "dst"
inPhrase = " わ-い たーのしー "
outPhrase = "わ-い たーのしー"
[["-i", inFilename, "--output=#{outFilename}", "--phrase", inPhrase],
["-i#{inFilename}", "--output", outFilename, "-p", inPhrase]].each do |arg|
opt = MyProgramOption.new(arg)
assert_equal(inFilename, opt.inFilename)
assert_equal(outFilename, opt.outFilename)
assert_equal(outPhrase, opt.phrase)
end
end
def test_missingParameter
inFilename = "src"
outFilename = "dst"
inPhrase = " わ-い たーのしー "
outPhrase = "わ-い たーのしー"
[[["-i", inFilename, "--output=#{outFilename}", "--phrase"], inFilename, outFilename, nil],
[["-i", inFilename, "--output=#{outFilename}", "-p"], inFilename, outFilename, nil],
[["-i", inFilename, "--output", "--phrase"], inFilename, nil, nil],
[["-i", inFilename, "-o", "--phrase"], inFilename, nil, nil],
[["--input", "--output", "--phrase"], nil, nil, nil],
[["-i", "--output", "-p"], nil, nil, nil],
[["-i", inFilename, "--output=#{outFilename}", "--phrase="], inFilename, outFilename, ""],
[["-i", inFilename, "--output=", "--phrase="], inFilename, "", ""],
[["--input=", "--output=", "--phrase="], "", "", ""]].each do
|arg, expectedInFilename, expectedOutFilename, expectedPhrase|
opt = MyProgramOption.new(arg)
assert_equal(expectedInFilename, opt.inFilename)
assert_equal(expectedOutFilename, opt.outFilename)
assert_equal(expectedPhrase, opt.phrase)
end
end
def test_patterns
assert_equal(LINE_PATTERN_SET, MyProgramOption.new([]).patterns)
end
end
class TestNullLineChecker < Test::Unit::TestCase
def test_all
assert_false(NullLineChecker.new(nil).check(""))
end
end
class TestTweetChecker < Test::Unit::TestCase
data(
'empty' => "",
'plain' => "line",
'kana' => "@ホスト名",
'user 1' => "user@hostname",
'user 2' => "ユーザ@ホスト名",
'hashmark' => "#",
'not a hashtag' => "ユーザ#ホスト名")
def test_checkNothingFound(data)
line = data
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
assert_false(checker.checkMention(line))
assert_false(checker.checkHashtag(line))
assert_false(checker.check(line))
assert_true(outStream.str.empty?)
end
data(
'simple' => "@a",
'space 1' => " @a ",
'space 2' => "@a ",
'spaces' => " @a ",
'pre' => "本文 @a ",
'post' => " @a 本文",
'full' => "前文 @a 本文")
def test_checkMention(data)
line = data
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
assert_true(checker.checkMention(line))
assert_equal("Mention(s) found in #{line}\n", outStream.str)
assert_true(checker.check(line))
end
def test_checkMultipleMention
line = "前文 @a 本文 @b まとめ"
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
assert_true(checker.checkMention(line))
assert_equal("Mention(s) found in #{line}\n", outStream.str)
assert_true(checker.check(line))
end
def test_checkKnownHashtags
[HASHTAG_SET, "ifdef", "ifndef"].flatten.each do |tag|
line = '#' + tag
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
assert_false(checker.checkHashtag(line))
assert_false(checker.check(line))
assert_true(outStream.str.empty?)
end
end
def test_checkUnknownHashtags
["tag", "タグ"].each do |tag|
["", " "].each do |prefix|
["", " "].each do |postfix|
line = prefix + '#' + tag + postfix
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
assert_true(checker.checkHashtag(line))
assert_equal("Unknown tag(s) " + '#' + "#{tag} found\n", outStream.str)
assert_true(checker.check(line))
end
end
end
end
def test_checkMultipleTags
line = '#tagA #tagB #tagC'
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
assert_true(checker.checkHashtag(line))
assert_equal('Unknown tag(s) #tagA, #tagB, #tagC found' + "\n", outStream.str)
assert_true(checker.check(line))
end
data(
'simple' => ["@a #tag", true,
"Mention(s) found in @a #tag\nUnknown tag(s) #tag found\n"],
'spaces' => [" @a #tag ", true,
"Mention(s) found in @a #tag \nUnknown tag(s) #tag found\n"],
'multi' => ["@a #tagA @b #tagB", true,
"Mention(s) found in @a #tagA @b #tagB\nUnknown tag(s) #tagA, #tagB found\n"],
'body' => ["前文 user@hostname A#B @a #tag 本文", true,
"Mention(s) found in 前文 user@hostname A#B @a #tag 本文\nUnknown tag(s) #tag found\n"])
def test_checkSentence(data)
line, expected, expectedStr = data
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
assert_equal(expected, checker.check(line))
assert_equal(expectedStr, outStream.str)
end
end
class TestArrayInterleaver < Test::Unit::TestCase
# ex以外の要素が隣接するときtrue
def checkIfSuccessive(sequence, ex)
return false if sequence.size < 2
e = sequence[0]
1.upto(sequence.size - 1) do |i|
nextElement = sequence[i]
return true if (e == nextElement) && (e != ex)
e = nextElement
end
return false
end
def test_empty
0.upto(2) do |size|
arg = Array.new(size, 0)
assert_true(ArrayInterleaver.new.makeSequence(arg).empty?)
end
end
def test_oneMember
1.upto(3) do |size|
actual = ArrayInterleaver.new.makeSequence([size])
assert_equal(size, actual.size)
end
end
def test_uniformMember
1.upto(3) do |arraySize|
1.upto(7) do |elementSize|
arg = Array.new(arraySize, elementSize)
actual = ArrayInterleaver.new.makeSequence(arg)
assert_equal(arraySize * elementSize, actual.size)
assert_false(checkIfSuccessive(actual, nil)) if arraySize > 1
0.upto(arraySize - 1) do |i|
assert_equal(elementSize, actual.count(i))
end
end
end
end
data(
'containing zero' => [2,0,1],
'ascending' => [1,2,3],
'descending' => [3,2,1],
'not ordered' => [2,3,1],
'duplicate 1' => [1,3,3],
'duplicate 2' => [1,1,3],
'long 1' => [1,2,4,8],
'long 2' => [4,3,2,1])
def test_patterns(data)
arg = data
totalElements = arg.reduce(0, &:+)
maxElement = arg.max
indexArray = []
arg.each_with_index do |size, i|
indexArray << Struct.new(:size, :index).new(size, i)
end
SIZE_OF_RANDOM_TESTING_LARGE.times do
actual = ArrayInterleaver.new.makeSequence(arg)
assert_equal(totalElements, actual.size)
# 最大要素数になる配列が複数あるときは、どの配列の要素も隣合わない
index = (arg.count(maxElement) > 1) ? nil : indexArray.sort_by(&:size)[-1].index
assert_false(checkIfSuccessive(actual, index))
arg.each_with_index do |size, i|
assert_equal(size, actual.count(i))
end
end
end
def test_isRandom
arg = [2,3,4,5,6,7,8,9,10,11,12,13,14,15]
# 偶然前回の結果と一致する確率がないとは言えない
previous = []
SIZE_OF_RANDOM_TESTING_SMALL.times do
actual = ArrayInterleaver.new.makeSequence(arg)
assert_not_equal(previous, actual)
previous = actual
end
end
end
class TestLineSet < Test::Unit::TestCase
def test_initialize
1.upto(3) do |i|
arg = (1..i).to_a
lineSet = LineSet.new(arg)
assert_equal(arg.size + 1, lineSet.instance_variable_get(:@lineArrays).size)
assert_true(lineSet.instance_variable_get(:@lineArrays).all?(&:empty?))
assert_equal(arg, lineSet.instance_variable_get(:@patterns))
assert_true(lineSet.instance_variable_get(:@string).empty?)
end
end
data(
'first 1' => ["abc 123", 0],
'first 2' => ["123 abc", 0],
'second 1' => ["def 123", 1],
'second 2' => ["123 def", 1],
'other 1' => ["ghi", 2],
'other 2' => ["abb", 2],
'other 3' => ["df", 2])
def test_addLine(data)
line, expected = data
patterns = [/abc/, /d.f/]
lineSet = LineSet.new(patterns)
lineSet.addLine(line)
lineSet.instance_variable_get(:@lineArrays).each_with_index do |array, i|
assert_equal(i != expected, array.empty?)
end
lineSet.addLine(line)
assert_equal(2, lineSet.instance_variable_get(:@lineArrays)[expected].size)
end
def test_shuffleShort
patterns = [/\A\d/, /\A\d/]
actual = (1..SIZE_OF_RANDOM_TESTING_SMALL).map do
lineSet = LineSet.new(patterns)
["1", "2", "a"].each { |line| lineSet.addLine(line) }
lineSet.shuffle
lineSet.to_s
end.sort.uniq
assert_equal(["12a", "1a2", "21a", "2a1", "a12", "a21"], actual)
end
def test_shuffleLong
patterns = [/\A\d/, /\A[a-z]/, /\A[A-Z]/]
(1..SIZE_OF_RANDOM_TESTING_SMALL).map do
lineSet = LineSet.new(patterns)
["1", "2", "a", "b", "A", "B", "C", "D"].each { |line| lineSet.addLine(line) }
lineSet.shuffle
str = lineSet.to_s
assert_not_match(/\d{2}/, str)
assert_not_match(/[a-z]{2}/, str)
end
end
end
class TestLineSetParser < Test::Unit::TestCase
def test_parseInputStreamWithoutPhrase
parser = LineSetParser.new(nil)
inputLines = ["1", "a", "A", "2"]
inStream = MockInputStream.new(inputLines)
patterns = [/\A\d/, /\A[a-x]/, /\A[A-Z]/]
actual, lines = parser.parseInputStream(patterns, inStream, NullLineChecker.new(nil))
assert_equal(1, actual.size)
assert_equal(inputLines.sort, lines)
assert_equal([["1", "2"], ["a"], ["A"], []], actual[0].instance_variable_get(:@lineArrays))
end
def test_parseInputStreamWithPhrase
delimiter = "---END---"
parser = LineSetParser.new(nil)
parser.instance_variable_set(:@phrase, "END")
inputLines = ["1", "a", delimiter, "b", "2"]
inStream = MockInputStream.new(inputLines)
patterns = [/\A\d/, /\A[a-x]/]
actual, lines = parser.parseInputStream(patterns, inStream, NullLineChecker.new(nil))
assert_equal(2, actual.size)
assert_equal(inputLines.sort, lines)
assert_equal([["1"], ["a"], [delimiter]], actual[0].instance_variable_get(:@lineArrays))
assert_equal([["2"], ["b"], []], actual[1].instance_variable_get(:@lineArrays))
end
def test_parseInputStreamWithCheck
parser = LineSetParser.new(nil)
inputLines = ["#tag", "@a"]
inStream = MockInputStream.new(inputLines)
outStream = MockOutputStream.new
checker = TweetChecker.new(outStream)
actual, lines = parser.parseInputStream([], inStream, checker)
assert_equal("Unknown tag(s) #tag found\nMention(s) found in @a\n", outStream.str)
end
def setUpLineSetQueue
lineSetA = LineSet.new([])
lineSetB = LineSet.new([])
lineSetA.addLine("a")
lineSetA.addLine("B")
lineSetB.addLine("c")
lineSetB.addLine("D")
[lineSetA, lineSetB]
end
def test_shuffle
actual = (1..SIZE_OF_RANDOM_TESTING_SMALL).map do
delimiter = "---END---"
parser = LineSetParser.new(nil)
lineSetQueue = setUpLineSetQueue
parser.instance_variable_set(:@lineSetQueue, lineSetQueue)
parser.shuffle
lineSetQueue.map(&:to_s).join("")
end.sort.uniq
assert_equal(4, actual.size)
end
def test_writeToStream
parser = LineSetParser.new(nil)
lineSetQueue = setUpLineSetQueue
parser.instance_variable_set(:@lineSetQueue, lineSetQueue)
outStream = MockOutputStream.new
parser.shuffle
str = parser.writeToStream(outStream)
assert_equal("BDac", str.split("").sort.join(""))
assert_equal("BDac", outStream.str.split("").sort.join(""))
end
end
class TestFileIO < Test::Unit::TestCase
def parse(options, original, outFilename)
parser = LineSetParser.new(options)
expectedLines = original.sort.map { |s| s + "\n" }
assert_equal(expectedLines, parser.instance_variable_get(:@linesRead))
parser.shuffle
parser.write
lines = []
File.open(outFilename, "r") { |inStream|
while line = inStream.gets
lines << line
end
}
lines
end
def test_noParse
SIZE_OF_RANDOM_TESTING_FILE.times do
inTmpfile = Tempfile.new("input")
inFilename = inTmpfile.path
original = ["a", "b", "c", "d", "1", "2", "3"]
original.each { |s| inTmpfile.puts s }
inTmpfile.close
outTmpfile = Tempfile.new("output")
outFilename = outTmpfile.path
outTmpfile.close
options = MyProgramOption.new(["-i", inFilename, "-o", outFilename])
options.instance_variable_set(:@patterns, [/\d+/])
lines = parse(options, original, outFilename)
assert_equal(original.size, lines.size)
assert_equal(original.sort, lines.sort.map(&:chomp))
end
end
def test_withParse
SIZE_OF_RANDOM_TESTING_FILE.times do
inTmpfile = Tempfile.new("input")
inFilename = inTmpfile.path
phrase = "x"
original = ["a", "b", "c", phrase, "1", "2", "3"]
original.each { |s| inTmpfile.puts s }
inTmpfile.close
outTmpfile = Tempfile.new("output")
outFilename = outTmpfile.path
outTmpfile.close
options = MyProgramOption.new(["-i", inFilename, "-o", outFilename])
options.instance_variable_set(:@patterns, [/\d+/])
lines = parse(options, original, outFilename)
assert_equal(original.size, lines.size)
assert_equal(original[-3..-1], lines.sort.map(&:chomp)[0..2])
assert_equal(original[0..3], lines.sort.map(&:chomp)[3..-1])
end
end
data(
'empty set' => [[""], "x", true],
'not matched' => [["a"], "x", true],
'empty set string' => [[], "", true],
'empty lines' => [["a"], "", false])
def test_findParse(data)
lines, phrase, error = data
inTmpfile = Tempfile.new("input")
inFilename = inTmpfile.path
lines.each { |s| inTmpfile.puts s }
inTmpfile.close
outTmpfile = Tempfile.new("output")
outFilename = outTmpfile.path
outTmpfile.close
options = MyProgramOption.new(["-i", inFilename, "-o", outFilename, "-p", phrase])
options.instance_variable_set(:@patterns, [/\d+/])
if error
assert_raise(AppInvalidParameter) { LineSetParser.new(options) }
else
LineSetParser.new(options)
end
end
def test_identicalFiles
SIZE_OF_RANDOM_TESTING_FILE.times do
tmpfile = Tempfile.new("input")
filename = tmpfile.path
tmpfile.close
options = MyProgramOption.new(["-i", filename, "-o", filename])
assert_raise(AppInvalidParameter) { LineSetParser.new(options) }
end
end
def test_noInputFile
SIZE_OF_RANDOM_TESTING_FILE.times do
filename = "__f_i_l_e_not_exist__"
assert_false(File.exist?(filename))
options = MyProgramOption.new(["-i", filename])
assert_raise(AppInvalidParameter) { LineSetParser.new(options) }
end
end
end
class TestActualFile < Test::Unit::TestCase
def setup
@inputLines = readAndSort(TEST_INPUT_FILENAME)
assert_false(@inputLines.empty?)
@convertedLines = @inputLines
end
def checkIfIncludeCR(str, includeCR)
assert_equal(includeCR, str.include?("\r")) unless includeCR.nil?
end
def convertFile(outFilename, includeCR, encondingArgs)
@convertedLines = []
File.open(outFilename, "w") { |outStream|
@inputLines.each do |line|
convertedLine = line.encode(*encondingArgs)
checkIfIncludeCR(convertedLine, includeCR)
outStream.write(convertedLine)
@convertedLines << convertedLine
end
}
end
def readAndSort(inFilename)
lines = []
File.open(inFilename, "r") { |inStream|
while line = inStream.gets
lines << line
end
}
lines.sort
end
data(
'file to file' => "#{TEST_COMMAND_NAME} -i #{TEST_INPUT_FILENAME} -o ",
'file to stdout' => "#{TEST_COMMAND_NAME} -i #{TEST_INPUT_FILENAME} > ",
'stdin to file' => "#{TEST_COMMAND_NAME} < #{TEST_INPUT_FILENAME} -o ",
'stdin to stdout' => "#{TEST_COMMAND_NAME} < #{TEST_INPUT_FILENAME} > ")
def test_io(data)
command = data
outTmpfile = Tempfile.new("output")
outFilename = outTmpfile.path
outTmpfile.close
stdoutstr, stderrstr, status = Open3.capture3(command + outFilename)
assert_equal("", stdoutstr.chomp)
assert_equal("", remove_shebang_message(stderrstr.chomp))
assert_true(status.success?)
assert_equal(@inputLines, readAndSort(outFilename))
end
data(
'UTF-8 CRLF' => [true, ["UTF-8", :crlf_newline => true]],
'UTF-8 LF' => [false, ["UTF-8", :universal_newline => true]])
def test_keepLineFeed(data)
includeCR, encodingArgs = data
inTmpfile = Tempfile.new("input")
inFilename = inTmpfile.path
inTmpfile.close
outTmpfile = Tempfile.new("output")
outFilename = outTmpfile.path
outTmpfile.close
convertFile(inFilename, includeCR, encodingArgs)
command = "#{TEST_COMMAND_NAME} -i #{inFilename} -o #{outFilename}"
stdoutstr, stderrstr, status = Open3.capture3(command)
assert_equal("", stdoutstr.chomp)
assert_equal("", remove_shebang_message(stderrstr.chomp))
assert_true(status.success?)
lines = readAndSort(outFilename)
assert_equal(@convertedLines.sort, lines)
checkIfIncludeCR(lines.join(""), includeCR)
end
def test_shiftJIS
inTmpfile = Tempfile.new("input")
inFilename = inTmpfile.path
inTmpfile.close
outTmpfile = Tempfile.new("output")
outFilename = outTmpfile.path
outTmpfile.close
encodingArgs = ["Shift_JIS", :crlf_newline => true, :undef => :replace, :replace => ""],
convertFile(inFilename, nil, encodingArgs)
command = "#{TEST_COMMAND_NAME} -i #{inFilename} -o #{outFilename}"
stdoutstr, stderrstr, status = Open3.capture3(command)
assert_true(status.success?)
end
data(
'exist 1' => ["Software Developer Manuals", true],
'exist 2' => ["われわれはかしこいので", true],
'not exist' => ["我々は賢いので", false])
def test_finePhrase(data)
phrase, success = data
outTmpfile = Tempfile.new("output")
outFilename = outTmpfile.path
outTmpfile.close
command = "#{TEST_COMMAND_NAME} -i #{TEST_INPUT_FILENAME} -o #{outFilename} -p #{phrase}"
stdoutstr, stderrstr, status = Open3.capture3(command)
assert_equal("", stdoutstr.chomp)
assert_equal(success, status.success?)
if success
assert_equal("", remove_shebang_message(stderrstr.chomp))
assert_equal(@inputLines, readAndSort(outFilename))
else
assert_true(stderrstr.include?("Cannot find #{phrase} in the input."))
assert_equal([], readAndSort(outFilename))
end
end
def test_sampleFile
SIZE_OF_RANDOM_TESTING_FILE.times do
command = "#{TEST_COMMAND_NAME} -i #{TEST_SAMPLE_FILENAME} -p 5"
stdoutstr, stderrstr, status = Open3.capture3(command)
assert_false(stdoutstr.empty?)
assert_equal("", remove_shebang_message(stderrstr.chomp))
assert_true(status.success?)
str = stdoutstr.tr("\r\n@#xy ", "")
assert_match(/\A\D{5}\d{5}\z/, str)
end
end
data(
'set' => ["-c", true],
'set long' => ["--check", true],
'unset long' => ["--no-check", false])
def test_checkFile(data)
arg, expected = data
command = "#{TEST_COMMAND_NAME} -i #{TEST_SAMPLE_FILENAME} #{arg}"
stdoutstr, stderrstr, status = Open3.capture3(command)
assert_false(stdoutstr.empty?)
str = "Mention(s) found in 3 @x #y\n"
str += "Unknown tag(s) #y found\n"
str += "Unknown tag(s) #x found\n"
str += "Mention(s) found in c @y"
expectedStr = expected ? str : ""
assert_equal(expectedStr, remove_shebang_message(stderrstr.chomp))
end
end
| {
"content_hash": "568d0f95f9bdb9d1526e65f2ad38fe97",
"timestamp": "",
"source": "github",
"line_count": 753,
"max_line_length": 100,
"avg_line_length": 30.302788844621514,
"alnum_prop": 0.6249890437374003,
"repo_name": "zettsu-t/cPlusPlusFriend",
"id": "b0c7e8a9851a6673c3a845a547c0cf72be771a90",
"size": "23313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shuffleLinesTest.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "15139"
},
{
"name": "Batchfile",
"bytes": "820"
},
{
"name": "C",
"bytes": "14964"
},
{
"name": "C++",
"bytes": "496333"
},
{
"name": "CMake",
"bytes": "4852"
},
{
"name": "Dockerfile",
"bytes": "4569"
},
{
"name": "Makefile",
"bytes": "55763"
},
{
"name": "Python",
"bytes": "140390"
},
{
"name": "R",
"bytes": "310386"
},
{
"name": "Ruby",
"bytes": "76315"
},
{
"name": "Rust",
"bytes": "49870"
},
{
"name": "Shell",
"bytes": "1045"
},
{
"name": "Stan",
"bytes": "5992"
}
],
"symlink_target": ""
} |
package org.gradle.caching.internal.controller.operations;
import org.gradle.caching.BuildCacheKey;
import org.gradle.caching.internal.operations.BuildCacheRemoteLoadBuildOperationType;
public class LoadOperationDetails implements BuildCacheRemoteLoadBuildOperationType.Details {
private final BuildCacheKey buildCacheKey;
public LoadOperationDetails(BuildCacheKey buildCacheKey) {
this.buildCacheKey = buildCacheKey;
}
@Override
public String getCacheKey() {
return buildCacheKey.getHashCode();
}
}
| {
"content_hash": "0c1f33bebc65efd29a9289cccaf1493f",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 93,
"avg_line_length": 27.35,
"alnum_prop": 0.7879341864716636,
"repo_name": "lsmaira/gradle",
"id": "bbe03147afc17171d18bbf0cbd4e3a624e032a18",
"size": "1162",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "subprojects/build-cache/src/main/java/org/gradle/caching/internal/controller/operations/LoadOperationDetails.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "277"
},
{
"name": "Brainfuck",
"bytes": "54"
},
{
"name": "C",
"bytes": "98577"
},
{
"name": "C++",
"bytes": "1805943"
},
{
"name": "CSS",
"bytes": "169594"
},
{
"name": "CoffeeScript",
"bytes": "620"
},
{
"name": "GAP",
"bytes": "424"
},
{
"name": "Gherkin",
"bytes": "191"
},
{
"name": "Groovy",
"bytes": "23143304"
},
{
"name": "HTML",
"bytes": "90514"
},
{
"name": "Java",
"bytes": "22751766"
},
{
"name": "JavaScript",
"bytes": "206201"
},
{
"name": "Kotlin",
"bytes": "661239"
},
{
"name": "Objective-C",
"bytes": "840"
},
{
"name": "Objective-C++",
"bytes": "441"
},
{
"name": "Perl",
"bytes": "37849"
},
{
"name": "Python",
"bytes": "57"
},
{
"name": "Ruby",
"bytes": "16"
},
{
"name": "Scala",
"bytes": "27838"
},
{
"name": "Shell",
"bytes": "6768"
},
{
"name": "XSLT",
"bytes": "58117"
}
],
"symlink_target": ""
} |
<!doctype html>
<!-- This file is generated by build.py. -->
<title>canvas; overflow:visible; -o-object-fit:fill; -o-object-position:center 100%</title>
<link rel="stylesheet" href="../../support/reftests.css">
<link rel='match' href='visible_auto_50_100-ref.html'>
<style>
#test > * { overflow:visible; -o-object-fit:fill; -o-object-position:center 100% }
</style>
<div id="test">
<canvas width=148 height=222></canvas>
</div>
<script>
var c = document.querySelector('canvas').getContext('2d');
var w = c.canvas.width / 2, h = c.canvas.height / 2;
c.fillStyle = 'blue';
c.fillRect(0, 0, w, h);
c.fillRect(w, h, w, h);
c.fillStyle = 'purple';
c.fillRect(w, 0, w, h);
c.fillRect(0, h, w, h);
</script>
| {
"content_hash": "1786e90f6e3560a14c0ac121a53f1aed",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 91,
"avg_line_length": 33.476190476190474,
"alnum_prop": 0.6586059743954481,
"repo_name": "frivoal/presto-testo",
"id": "6558836d2dd09be7b1bac07523e55cb66f7d3803",
"size": "703",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "css/image-fit/reftests/canvas-tall/visible_fill_center_100.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "2312"
},
{
"name": "ActionScript",
"bytes": "23470"
},
{
"name": "AutoHotkey",
"bytes": "8832"
},
{
"name": "Batchfile",
"bytes": "5001"
},
{
"name": "C",
"bytes": "116512"
},
{
"name": "C++",
"bytes": "219467"
},
{
"name": "CSS",
"bytes": "207914"
},
{
"name": "Erlang",
"bytes": "18523"
},
{
"name": "Groff",
"bytes": "674"
},
{
"name": "HTML",
"bytes": "103357488"
},
{
"name": "Haxe",
"bytes": "3874"
},
{
"name": "Java",
"bytes": "125658"
},
{
"name": "JavaScript",
"bytes": "22514682"
},
{
"name": "Makefile",
"bytes": "13409"
},
{
"name": "PHP",
"bytes": "531453"
},
{
"name": "Perl",
"bytes": "321672"
},
{
"name": "Python",
"bytes": "948191"
},
{
"name": "Ruby",
"bytes": "1006850"
},
{
"name": "Shell",
"bytes": "12140"
},
{
"name": "Smarty",
"bytes": "1860"
},
{
"name": "XSLT",
"bytes": "2567445"
}
],
"symlink_target": ""
} |
import ajaxWrapper from "../helpers/ajaxWrapper";
import config from "../config/config";
import AppDispatcher from "../AppDispatcher";
import AppsEvents from "../events/AppsEvents";
var AppsActions = {
requestApps: function () {
const embed = "embed=group.groups&embed=group.apps&" +
"embed=group.apps.deployments&embed=group.apps.counts&" +
"embed=group.apps.readiness";
this.request({
url: `${config.apiURL}v2/groups?${embed}`
})
.success(function (groups) {
AppDispatcher.dispatch({
actionType: AppsEvents.REQUEST_APPS,
data: groups
});
})
.error(function (error) {
AppDispatcher.dispatch({
actionType: AppsEvents.REQUEST_APPS_ERROR,
data: error
});
});
},
requestApp: function (appId) {
this.request({
url: `${config.apiURL}v2/apps/${appId}?embed=app.taskStats&` +
`embed=app.readiness`
})
.success(function (app) {
AppDispatcher.dispatch({
actionType: AppsEvents.REQUEST_APP,
data: app
});
})
.error(function (error) {
AppDispatcher.dispatch({
actionType: AppsEvents.REQUEST_APP_ERROR,
data: error
});
});
},
createApp: function (newAppAttributes) {
if (newAppAttributes == null) {
AppDispatcher.dispatch({
actionType: AppsEvents.CREATE_APP_ERROR
});
return;
}
if (newAppAttributes.container != null &&
newAppAttributes.container.volumes != null &&
newAppAttributes.container.volumes.some(
volume => volume.persistent != null
)
) {
newAppAttributes.residency = {
relaunchEscalationTimeoutSeconds: 10,
taskLostBehavior: "WAIT_FOREVER"
};
}
if (newAppAttributes.container != null &&
newAppAttributes.container.volumes != null &&
newAppAttributes.container.volumes.some(
volume => volume.external != null
)
) {
newAppAttributes.upgradeStrategy = {
maximumOverCapacity: 0,
minimumHealthCapacity: 0
};
}
this.request({
method: "POST",
data: newAppAttributes,
url: `${config.apiURL}v2/apps`
})
.success(function (app) {
AppDispatcher.dispatch({
actionType: AppsEvents.CREATE_APP,
data: app
});
})
.error(function (error) {
AppDispatcher.dispatch({
actionType: AppsEvents.CREATE_APP_ERROR,
data: error
});
});
},
deleteApp: function (appId) {
this.request({
method: "DELETE",
headers: {
"Content-Type": "application/json"
},
url: `${config.apiURL}v2/apps/${appId}`
})
.success(function (app) {
AppDispatcher.dispatch({
actionType: AppsEvents.DELETE_APP,
data: app,
appId: appId
});
})
.error(function (error) {
AppDispatcher.dispatch({
actionType: AppsEvents.DELETE_APP_ERROR,
data: error
});
});
},
restartApp: function (appId, force = false) {
var url = `${config.apiURL}v2/apps/${appId}/restart`;
if (force) {
url = url + "?force=true";
}
this.request({
method: "POST",
data: {
force: force
},
url: url
})
.success(function (app) {
AppDispatcher.dispatch({
actionType: AppsEvents.RESTART_APP,
data: app,
appId: appId
});
})
.error(function (error) {
AppDispatcher.dispatch({
actionType: AppsEvents.RESTART_APP_ERROR,
data: error
});
});
},
scaleApp: function (appId, instances, force = false) {
var url = `${config.apiURL}v2/apps/${appId}`;
if (force) {
url = url + "?force=true";
}
this.request({
method: "PUT",
data: {
instances: instances
},
headers: {
"Content-Type": "application/json"
},
url: url
})
.success(function (app) {
AppDispatcher.dispatch({
actionType: AppsEvents.SCALE_APP,
data: app,
appId: appId
});
})
.error(function (error) {
AppDispatcher.dispatch({
actionType: AppsEvents.SCALE_APP_ERROR,
data: error,
instances: instances
});
});
},
applySettingsOnApp: function (appId, settings, isEditing = false,
force = false) {
// Used to mark current app config as stale
AppDispatcher.dispatch({
actionType: AppsEvents.APPLY_APP_REQUEST,
appId: appId
});
var url = `${config.apiURL}v2/apps/${appId}`;
if (force) {
url = url + "?force=true";
}
this.request({
method: "PUT",
data: settings,
url: url
})
.success(function (app) {
AppDispatcher.dispatch({
actionType: AppsEvents.APPLY_APP,
data: app,
appId: appId,
isEditing: isEditing
});
})
.error(function (error) {
AppDispatcher.dispatch({
actionType: AppsEvents.APPLY_APP_ERROR,
data: error,
isEditing: isEditing
});
});
},
emitFilterCounts: function (filterCounts) {
AppDispatcher.dispatchNext({
actionType: AppsEvents.UPDATE_APPS_FILTER_COUNT,
data: filterCounts
});
},
request: ajaxWrapper
};
export default AppsActions;
| {
"content_hash": "b3fd960527602d378d049b0ac08b60ae",
"timestamp": "",
"source": "github",
"line_count": 223,
"max_line_length": 68,
"avg_line_length": 24.699551569506728,
"alnum_prop": 0.5497458242556281,
"repo_name": "cribalik/marathon-ui",
"id": "1013ce63f15a73e8984fa0debbef1ca0053ec54b",
"size": "5508",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/js/actions/AppsActions.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "58893"
},
{
"name": "HTML",
"bytes": "395"
},
{
"name": "JavaScript",
"bytes": "872006"
},
{
"name": "Smarty",
"bytes": "1226"
}
],
"symlink_target": ""
} |
iconf is command let you manage your Variables / Alias / scripts
## install
## STEP 1
```bash
wget -O - https://raw.githubusercontent.com/broven/iconf/master/install.sh | bash
```
## STEP 2
Add following to your shell rc file
```
#########iconf########
export path_to_iconf=~/iconf/ # iconf install path
export PATH="${path_to_iconf}bin:${PATH}"
path_to_iconfrc=${path_to_iconf}rc
source $path_to_iconfrc
alias iconf='source iconf-main'
######################
```
## Usage
```
Usage: iconf <command> <operation options>
Commands:
v|var variable operation
a|alias alias operation
s|script script operation
```
### variable
```
iconf <v|var> [operation] [variable]
Options:
-n|--new add a new variable
-d|--delete delete a variable
-l|--list list all your variables
```
### alias
```
iconf <a|alias> [operation]
Options:
-n|--new Create new alias
-d|--delte delete alias
-l|--list list all alias you have
```
### script
```
TODO
```
| {
"content_hash": "a154837347c11e4313a0c2523d3311f6",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 81,
"avg_line_length": 21.0625,
"alnum_prop": 0.6152324431256182,
"repo_name": "broven/iconf",
"id": "7db5ca4d800d3e987211bf6b76a001602b98d76f",
"size": "1011",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "4238"
}
],
"symlink_target": ""
} |
// Specifically test buffer module regression.
import {
Buffer as ImportedBuffer,
SlowBuffer as ImportedSlowBuffer,
transcode,
TranscodeEncoding,
constants,
kMaxLength,
kStringMaxLength,
Blob,
} from 'buffer';
const utf8Buffer = new Buffer('test');
const base64Buffer = new Buffer('', 'base64');
const octets: Uint8Array = new Uint8Array(123);
const octetBuffer = new Buffer(octets);
const sharedBuffer = new Buffer(octets.buffer);
const copiedBuffer = new Buffer(utf8Buffer);
console.log(Buffer.isBuffer(octetBuffer));
console.log(Buffer.isEncoding('utf8'));
console.log(Buffer.byteLength('xyz123'));
console.log(Buffer.byteLength('xyz123', 'ascii'));
const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>);
const result2 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>, 9999999);
// Module constants
{
const value1: number = constants.MAX_LENGTH;
const value2: number = constants.MAX_STRING_LENGTH;
const value3: number = kMaxLength;
const value4: number = kStringMaxLength;
}
// Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64()
{
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
buf.swap16();
buf.swap32();
buf.swap64();
}
// Class Method: Buffer.from(data)
{
// Array
const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72] as ReadonlyArray<number>);
// Buffer
const buf2: Buffer = Buffer.from(buf1, 1, 2);
// String
const buf3: Buffer = Buffer.from('this is a tést');
// ArrayBuffer
const arrUint16: Uint16Array = new Uint16Array(2);
arrUint16[0] = 5000;
arrUint16[1] = 4000;
const buf4: Buffer = Buffer.from(arrUint16.buffer);
const arrUint8: Uint8Array = new Uint8Array(2);
const buf5: Buffer = Buffer.from(arrUint8);
const buf6: Buffer = Buffer.from(buf1);
const sb: SharedArrayBuffer = {} as any;
const buf7: Buffer = Buffer.from(sb);
// $ExpectError
Buffer.from({});
}
// Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
{
const arr: Uint16Array = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
let buf: Buffer;
buf = Buffer.from(arr.buffer, 1);
buf = Buffer.from(arr.buffer, 0, 1);
// $ExpectError
Buffer.from("this is a test", 1, 1);
// Ideally passing a normal Buffer would be a type error too, but it's not
// since Buffer is assignable to ArrayBuffer currently
}
// Class Method: Buffer.from(str[, encoding])
{
const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex');
/* tslint:disable-next-line no-construct */
Buffer.from(new String("DEADBEEF"), "hex");
// $ExpectError
Buffer.from(buf2, 'hex');
}
// Class Method: Buffer.from(object, [, byteOffset[, length]]) (Implicit coercion)
{
const pseudoBuf = { valueOf() { return Buffer.from([1, 2, 3]); } };
let buf: Buffer = Buffer.from(pseudoBuf);
const pseudoString = { valueOf() { return "Hello"; }};
buf = Buffer.from(pseudoString);
buf = Buffer.from(pseudoString, "utf-8");
// $ExpectError
Buffer.from(pseudoString, 1, 2);
const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } };
buf = Buffer.from(pseudoArrayBuf, 1, 1);
}
// Class Method: Buffer.alloc(size[, fill[, encoding]])
{
const buf1: Buffer = Buffer.alloc(5);
const buf2: Buffer = Buffer.alloc(5, 'a');
const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
}
// Class Method: Buffer.allocUnsafe(size)
{
const buf: Buffer = Buffer.allocUnsafe(5);
}
// Class Method: Buffer.allocUnsafeSlow(size)
{
const buf: Buffer = Buffer.allocUnsafeSlow(10);
}
// Class Method byteLenght
{
let len: number;
len = Buffer.byteLength("foo");
len = Buffer.byteLength("foo", "utf8");
const b = Buffer.from("bar");
len = Buffer.byteLength(b);
len = Buffer.byteLength(b, "utf16le");
const ab = new ArrayBuffer(15);
len = Buffer.byteLength(ab);
len = Buffer.byteLength(ab, "ascii");
const dv = new DataView(ab);
len = Buffer.byteLength(dv);
len = Buffer.byteLength(dv, "utf16le");
}
// Class Method poolSize
{
let s: number;
s = Buffer.poolSize;
Buffer.poolSize = 4096;
}
// Test that TS 1.6 works with the 'as Buffer' annotation
// on isBuffer.
let a: Buffer | number;
a = new Buffer(10);
if (Buffer.isBuffer(a)) {
a.writeUInt8(3, 4);
}
// write* methods return offsets.
const b = new Buffer(16);
let result: number = b.writeUInt32LE(0, 0);
result = b.writeUInt16LE(0, 4);
result = b.writeUInt8(0, 6);
result = b.writeInt8(0, 7);
result = b.writeDoubleLE(0, 8);
result = b.write('asd');
result = b.write('asd', 'hex');
result = b.write('asd', 123, 'hex');
result = b.write('asd', 123, 123, 'hex');
// fill returns the input buffer.
b.fill('a').fill('b');
{
const buffer = new Buffer('123');
let index: number;
index = buffer.indexOf("23");
index = buffer.indexOf("23", 1);
index = buffer.indexOf("23", 1, "utf8");
index = buffer.indexOf(23);
index = buffer.indexOf(buffer);
}
{
const buffer = new Buffer('123');
let index: number;
index = buffer.lastIndexOf("23");
index = buffer.lastIndexOf("23", 1);
index = buffer.lastIndexOf("23", 1, "utf8");
index = buffer.lastIndexOf(23);
index = buffer.lastIndexOf(buffer);
}
{
const buffer = new Buffer('123');
const val: [number, number] = [1, 1];
/* comment out for --target es5
for (let entry of buffer.entries()) {
val = entry;
}
*/
}
{
const buffer = new Buffer('123');
let includes: boolean;
includes = buffer.includes("23");
includes = buffer.includes("23", 1);
includes = buffer.includes("23", 1, "utf8");
includes = buffer.includes(23);
includes = buffer.includes(23, 1);
includes = buffer.includes(23, 1, "utf8");
includes = buffer.includes(buffer);
includes = buffer.includes(buffer, 1);
includes = buffer.includes(buffer, 1, "utf8");
}
{
const buffer = new Buffer('123');
const val = 1;
/* comment out for --target es5
for (let key of buffer.keys()) {
val = key;
}
*/
}
{
const buffer = new Buffer('123');
const val = 1;
/* comment out for --target es5
for (let value of buffer.values()) {
val = value;
}
*/
}
// Imported Buffer from buffer module works properly
{
const b = new ImportedBuffer('123');
b.writeUInt8(0, 6);
const sb = new ImportedSlowBuffer(43);
b.writeUInt8(0, 6);
}
// Buffer has Uint8Array's buffer field (an ArrayBuffer).
{
const buffer = new Buffer('123');
const octets = new Uint8Array(buffer.buffer);
}
// Inherited from Uint8Array but return buffer
{
const b = Buffer.from('asd');
let res: Buffer = b.reverse();
res = b.subarray();
res = b.subarray(1);
res = b.subarray(1, 2);
}
// Buffer module, transcode function
{
transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer
const source: TranscodeEncoding = 'utf8';
const target: TranscodeEncoding = 'ascii';
transcode(Buffer.from('€'), source, target); // $ExpectType Buffer
}
{
const a = Buffer.alloc(1000);
a.writeBigInt64BE(123n);
a.writeBigInt64LE(123n);
a.writeBigUInt64BE(123n);
a.writeBigUInt64LE(123n);
let b: bigint = a.readBigInt64BE(123);
b = a.readBigInt64LE(123);
b = a.readBigUInt64LE(123);
b = a.readBigUInt64BE(123);
}
async () => {
const blob = new Blob(['asd', Buffer.from('test'), new Blob(['dummy'])], {
type: 'application/javascript',
encoding: 'base64',
});
blob.size; // $ExpectType number
blob.type; // $ExpectType string
blob.arrayBuffer(); // $ExpectType Promise<ArrayBuffer>
blob.text(); // $ExpectType Promise<string>
blob.slice(); // $ExpectType Blob
blob.slice(1); // $ExpectType Blob
blob.slice(1, 2); // $ExpectType Blob
blob.slice(1, 2, 'other'); // $ExpectType Blob
};
| {
"content_hash": "ff703acee01d90058d17852fd35a9618",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 100,
"avg_line_length": 27.482876712328768,
"alnum_prop": 0.6362616822429906,
"repo_name": "georgemarshall/DefinitelyTyped",
"id": "5ecc30eca2ed0d0458b167253ddef63e0e3bba83",
"size": "8030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "types/node/test/buffer.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16338312"
},
{
"name": "Ruby",
"bytes": "40"
},
{
"name": "Shell",
"bytes": "73"
},
{
"name": "TypeScript",
"bytes": "17728346"
}
],
"symlink_target": ""
} |
<testsuites>
<testsuite tests="3" failures="0" time="17.564" name="github.com/GoogleCloudPlatform/golang-samples">
<properties>
<property name="go.version" value="go1.12.4"/>
</properties>
<testcase classname="golang-samples" name="TestBadFiles" time="0.040"/>
</testsuite>
<testsuite tests="2" failures="0" time="0.006" name="github.com/GoogleCloudPlatform/golang-samples/appengine/go11x/helloworld">
<properties>
<property name="go.version" value="go1.12.4"/>
</properties>
<testcase classname="helloworld" name="TestIndexHandler" time="0.000"/>
</testsuite>
</testsuites>
| {
"content_hash": "3264e5f52698da016f2a1fb589dc5eab",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 127,
"avg_line_length": 41.07142857142857,
"alnum_prop": 0.7478260869565218,
"repo_name": "GoogleCloudPlatform/flaky-service",
"id": "f969bc3eaa961c5905a5e874552a5d7f89c4a870",
"size": "575",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "packages/api/test/fixtures/passed.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18693"
},
{
"name": "Dockerfile",
"bytes": "604"
},
{
"name": "HTML",
"bytes": "24051"
},
{
"name": "JavaScript",
"bytes": "164005"
},
{
"name": "Python",
"bytes": "2927"
},
{
"name": "SCSS",
"bytes": "1522"
},
{
"name": "TypeScript",
"bytes": "220636"
}
],
"symlink_target": ""
} |
"""Behaviors for servicing RPCs."""
# base_interfaces and interfaces are referenced from specification in this
# module.
from grpc.framework.base import interfaces as base_interfaces # pylint: disable=unused-import
from grpc.framework.face import _control
from grpc.framework.face import exceptions
from grpc.framework.face import interfaces # pylint: disable=unused-import
from grpc.framework.foundation import abandonment
from grpc.framework.foundation import callable_util
from grpc.framework.foundation import stream
from grpc.framework.foundation import stream_util
class _ValueInStreamOutConsumer(stream.Consumer):
"""A stream.Consumer that maps inputs one-to-many onto outputs."""
def __init__(self, behavior, context, downstream):
"""Constructor.
Args:
behavior: A callable that takes a single value and an
interfaces.RpcContext and returns a generator of arbitrarily many
values.
context: An interfaces.RpcContext.
downstream: A stream.Consumer to which to pass the values generated by the
given behavior.
"""
self._behavior = behavior
self._context = context
self._downstream = downstream
def consume(self, value):
_control.pipe_iterator_to_consumer(
self._behavior(value, self._context), self._downstream,
self._context.is_active, False)
def terminate(self):
self._downstream.terminate()
def consume_and_terminate(self, value):
_control.pipe_iterator_to_consumer(
self._behavior(value, self._context), self._downstream,
self._context.is_active, True)
def _pool_wrap(behavior, operation_context):
"""Wraps an operation-related behavior so that it may be called in a pool.
Args:
behavior: A callable related to carrying out an operation.
operation_context: A base_interfaces.OperationContext for the operation.
Returns:
A callable that when called carries out the behavior of the given callable
and handles whatever exceptions it raises appropriately.
"""
def translation(*args):
try:
behavior(*args)
except (
abandonment.Abandoned,
exceptions.ExpirationError,
exceptions.CancellationError,
exceptions.ServicedError,
exceptions.NetworkError) as e:
if operation_context.is_active():
operation_context.fail(e)
except Exception as e:
operation_context.fail(e)
return callable_util.with_exceptions_logged(
translation, _control.INTERNAL_ERROR_LOG_MESSAGE)
def adapt_inline_value_in_value_out(method):
def adaptation(response_consumer, operation_context):
rpc_context = _control.RpcContext(operation_context)
return stream_util.TransformingConsumer(
lambda request: method.service(request, rpc_context), response_consumer)
return adaptation
def adapt_inline_value_in_stream_out(method):
def adaptation(response_consumer, operation_context):
rpc_context = _control.RpcContext(operation_context)
return _ValueInStreamOutConsumer(
method.service, rpc_context, response_consumer)
return adaptation
def adapt_inline_stream_in_value_out(method, pool):
def adaptation(response_consumer, operation_context):
rendezvous = _control.Rendezvous()
operation_context.add_termination_callback(rendezvous.set_outcome)
def in_pool_thread():
response_consumer.consume_and_terminate(
method.service(rendezvous, _control.RpcContext(operation_context)))
pool.submit(_pool_wrap(in_pool_thread, operation_context))
return rendezvous
return adaptation
def adapt_inline_stream_in_stream_out(method, pool):
"""Adapts an interfaces.InlineStreamInStreamOutMethod for use with Consumers.
RPCs may be serviced by calling the return value of this function, passing
request values to the stream.Consumer returned from that call, and receiving
response values from the stream.Consumer passed to that call.
Args:
method: An interfaces.InlineStreamInStreamOutMethod.
pool: A thread pool.
Returns:
A callable that takes a stream.Consumer and a
base_interfaces.OperationContext and returns a stream.Consumer.
"""
def adaptation(response_consumer, operation_context):
rendezvous = _control.Rendezvous()
operation_context.add_termination_callback(rendezvous.set_outcome)
def in_pool_thread():
_control.pipe_iterator_to_consumer(
method.service(rendezvous, _control.RpcContext(operation_context)),
response_consumer, operation_context.is_active, True)
pool.submit(_pool_wrap(in_pool_thread, operation_context))
return rendezvous
return adaptation
def adapt_event_value_in_value_out(method):
def adaptation(response_consumer, operation_context):
def on_payload(payload):
method.service(
payload, response_consumer.consume_and_terminate,
_control.RpcContext(operation_context))
return _control.UnaryConsumer(on_payload)
return adaptation
def adapt_event_value_in_stream_out(method):
def adaptation(response_consumer, operation_context):
def on_payload(payload):
method.service(
payload, response_consumer, _control.RpcContext(operation_context))
return _control.UnaryConsumer(on_payload)
return adaptation
def adapt_event_stream_in_value_out(method):
def adaptation(response_consumer, operation_context):
rpc_context = _control.RpcContext(operation_context)
return method.service(response_consumer.consume_and_terminate, rpc_context)
return adaptation
def adapt_event_stream_in_stream_out(method):
def adaptation(response_consumer, operation_context):
return method.service(
response_consumer, _control.RpcContext(operation_context))
return adaptation
| {
"content_hash": "f8287d8dfc0cf9cd5d5718111882f2e3",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 94,
"avg_line_length": 35.875,
"alnum_prop": 0.7381533101045297,
"repo_name": "nmittler/grpc",
"id": "26bde129687a5b48b6bb7ad849665b10ab19e722",
"size": "7269",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/python/src/grpc/framework/face/_service.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3067591"
},
{
"name": "C#",
"bytes": "384252"
},
{
"name": "C++",
"bytes": "499254"
},
{
"name": "JavaScript",
"bytes": "135884"
},
{
"name": "Makefile",
"bytes": "1105184"
},
{
"name": "Objective-C",
"bytes": "145264"
},
{
"name": "PHP",
"bytes": "100749"
},
{
"name": "Protocol Buffer",
"bytes": "133189"
},
{
"name": "Python",
"bytes": "649840"
},
{
"name": "Ruby",
"bytes": "291726"
},
{
"name": "Shell",
"bytes": "17838"
}
],
"symlink_target": ""
} |
namespace v8 {
namespace internal {
#define DEFINE_COMPILE(type) \
void L##type::CompileToNative(LCodeGen* generator) { \
generator->Do##type(this); \
}
LITHIUM_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE)
#undef DEFINE_COMPILE
#ifdef DEBUG
void LInstruction::VerifyCall() {
// Call instructions can use only fixed registers as temporaries and
// outputs because all registers are blocked by the calling convention.
// Inputs operands must use a fixed register or use-at-start policy or
// a non-register policy.
DCHECK(Output() == NULL ||
LUnallocated::cast(Output())->HasFixedPolicy() ||
!LUnallocated::cast(Output())->HasRegisterPolicy());
for (UseIterator it(this); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
DCHECK(operand->HasFixedPolicy() ||
operand->IsUsedAtStart());
}
for (TempIterator it(this); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
DCHECK(operand->HasFixedPolicy() ||!operand->HasRegisterPolicy());
}
}
#endif
bool LInstruction::HasDoubleRegisterResult() {
return HasResult() && result()->IsDoubleRegister();
}
bool LInstruction::HasDoubleRegisterInput() {
for (int i = 0; i < InputCount(); i++) {
LOperand* op = InputAt(i);
if (op != NULL && op->IsDoubleRegister()) {
return true;
}
}
return false;
}
bool LInstruction::IsDoubleInput(X87Register reg, LCodeGen* cgen) {
for (int i = 0; i < InputCount(); i++) {
LOperand* op = InputAt(i);
if (op != NULL && op->IsDoubleRegister()) {
if (cgen->ToX87Register(op).is(reg)) return true;
}
}
return false;
}
void LInstruction::PrintTo(StringStream* stream) {
stream->Add("%s ", this->Mnemonic());
PrintOutputOperandTo(stream);
PrintDataTo(stream);
if (HasEnvironment()) {
stream->Add(" ");
environment()->PrintTo(stream);
}
if (HasPointerMap()) {
stream->Add(" ");
pointer_map()->PrintTo(stream);
}
}
void LInstruction::PrintDataTo(StringStream* stream) {
stream->Add("= ");
for (int i = 0; i < InputCount(); i++) {
if (i > 0) stream->Add(" ");
if (InputAt(i) == NULL) {
stream->Add("NULL");
} else {
InputAt(i)->PrintTo(stream);
}
}
}
void LInstruction::PrintOutputOperandTo(StringStream* stream) {
if (HasResult()) result()->PrintTo(stream);
}
void LLabel::PrintDataTo(StringStream* stream) {
LGap::PrintDataTo(stream);
LLabel* rep = replacement();
if (rep != NULL) {
stream->Add(" Dead block replaced with B%d", rep->block_id());
}
}
bool LGap::IsRedundant() const {
for (int i = 0; i < 4; i++) {
if (parallel_moves_[i] != NULL && !parallel_moves_[i]->IsRedundant()) {
return false;
}
}
return true;
}
void LGap::PrintDataTo(StringStream* stream) {
for (int i = 0; i < 4; i++) {
stream->Add("(");
if (parallel_moves_[i] != NULL) {
parallel_moves_[i]->PrintDataTo(stream);
}
stream->Add(") ");
}
}
const char* LArithmeticD::Mnemonic() const {
switch (op()) {
case Token::ADD: return "add-d";
case Token::SUB: return "sub-d";
case Token::MUL: return "mul-d";
case Token::DIV: return "div-d";
case Token::MOD: return "mod-d";
default:
UNREACHABLE();
return NULL;
}
}
const char* LArithmeticT::Mnemonic() const {
switch (op()) {
case Token::ADD: return "add-t";
case Token::SUB: return "sub-t";
case Token::MUL: return "mul-t";
case Token::MOD: return "mod-t";
case Token::DIV: return "div-t";
case Token::BIT_AND: return "bit-and-t";
case Token::BIT_OR: return "bit-or-t";
case Token::BIT_XOR: return "bit-xor-t";
case Token::ROR: return "ror-t";
case Token::SHL: return "sal-t";
case Token::SAR: return "sar-t";
case Token::SHR: return "shr-t";
default:
UNREACHABLE();
return NULL;
}
}
bool LGoto::HasInterestingComment(LCodeGen* gen) const {
return !gen->IsNextEmittedBlock(block_id());
}
void LGoto::PrintDataTo(StringStream* stream) {
stream->Add("B%d", block_id());
}
void LBranch::PrintDataTo(StringStream* stream) {
stream->Add("B%d | B%d on ", true_block_id(), false_block_id());
value()->PrintTo(stream);
}
void LCompareNumericAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if ");
left()->PrintTo(stream);
stream->Add(" %s ", Token::String(op()));
right()->PrintTo(stream);
stream->Add(" then B%d else B%d", true_block_id(), false_block_id());
}
void LIsStringAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if is_string(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LIsSmiAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if is_smi(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LIsUndetectableAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if is_undetectable(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LStringCompareAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if string_compare(");
left()->PrintTo(stream);
right()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LHasInstanceTypeAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if has_instance_type(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LHasCachedArrayIndexAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if has_cached_array_index(");
value()->PrintTo(stream);
stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}
void LClassOfTestAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if class_of_test(");
value()->PrintTo(stream);
stream->Add(", \"%o\") then B%d else B%d",
*hydrogen()->class_name(),
true_block_id(),
false_block_id());
}
void LTypeofIsAndBranch::PrintDataTo(StringStream* stream) {
stream->Add("if typeof ");
value()->PrintTo(stream);
stream->Add(" == \"%s\" then B%d else B%d",
hydrogen()->type_literal()->ToCString().get(),
true_block_id(), false_block_id());
}
void LStoreCodeEntry::PrintDataTo(StringStream* stream) {
stream->Add(" = ");
function()->PrintTo(stream);
stream->Add(".code_entry = ");
code_object()->PrintTo(stream);
}
void LInnerAllocatedObject::PrintDataTo(StringStream* stream) {
stream->Add(" = ");
base_object()->PrintTo(stream);
stream->Add(" + ");
offset()->PrintTo(stream);
}
void LCallFunction::PrintDataTo(StringStream* stream) {
context()->PrintTo(stream);
stream->Add(" ");
function()->PrintTo(stream);
if (hydrogen()->HasVectorAndSlot()) {
stream->Add(" (type-feedback-vector ");
temp_vector()->PrintTo(stream);
stream->Add(" ");
temp_slot()->PrintTo(stream);
stream->Add(")");
}
}
void LCallJSFunction::PrintDataTo(StringStream* stream) {
stream->Add("= ");
function()->PrintTo(stream);
stream->Add("#%d / ", arity());
}
void LCallWithDescriptor::PrintDataTo(StringStream* stream) {
for (int i = 0; i < InputCount(); i++) {
InputAt(i)->PrintTo(stream);
stream->Add(" ");
}
stream->Add("#%d / ", arity());
}
void LLoadContextSlot::PrintDataTo(StringStream* stream) {
context()->PrintTo(stream);
stream->Add("[%d]", slot_index());
}
void LStoreContextSlot::PrintDataTo(StringStream* stream) {
context()->PrintTo(stream);
stream->Add("[%d] <- ", slot_index());
value()->PrintTo(stream);
}
void LInvokeFunction::PrintDataTo(StringStream* stream) {
stream->Add("= ");
context()->PrintTo(stream);
stream->Add(" ");
function()->PrintTo(stream);
stream->Add(" #%d / ", arity());
}
void LCallNewArray::PrintDataTo(StringStream* stream) {
stream->Add("= ");
context()->PrintTo(stream);
stream->Add(" ");
constructor()->PrintTo(stream);
stream->Add(" #%d / ", arity());
ElementsKind kind = hydrogen()->elements_kind();
stream->Add(" (%s) ", ElementsKindToString(kind));
}
void LAccessArgumentsAt::PrintDataTo(StringStream* stream) {
arguments()->PrintTo(stream);
stream->Add(" length ");
length()->PrintTo(stream);
stream->Add(" index ");
index()->PrintTo(stream);
}
int LPlatformChunk::GetNextSpillIndex(RegisterKind kind) {
// Skip a slot if for a double-width slot.
if (kind == DOUBLE_REGISTERS) {
current_frame_slots_++;
current_frame_slots_ |= 1;
num_double_slots_++;
}
return current_frame_slots_++;
}
LOperand* LPlatformChunk::GetNextSpillSlot(RegisterKind kind) {
int index = GetNextSpillIndex(kind);
if (kind == DOUBLE_REGISTERS) {
return LDoubleStackSlot::Create(index, zone());
} else {
DCHECK(kind == GENERAL_REGISTERS);
return LStackSlot::Create(index, zone());
}
}
void LStoreNamedField::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
std::ostringstream os;
os << hydrogen()->access() << " <- ";
stream->Add(os.str().c_str());
value()->PrintTo(stream);
}
void LStoreNamedGeneric::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
stream->Add(".");
stream->Add(String::cast(*name())->ToCString().get());
stream->Add(" <- ");
value()->PrintTo(stream);
}
void LLoadKeyed::PrintDataTo(StringStream* stream) {
elements()->PrintTo(stream);
stream->Add("[");
key()->PrintTo(stream);
if (hydrogen()->IsDehoisted()) {
stream->Add(" + %d]", base_offset());
} else {
stream->Add("]");
}
}
void LStoreKeyed::PrintDataTo(StringStream* stream) {
elements()->PrintTo(stream);
stream->Add("[");
key()->PrintTo(stream);
if (hydrogen()->IsDehoisted()) {
stream->Add(" + %d] <-", base_offset());
} else {
stream->Add("] <- ");
}
if (value() == NULL) {
DCHECK(hydrogen()->IsConstantHoleStore() &&
hydrogen()->value()->representation().IsDouble());
stream->Add("<the hole(nan)>");
} else {
value()->PrintTo(stream);
}
}
void LStoreKeyedGeneric::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
stream->Add("[");
key()->PrintTo(stream);
stream->Add("] <- ");
value()->PrintTo(stream);
}
void LTransitionElementsKind::PrintDataTo(StringStream* stream) {
object()->PrintTo(stream);
stream->Add(" %p -> %p", *original_map(), *transitioned_map());
}
LPlatformChunk* LChunkBuilder::Build() {
DCHECK(is_unused());
chunk_ = new(zone()) LPlatformChunk(info(), graph());
LPhase phase("L_Building chunk", chunk_);
status_ = BUILDING;
// Reserve the first spill slot for the state of dynamic alignment.
if (info()->IsOptimizing()) {
int alignment_state_index = chunk_->GetNextSpillIndex(GENERAL_REGISTERS);
DCHECK_EQ(alignment_state_index, 4);
USE(alignment_state_index);
}
// If compiling for OSR, reserve space for the unoptimized frame,
// which will be subsumed into this frame.
if (graph()->has_osr()) {
for (int i = graph()->osr()->UnoptimizedFrameSlots(); i > 0; i--) {
chunk_->GetNextSpillIndex(GENERAL_REGISTERS);
}
}
const ZoneList<HBasicBlock*>* blocks = graph()->blocks();
for (int i = 0; i < blocks->length(); i++) {
HBasicBlock* next = NULL;
if (i < blocks->length() - 1) next = blocks->at(i + 1);
DoBasicBlock(blocks->at(i), next);
if (is_aborted()) return NULL;
}
status_ = DONE;
return chunk_;
}
LUnallocated* LChunkBuilder::ToUnallocated(Register reg) {
return new (zone()) LUnallocated(LUnallocated::FIXED_REGISTER, reg.code());
}
LUnallocated* LChunkBuilder::ToUnallocated(X87Register reg) {
return new (zone())
LUnallocated(LUnallocated::FIXED_DOUBLE_REGISTER, reg.code());
}
LOperand* LChunkBuilder::UseFixed(HValue* value, Register fixed_register) {
return Use(value, ToUnallocated(fixed_register));
}
LOperand* LChunkBuilder::UseRegister(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER));
}
LOperand* LChunkBuilder::UseRegisterAtStart(HValue* value) {
return Use(value,
new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER,
LUnallocated::USED_AT_START));
}
LOperand* LChunkBuilder::UseTempRegister(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::WRITABLE_REGISTER));
}
LOperand* LChunkBuilder::Use(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::NONE));
}
LOperand* LChunkBuilder::UseAtStart(HValue* value) {
return Use(value, new(zone()) LUnallocated(LUnallocated::NONE,
LUnallocated::USED_AT_START));
}
static inline bool CanBeImmediateConstant(HValue* value) {
return value->IsConstant() && HConstant::cast(value)->NotInNewSpace();
}
LOperand* LChunkBuilder::UseOrConstant(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: Use(value);
}
LOperand* LChunkBuilder::UseOrConstantAtStart(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseAtStart(value);
}
LOperand* LChunkBuilder::UseFixedOrConstant(HValue* value,
Register fixed_register) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseFixed(value, fixed_register);
}
LOperand* LChunkBuilder::UseRegisterOrConstant(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseRegister(value);
}
LOperand* LChunkBuilder::UseRegisterOrConstantAtStart(HValue* value) {
return CanBeImmediateConstant(value)
? chunk_->DefineConstantOperand(HConstant::cast(value))
: UseRegisterAtStart(value);
}
LOperand* LChunkBuilder::UseConstant(HValue* value) {
return chunk_->DefineConstantOperand(HConstant::cast(value));
}
LOperand* LChunkBuilder::UseAny(HValue* value) {
return value->IsConstant()
? chunk_->DefineConstantOperand(HConstant::cast(value))
: Use(value, new(zone()) LUnallocated(LUnallocated::ANY));
}
LOperand* LChunkBuilder::Use(HValue* value, LUnallocated* operand) {
if (value->EmitAtUses()) {
HInstruction* instr = HInstruction::cast(value);
VisitInstruction(instr);
}
operand->set_virtual_register(value->id());
return operand;
}
LInstruction* LChunkBuilder::Define(LTemplateResultInstruction<1>* instr,
LUnallocated* result) {
result->set_virtual_register(current_instruction_->id());
instr->set_result(result);
return instr;
}
LInstruction* LChunkBuilder::DefineAsRegister(
LTemplateResultInstruction<1>* instr) {
return Define(instr,
new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER));
}
LInstruction* LChunkBuilder::DefineAsSpilled(
LTemplateResultInstruction<1>* instr,
int index) {
return Define(instr,
new(zone()) LUnallocated(LUnallocated::FIXED_SLOT, index));
}
LInstruction* LChunkBuilder::DefineSameAsFirst(
LTemplateResultInstruction<1>* instr) {
return Define(instr,
new(zone()) LUnallocated(LUnallocated::SAME_AS_FIRST_INPUT));
}
LInstruction* LChunkBuilder::DefineFixed(LTemplateResultInstruction<1>* instr,
Register reg) {
return Define(instr, ToUnallocated(reg));
}
LInstruction* LChunkBuilder::DefineFixed(LTemplateResultInstruction<1>* instr,
X87Register reg) {
return Define(instr, ToUnallocated(reg));
}
LInstruction* LChunkBuilder::AssignEnvironment(LInstruction* instr) {
HEnvironment* hydrogen_env = current_block_->last_environment();
int argument_index_accumulator = 0;
ZoneList<HValue*> objects_to_materialize(0, zone());
instr->set_environment(CreateEnvironment(hydrogen_env,
&argument_index_accumulator,
&objects_to_materialize));
return instr;
}
LInstruction* LChunkBuilder::MarkAsCall(LInstruction* instr,
HInstruction* hinstr,
CanDeoptimize can_deoptimize) {
info()->MarkAsNonDeferredCalling();
#ifdef DEBUG
instr->VerifyCall();
#endif
instr->MarkAsCall();
instr = AssignPointerMap(instr);
// If instruction does not have side-effects lazy deoptimization
// after the call will try to deoptimize to the point before the call.
// Thus we still need to attach environment to this call even if
// call sequence can not deoptimize eagerly.
bool needs_environment =
(can_deoptimize == CAN_DEOPTIMIZE_EAGERLY) ||
!hinstr->HasObservableSideEffects();
if (needs_environment && !instr->HasEnvironment()) {
instr = AssignEnvironment(instr);
// We can't really figure out if the environment is needed or not.
instr->environment()->set_has_been_used();
}
return instr;
}
LInstruction* LChunkBuilder::AssignPointerMap(LInstruction* instr) {
DCHECK(!instr->HasPointerMap());
instr->set_pointer_map(new(zone()) LPointerMap(zone()));
return instr;
}
LUnallocated* LChunkBuilder::TempRegister() {
LUnallocated* operand =
new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER);
int vreg = allocator_->GetVirtualRegister();
if (!allocator_->AllocationOk()) {
Abort(kOutOfVirtualRegistersWhileTryingToAllocateTempRegister);
vreg = 0;
}
operand->set_virtual_register(vreg);
return operand;
}
LOperand* LChunkBuilder::FixedTemp(Register reg) {
LUnallocated* operand = ToUnallocated(reg);
DCHECK(operand->HasFixedPolicy());
return operand;
}
LInstruction* LChunkBuilder::DoBlockEntry(HBlockEntry* instr) {
return new(zone()) LLabel(instr->block());
}
LInstruction* LChunkBuilder::DoDummyUse(HDummyUse* instr) {
return DefineAsRegister(new(zone()) LDummyUse(UseAny(instr->value())));
}
LInstruction* LChunkBuilder::DoEnvironmentMarker(HEnvironmentMarker* instr) {
UNREACHABLE();
return NULL;
}
LInstruction* LChunkBuilder::DoDeoptimize(HDeoptimize* instr) {
return AssignEnvironment(new(zone()) LDeoptimize);
}
LInstruction* LChunkBuilder::DoShift(Token::Value op,
HBitwiseBinaryOperation* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* left = UseRegisterAtStart(instr->left());
HValue* right_value = instr->right();
LOperand* right = NULL;
int constant_value = 0;
bool does_deopt = false;
if (right_value->IsConstant()) {
HConstant* constant = HConstant::cast(right_value);
right = chunk_->DefineConstantOperand(constant);
constant_value = constant->Integer32Value() & 0x1f;
// Left shifts can deoptimize if we shift by > 0 and the result cannot be
// truncated to smi.
if (instr->representation().IsSmi() && constant_value > 0) {
does_deopt = !instr->CheckUsesForFlag(HValue::kTruncatingToSmi);
}
} else {
right = UseFixed(right_value, ecx);
}
// Shift operations can only deoptimize if we do a logical shift by 0 and
// the result cannot be truncated to int32.
if (op == Token::SHR && constant_value == 0) {
does_deopt = !instr->CheckFlag(HInstruction::kUint32);
}
LInstruction* result =
DefineSameAsFirst(new(zone()) LShiftI(op, left, right, does_deopt));
return does_deopt ? AssignEnvironment(result) : result;
} else {
return DoArithmeticT(op, instr);
}
}
LInstruction* LChunkBuilder::DoArithmeticD(Token::Value op,
HArithmeticBinaryOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->left()->representation().IsDouble());
DCHECK(instr->right()->representation().IsDouble());
if (op == Token::MOD) {
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
LOperand* right = UseRegisterAtStart(instr->BetterRightOperand());
LArithmeticD* result = new(zone()) LArithmeticD(op, left, right);
return MarkAsCall(DefineSameAsFirst(result), instr);
} else {
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
LOperand* right = UseRegisterAtStart(instr->BetterRightOperand());
LArithmeticD* result = new(zone()) LArithmeticD(op, left, right);
return DefineSameAsFirst(result);
}
}
LInstruction* LChunkBuilder::DoArithmeticT(Token::Value op,
HBinaryOperation* instr) {
HValue* left = instr->left();
HValue* right = instr->right();
DCHECK(left->representation().IsTagged());
DCHECK(right->representation().IsTagged());
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left_operand = UseFixed(left, edx);
LOperand* right_operand = UseFixed(right, eax);
LArithmeticT* result =
new(zone()) LArithmeticT(op, context, left_operand, right_operand);
return MarkAsCall(DefineFixed(result, eax), instr);
}
void LChunkBuilder::DoBasicBlock(HBasicBlock* block, HBasicBlock* next_block) {
DCHECK(is_building());
current_block_ = block;
next_block_ = next_block;
if (block->IsStartBlock()) {
block->UpdateEnvironment(graph_->start_environment());
argument_count_ = 0;
} else if (block->predecessors()->length() == 1) {
// We have a single predecessor => copy environment and outgoing
// argument count from the predecessor.
DCHECK(block->phis()->length() == 0);
HBasicBlock* pred = block->predecessors()->at(0);
HEnvironment* last_environment = pred->last_environment();
DCHECK(last_environment != NULL);
// Only copy the environment, if it is later used again.
if (pred->end()->SecondSuccessor() == NULL) {
DCHECK(pred->end()->FirstSuccessor() == block);
} else {
if (pred->end()->FirstSuccessor()->block_id() > block->block_id() ||
pred->end()->SecondSuccessor()->block_id() > block->block_id()) {
last_environment = last_environment->Copy();
}
}
block->UpdateEnvironment(last_environment);
DCHECK(pred->argument_count() >= 0);
argument_count_ = pred->argument_count();
} else {
// We are at a state join => process phis.
HBasicBlock* pred = block->predecessors()->at(0);
// No need to copy the environment, it cannot be used later.
HEnvironment* last_environment = pred->last_environment();
for (int i = 0; i < block->phis()->length(); ++i) {
HPhi* phi = block->phis()->at(i);
if (phi->HasMergedIndex()) {
last_environment->SetValueAt(phi->merged_index(), phi);
}
}
for (int i = 0; i < block->deleted_phis()->length(); ++i) {
if (block->deleted_phis()->at(i) < last_environment->length()) {
last_environment->SetValueAt(block->deleted_phis()->at(i),
graph_->GetConstantUndefined());
}
}
block->UpdateEnvironment(last_environment);
// Pick up the outgoing argument count of one of the predecessors.
argument_count_ = pred->argument_count();
}
HInstruction* current = block->first();
int start = chunk_->instructions()->length();
while (current != NULL && !is_aborted()) {
// Code for constants in registers is generated lazily.
if (!current->EmitAtUses()) {
VisitInstruction(current);
}
current = current->next();
}
int end = chunk_->instructions()->length() - 1;
if (end >= start) {
block->set_first_instruction_index(start);
block->set_last_instruction_index(end);
}
block->set_argument_count(argument_count_);
next_block_ = NULL;
current_block_ = NULL;
}
void LChunkBuilder::VisitInstruction(HInstruction* current) {
HInstruction* old_current = current_instruction_;
current_instruction_ = current;
LInstruction* instr = NULL;
if (current->CanReplaceWithDummyUses()) {
if (current->OperandCount() == 0) {
instr = DefineAsRegister(new(zone()) LDummy());
} else {
DCHECK(!current->OperandAt(0)->IsControlInstruction());
instr = DefineAsRegister(new(zone())
LDummyUse(UseAny(current->OperandAt(0))));
}
for (int i = 1; i < current->OperandCount(); ++i) {
if (current->OperandAt(i)->IsControlInstruction()) continue;
LInstruction* dummy =
new(zone()) LDummyUse(UseAny(current->OperandAt(i)));
dummy->set_hydrogen_value(current);
chunk_->AddInstruction(dummy, current_block_);
}
} else {
HBasicBlock* successor;
if (current->IsControlInstruction() &&
HControlInstruction::cast(current)->KnownSuccessorBlock(&successor) &&
successor != NULL) {
// Always insert a fpu register barrier here when branch is optimized to
// be a direct goto.
// TODO(weiliang): require a better solution.
if (!current->IsGoto()) {
LClobberDoubles* clobber = new (zone()) LClobberDoubles(isolate());
clobber->set_hydrogen_value(current);
chunk_->AddInstruction(clobber, current_block_);
}
instr = new(zone()) LGoto(successor);
} else {
instr = current->CompileToLithium(this);
}
}
argument_count_ += current->argument_delta();
DCHECK(argument_count_ >= 0);
if (instr != NULL) {
AddInstruction(instr, current);
}
current_instruction_ = old_current;
}
void LChunkBuilder::AddInstruction(LInstruction* instr,
HInstruction* hydrogen_val) {
// Associate the hydrogen instruction first, since we may need it for
// the ClobbersRegisters() or ClobbersDoubleRegisters() calls below.
instr->set_hydrogen_value(hydrogen_val);
#if DEBUG
// Make sure that the lithium instruction has either no fixed register
// constraints in temps or the result OR no uses that are only used at
// start. If this invariant doesn't hold, the register allocator can decide
// to insert a split of a range immediately before the instruction due to an
// already allocated register needing to be used for the instruction's fixed
// register constraint. In this case, The register allocator won't see an
// interference between the split child and the use-at-start (it would if
// the it was just a plain use), so it is free to move the split child into
// the same register that is used for the use-at-start.
// See https://code.google.com/p/chromium/issues/detail?id=201590
if (!(instr->ClobbersRegisters() &&
instr->ClobbersDoubleRegisters(isolate()))) {
int fixed = 0;
int used_at_start = 0;
for (UseIterator it(instr); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
if (operand->IsUsedAtStart()) ++used_at_start;
}
if (instr->Output() != NULL) {
if (LUnallocated::cast(instr->Output())->HasFixedPolicy()) ++fixed;
}
for (TempIterator it(instr); !it.Done(); it.Advance()) {
LUnallocated* operand = LUnallocated::cast(it.Current());
if (operand->HasFixedPolicy()) ++fixed;
}
DCHECK(fixed == 0 || used_at_start == 0);
}
#endif
if (FLAG_stress_pointer_maps && !instr->HasPointerMap()) {
instr = AssignPointerMap(instr);
}
if (FLAG_stress_environments && !instr->HasEnvironment()) {
instr = AssignEnvironment(instr);
}
if (instr->IsGoto() &&
(LGoto::cast(instr)->jumps_to_join() || next_block_->is_osr_entry())) {
// TODO(olivf) Since phis of spilled values are joined as registers
// (not in the stack slot), we need to allow the goto gaps to keep one
// x87 register alive. To ensure all other values are still spilled, we
// insert a fpu register barrier right before.
LClobberDoubles* clobber = new(zone()) LClobberDoubles(isolate());
clobber->set_hydrogen_value(hydrogen_val);
chunk_->AddInstruction(clobber, current_block_);
}
chunk_->AddInstruction(instr, current_block_);
if (instr->IsCall() || instr->IsPrologue()) {
HValue* hydrogen_value_for_lazy_bailout = hydrogen_val;
if (hydrogen_val->HasObservableSideEffects()) {
HSimulate* sim = HSimulate::cast(hydrogen_val->next());
sim->ReplayEnvironment(current_block_->last_environment());
hydrogen_value_for_lazy_bailout = sim;
}
LInstruction* bailout = AssignEnvironment(new(zone()) LLazyBailout());
bailout->set_hydrogen_value(hydrogen_value_for_lazy_bailout);
chunk_->AddInstruction(bailout, current_block_);
}
}
LInstruction* LChunkBuilder::DoPrologue(HPrologue* instr) {
return new (zone()) LPrologue();
}
LInstruction* LChunkBuilder::DoGoto(HGoto* instr) {
return new(zone()) LGoto(instr->FirstSuccessor());
}
LInstruction* LChunkBuilder::DoBranch(HBranch* instr) {
HValue* value = instr->value();
Representation r = value->representation();
HType type = value->type();
ToBooleanStub::Types expected = instr->expected_input_types();
if (expected.IsEmpty()) expected = ToBooleanStub::Types::Generic();
bool easy_case = !r.IsTagged() || type.IsBoolean() || type.IsSmi() ||
type.IsJSArray() || type.IsHeapNumber() || type.IsString();
LOperand* temp = !easy_case && expected.NeedsMap() ? TempRegister() : NULL;
LInstruction* branch =
temp != NULL ? new (zone()) LBranch(UseRegister(value), temp)
: new (zone()) LBranch(UseRegisterAtStart(value), temp);
if (!easy_case &&
((!expected.Contains(ToBooleanStub::SMI) && expected.NeedsMap()) ||
!expected.IsGeneric())) {
branch = AssignEnvironment(branch);
}
return branch;
}
LInstruction* LChunkBuilder::DoDebugBreak(HDebugBreak* instr) {
return new(zone()) LDebugBreak();
}
LInstruction* LChunkBuilder::DoCompareMap(HCompareMap* instr) {
DCHECK(instr->value()->representation().IsTagged());
LOperand* value = UseRegisterAtStart(instr->value());
return new(zone()) LCmpMapAndBranch(value);
}
LInstruction* LChunkBuilder::DoArgumentsLength(HArgumentsLength* length) {
info()->MarkAsRequiresFrame();
return DefineAsRegister(new(zone()) LArgumentsLength(Use(length->value())));
}
LInstruction* LChunkBuilder::DoArgumentsElements(HArgumentsElements* elems) {
info()->MarkAsRequiresFrame();
return DefineAsRegister(new(zone()) LArgumentsElements);
}
LInstruction* LChunkBuilder::DoInstanceOf(HInstanceOf* instr) {
LOperand* left =
UseFixed(instr->left(), InstanceOfDescriptor::LeftRegister());
LOperand* right =
UseFixed(instr->right(), InstanceOfDescriptor::RightRegister());
LOperand* context = UseFixed(instr->context(), esi);
LInstanceOf* result = new (zone()) LInstanceOf(context, left, right);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoHasInPrototypeChainAndBranch(
HHasInPrototypeChainAndBranch* instr) {
LOperand* object = UseRegister(instr->object());
LOperand* prototype = UseRegister(instr->prototype());
LOperand* temp = TempRegister();
LHasInPrototypeChainAndBranch* result =
new (zone()) LHasInPrototypeChainAndBranch(object, prototype, temp);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoWrapReceiver(HWrapReceiver* instr) {
LOperand* receiver = UseRegister(instr->receiver());
LOperand* function = UseRegister(instr->function());
LOperand* temp = TempRegister();
LWrapReceiver* result =
new(zone()) LWrapReceiver(receiver, function, temp);
return AssignEnvironment(DefineSameAsFirst(result));
}
LInstruction* LChunkBuilder::DoApplyArguments(HApplyArguments* instr) {
LOperand* function = UseFixed(instr->function(), edi);
LOperand* receiver = UseFixed(instr->receiver(), eax);
LOperand* length = UseFixed(instr->length(), ebx);
LOperand* elements = UseFixed(instr->elements(), ecx);
LApplyArguments* result = new(zone()) LApplyArguments(function,
receiver,
length,
elements);
return MarkAsCall(DefineFixed(result, eax), instr, CAN_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoPushArguments(HPushArguments* instr) {
int argc = instr->OperandCount();
for (int i = 0; i < argc; ++i) {
LOperand* argument = UseAny(instr->argument(i));
AddInstruction(new(zone()) LPushArgument(argument), instr);
}
return NULL;
}
LInstruction* LChunkBuilder::DoStoreCodeEntry(
HStoreCodeEntry* store_code_entry) {
LOperand* function = UseRegister(store_code_entry->function());
LOperand* code_object = UseTempRegister(store_code_entry->code_object());
return new(zone()) LStoreCodeEntry(function, code_object);
}
LInstruction* LChunkBuilder::DoInnerAllocatedObject(
HInnerAllocatedObject* instr) {
LOperand* base_object = UseRegisterAtStart(instr->base_object());
LOperand* offset = UseRegisterOrConstantAtStart(instr->offset());
return DefineAsRegister(
new(zone()) LInnerAllocatedObject(base_object, offset));
}
LInstruction* LChunkBuilder::DoThisFunction(HThisFunction* instr) {
return instr->HasNoUses()
? NULL
: DefineAsRegister(new(zone()) LThisFunction);
}
LInstruction* LChunkBuilder::DoContext(HContext* instr) {
if (instr->HasNoUses()) return NULL;
if (info()->IsStub()) {
return DefineFixed(new(zone()) LContext, esi);
}
return DefineAsRegister(new(zone()) LContext);
}
LInstruction* LChunkBuilder::DoDeclareGlobals(HDeclareGlobals* instr) {
LOperand* context = UseFixed(instr->context(), esi);
return MarkAsCall(new(zone()) LDeclareGlobals(context), instr);
}
LInstruction* LChunkBuilder::DoCallJSFunction(
HCallJSFunction* instr) {
LOperand* function = UseFixed(instr->function(), edi);
LCallJSFunction* result = new(zone()) LCallJSFunction(function);
return MarkAsCall(DefineFixed(result, eax), instr, CANNOT_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoCallWithDescriptor(
HCallWithDescriptor* instr) {
CallInterfaceDescriptor descriptor = instr->descriptor();
LOperand* target = UseRegisterOrConstantAtStart(instr->target());
ZoneList<LOperand*> ops(instr->OperandCount(), zone());
// Target
ops.Add(target, zone());
// Context
LOperand* op = UseFixed(instr->OperandAt(1), esi);
ops.Add(op, zone());
// Other register parameters
for (int i = LCallWithDescriptor::kImplicitRegisterParameterCount;
i < instr->OperandCount(); i++) {
op =
UseFixed(instr->OperandAt(i),
descriptor.GetRegisterParameter(
i - LCallWithDescriptor::kImplicitRegisterParameterCount));
ops.Add(op, zone());
}
LCallWithDescriptor* result = new(zone()) LCallWithDescriptor(
descriptor, ops, zone());
return MarkAsCall(DefineFixed(result, eax), instr, CANNOT_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoInvokeFunction(HInvokeFunction* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* function = UseFixed(instr->function(), edi);
LInvokeFunction* result = new(zone()) LInvokeFunction(context, function);
return MarkAsCall(DefineFixed(result, eax), instr, CANNOT_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoUnaryMathOperation(HUnaryMathOperation* instr) {
switch (instr->op()) {
case kMathFloor: return DoMathFloor(instr);
case kMathRound: return DoMathRound(instr);
case kMathFround: return DoMathFround(instr);
case kMathAbs: return DoMathAbs(instr);
case kMathLog: return DoMathLog(instr);
case kMathExp: return DoMathExp(instr);
case kMathSqrt: return DoMathSqrt(instr);
case kMathPowHalf: return DoMathPowHalf(instr);
case kMathClz32: return DoMathClz32(instr);
default:
UNREACHABLE();
return NULL;
}
}
LInstruction* LChunkBuilder::DoMathFloor(HUnaryMathOperation* instr) {
LOperand* input = UseRegisterAtStart(instr->value());
LMathFloor* result = new(zone()) LMathFloor(input);
return AssignEnvironment(DefineAsRegister(result));
}
LInstruction* LChunkBuilder::DoMathRound(HUnaryMathOperation* instr) {
LOperand* input = UseRegisterAtStart(instr->value());
LInstruction* result = DefineAsRegister(new (zone()) LMathRound(input));
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoMathFround(HUnaryMathOperation* instr) {
LOperand* input = UseRegister(instr->value());
LMathFround* result = new (zone()) LMathFround(input);
return DefineSameAsFirst(result);
}
LInstruction* LChunkBuilder::DoMathAbs(HUnaryMathOperation* instr) {
LOperand* context = UseAny(instr->context()); // Deferred use.
LOperand* input = UseRegisterAtStart(instr->value());
LInstruction* result =
DefineSameAsFirst(new(zone()) LMathAbs(context, input));
Representation r = instr->value()->representation();
if (!r.IsDouble() && !r.IsSmiOrInteger32()) result = AssignPointerMap(result);
if (!r.IsDouble()) result = AssignEnvironment(result);
return result;
}
LInstruction* LChunkBuilder::DoMathLog(HUnaryMathOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->value()->representation().IsDouble());
LOperand* input = UseRegisterAtStart(instr->value());
return MarkAsCall(DefineSameAsFirst(new(zone()) LMathLog(input)), instr);
}
LInstruction* LChunkBuilder::DoMathClz32(HUnaryMathOperation* instr) {
LOperand* input = UseRegisterAtStart(instr->value());
LMathClz32* result = new(zone()) LMathClz32(input);
return DefineAsRegister(result);
}
LInstruction* LChunkBuilder::DoMathExp(HUnaryMathOperation* instr) {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->value()->representation().IsDouble());
LOperand* value = UseRegisterAtStart(instr->value());
LOperand* temp1 = FixedTemp(ecx);
LOperand* temp2 = FixedTemp(edx);
LMathExp* result = new(zone()) LMathExp(value, temp1, temp2);
return MarkAsCall(DefineSameAsFirst(result), instr);
}
LInstruction* LChunkBuilder::DoMathSqrt(HUnaryMathOperation* instr) {
LOperand* input = UseRegisterAtStart(instr->value());
LOperand* temp1 = FixedTemp(ecx);
LOperand* temp2 = FixedTemp(edx);
LMathSqrt* result = new(zone()) LMathSqrt(input, temp1, temp2);
return MarkAsCall(DefineSameAsFirst(result), instr);
}
LInstruction* LChunkBuilder::DoMathPowHalf(HUnaryMathOperation* instr) {
LOperand* input = UseRegisterAtStart(instr->value());
LMathPowHalf* result = new (zone()) LMathPowHalf(input);
return DefineSameAsFirst(result);
}
LInstruction* LChunkBuilder::DoCallNewArray(HCallNewArray* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* constructor = UseFixed(instr->constructor(), edi);
LCallNewArray* result = new(zone()) LCallNewArray(context, constructor);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoCallFunction(HCallFunction* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* function = UseFixed(instr->function(), edi);
LOperand* slot = NULL;
LOperand* vector = NULL;
if (instr->HasVectorAndSlot()) {
slot = FixedTemp(edx);
vector = FixedTemp(ebx);
}
LCallFunction* call =
new (zone()) LCallFunction(context, function, slot, vector);
return MarkAsCall(DefineFixed(call, eax), instr);
}
LInstruction* LChunkBuilder::DoCallRuntime(HCallRuntime* instr) {
LOperand* context = UseFixed(instr->context(), esi);
return MarkAsCall(DefineFixed(new(zone()) LCallRuntime(context), eax), instr);
}
LInstruction* LChunkBuilder::DoRor(HRor* instr) {
return DoShift(Token::ROR, instr);
}
LInstruction* LChunkBuilder::DoShr(HShr* instr) {
return DoShift(Token::SHR, instr);
}
LInstruction* LChunkBuilder::DoSar(HSar* instr) {
return DoShift(Token::SAR, instr);
}
LInstruction* LChunkBuilder::DoShl(HShl* instr) {
return DoShift(Token::SHL, instr);
}
LInstruction* LChunkBuilder::DoBitwise(HBitwise* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
DCHECK(instr->CheckFlag(HValue::kTruncatingToInt32));
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
LOperand* right = UseOrConstantAtStart(instr->BetterRightOperand());
return DefineSameAsFirst(new(zone()) LBitI(left, right));
} else {
return DoArithmeticT(instr->op(), instr);
}
}
LInstruction* LChunkBuilder::DoDivByPowerOf2I(HDiv* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LInstruction* result = DefineAsRegister(new(zone()) LDivByPowerOf2I(
dividend, divisor));
if ((instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) ||
(instr->CheckFlag(HValue::kCanOverflow) && divisor == -1) ||
(!instr->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
divisor != 1 && divisor != -1)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoDivByConstI(HDiv* instr) {
DCHECK(instr->representation().IsInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LOperand* temp1 = FixedTemp(eax);
LOperand* temp2 = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LDivByConstI(
dividend, divisor, temp1, temp2), edx);
if (divisor == 0 ||
(instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) ||
!instr->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoDivI(HDiv* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseFixed(instr->left(), eax);
LOperand* divisor = UseRegister(instr->right());
LOperand* temp = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LDivI(
dividend, divisor, temp), eax);
if (instr->CheckFlag(HValue::kCanBeDivByZero) ||
instr->CheckFlag(HValue::kBailoutOnMinusZero) ||
instr->CheckFlag(HValue::kCanOverflow) ||
!instr->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoDiv(HDiv* instr) {
if (instr->representation().IsSmiOrInteger32()) {
if (instr->RightIsPowerOf2()) {
return DoDivByPowerOf2I(instr);
} else if (instr->right()->IsConstant()) {
return DoDivByConstI(instr);
} else {
return DoDivI(instr);
}
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::DIV, instr);
} else {
return DoArithmeticT(Token::DIV, instr);
}
}
LInstruction* LChunkBuilder::DoFlooringDivByPowerOf2I(HMathFloorOfDiv* instr) {
LOperand* dividend = UseRegisterAtStart(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LInstruction* result = DefineSameAsFirst(new(zone()) LFlooringDivByPowerOf2I(
dividend, divisor));
if ((instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) ||
(instr->CheckFlag(HValue::kLeftCanBeMinInt) && divisor == -1)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoFlooringDivByConstI(HMathFloorOfDiv* instr) {
DCHECK(instr->representation().IsInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LOperand* temp1 = FixedTemp(eax);
LOperand* temp2 = FixedTemp(edx);
LOperand* temp3 =
((divisor > 0 && !instr->CheckFlag(HValue::kLeftCanBeNegative)) ||
(divisor < 0 && !instr->CheckFlag(HValue::kLeftCanBePositive))) ?
NULL : TempRegister();
LInstruction* result =
DefineFixed(new(zone()) LFlooringDivByConstI(dividend,
divisor,
temp1,
temp2,
temp3),
edx);
if (divisor == 0 ||
(instr->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoFlooringDivI(HMathFloorOfDiv* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseFixed(instr->left(), eax);
LOperand* divisor = UseRegister(instr->right());
LOperand* temp = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LFlooringDivI(
dividend, divisor, temp), eax);
if (instr->CheckFlag(HValue::kCanBeDivByZero) ||
instr->CheckFlag(HValue::kBailoutOnMinusZero) ||
instr->CheckFlag(HValue::kCanOverflow)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoMathFloorOfDiv(HMathFloorOfDiv* instr) {
if (instr->RightIsPowerOf2()) {
return DoFlooringDivByPowerOf2I(instr);
} else if (instr->right()->IsConstant()) {
return DoFlooringDivByConstI(instr);
} else {
return DoFlooringDivI(instr);
}
}
LInstruction* LChunkBuilder::DoModByPowerOf2I(HMod* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegisterAtStart(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LInstruction* result = DefineSameAsFirst(new(zone()) LModByPowerOf2I(
dividend, divisor));
if (instr->CheckFlag(HValue::kLeftCanBeNegative) &&
instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoModByConstI(HMod* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseRegister(instr->left());
int32_t divisor = instr->right()->GetInteger32Constant();
LOperand* temp1 = FixedTemp(eax);
LOperand* temp2 = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LModByConstI(
dividend, divisor, temp1, temp2), eax);
if (divisor == 0 || instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoModI(HMod* instr) {
DCHECK(instr->representation().IsSmiOrInteger32());
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* dividend = UseFixed(instr->left(), eax);
LOperand* divisor = UseRegister(instr->right());
LOperand* temp = FixedTemp(edx);
LInstruction* result = DefineFixed(new(zone()) LModI(
dividend, divisor, temp), edx);
if (instr->CheckFlag(HValue::kCanBeDivByZero) ||
instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoMod(HMod* instr) {
if (instr->representation().IsSmiOrInteger32()) {
if (instr->RightIsPowerOf2()) {
return DoModByPowerOf2I(instr);
} else if (instr->right()->IsConstant()) {
return DoModByConstI(instr);
} else {
return DoModI(instr);
}
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::MOD, instr);
} else {
return DoArithmeticT(Token::MOD, instr);
}
}
LInstruction* LChunkBuilder::DoMul(HMul* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
HValue* h_right = instr->BetterRightOperand();
LOperand* right = UseOrConstant(h_right);
LOperand* temp = NULL;
if (instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
temp = TempRegister();
}
LMulI* mul = new(zone()) LMulI(left, right, temp);
int constant_value =
h_right->IsConstant() ? HConstant::cast(h_right)->Integer32Value() : 0;
// |needs_environment| must mirror the cases where LCodeGen::DoMulI calls
// |DeoptimizeIf|.
bool needs_environment =
instr->CheckFlag(HValue::kCanOverflow) ||
(instr->CheckFlag(HValue::kBailoutOnMinusZero) &&
(!right->IsConstantOperand() || constant_value <= 0));
if (needs_environment) {
AssignEnvironment(mul);
}
return DefineSameAsFirst(mul);
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::MUL, instr);
} else {
return DoArithmeticT(Token::MUL, instr);
}
}
LInstruction* LChunkBuilder::DoSub(HSub* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
LOperand* left = UseRegisterAtStart(instr->left());
LOperand* right = UseOrConstantAtStart(instr->right());
LSubI* sub = new(zone()) LSubI(left, right);
LInstruction* result = DefineSameAsFirst(sub);
if (instr->CheckFlag(HValue::kCanOverflow)) {
result = AssignEnvironment(result);
}
return result;
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::SUB, instr);
} else {
return DoArithmeticT(Token::SUB, instr);
}
}
LInstruction* LChunkBuilder::DoAdd(HAdd* instr) {
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
// Check to see if it would be advantageous to use an lea instruction rather
// than an add. This is the case when no overflow check is needed and there
// are multiple uses of the add's inputs, so using a 3-register add will
// preserve all input values for later uses.
bool use_lea = LAddI::UseLea(instr);
LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
HValue* right_candidate = instr->BetterRightOperand();
LOperand* right = use_lea
? UseRegisterOrConstantAtStart(right_candidate)
: UseOrConstantAtStart(right_candidate);
LAddI* add = new(zone()) LAddI(left, right);
bool can_overflow = instr->CheckFlag(HValue::kCanOverflow);
LInstruction* result = use_lea
? DefineAsRegister(add)
: DefineSameAsFirst(add);
if (can_overflow) {
result = AssignEnvironment(result);
}
return result;
} else if (instr->representation().IsDouble()) {
return DoArithmeticD(Token::ADD, instr);
} else if (instr->representation().IsExternal()) {
DCHECK(instr->IsConsistentExternalRepresentation());
DCHECK(!instr->CheckFlag(HValue::kCanOverflow));
bool use_lea = LAddI::UseLea(instr);
LOperand* left = UseRegisterAtStart(instr->left());
HValue* right_candidate = instr->right();
LOperand* right = use_lea
? UseRegisterOrConstantAtStart(right_candidate)
: UseOrConstantAtStart(right_candidate);
LAddI* add = new(zone()) LAddI(left, right);
LInstruction* result = use_lea
? DefineAsRegister(add)
: DefineSameAsFirst(add);
return result;
} else {
return DoArithmeticT(Token::ADD, instr);
}
}
LInstruction* LChunkBuilder::DoMathMinMax(HMathMinMax* instr) {
LOperand* left = NULL;
LOperand* right = NULL;
LOperand* scratch = TempRegister();
if (instr->representation().IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(instr->representation()));
DCHECK(instr->right()->representation().Equals(instr->representation()));
left = UseRegisterAtStart(instr->BetterLeftOperand());
right = UseOrConstantAtStart(instr->BetterRightOperand());
} else {
DCHECK(instr->representation().IsDouble());
DCHECK(instr->left()->representation().IsDouble());
DCHECK(instr->right()->representation().IsDouble());
left = UseRegisterAtStart(instr->left());
right = UseRegisterAtStart(instr->right());
}
LMathMinMax* minmax = new (zone()) LMathMinMax(left, right, scratch);
return DefineSameAsFirst(minmax);
}
LInstruction* LChunkBuilder::DoPower(HPower* instr) {
// Unlike ia32, we don't have a MathPowStub and directly call c function.
DCHECK(instr->representation().IsDouble());
DCHECK(instr->left()->representation().IsDouble());
LOperand* left = UseRegisterAtStart(instr->left());
LOperand* right = UseRegisterAtStart(instr->right());
LPower* result = new (zone()) LPower(left, right);
return MarkAsCall(DefineSameAsFirst(result), instr);
}
LInstruction* LChunkBuilder::DoCompareGeneric(HCompareGeneric* instr) {
DCHECK(instr->left()->representation().IsSmiOrTagged());
DCHECK(instr->right()->representation().IsSmiOrTagged());
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left = UseFixed(instr->left(), edx);
LOperand* right = UseFixed(instr->right(), eax);
LCmpT* result = new(zone()) LCmpT(context, left, right);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoCompareNumericAndBranch(
HCompareNumericAndBranch* instr) {
Representation r = instr->representation();
if (r.IsSmiOrInteger32()) {
DCHECK(instr->left()->representation().Equals(r));
DCHECK(instr->right()->representation().Equals(r));
LOperand* left = UseRegisterOrConstantAtStart(instr->left());
LOperand* right = UseOrConstantAtStart(instr->right());
return new(zone()) LCompareNumericAndBranch(left, right);
} else {
DCHECK(r.IsDouble());
DCHECK(instr->left()->representation().IsDouble());
DCHECK(instr->right()->representation().IsDouble());
LOperand* left;
LOperand* right;
if (CanBeImmediateConstant(instr->left()) &&
CanBeImmediateConstant(instr->right())) {
// The code generator requires either both inputs to be constant
// operands, or neither.
left = UseConstant(instr->left());
right = UseConstant(instr->right());
} else {
left = UseRegisterAtStart(instr->left());
right = UseRegisterAtStart(instr->right());
}
return new(zone()) LCompareNumericAndBranch(left, right);
}
}
LInstruction* LChunkBuilder::DoCompareObjectEqAndBranch(
HCompareObjectEqAndBranch* instr) {
LOperand* left = UseRegisterAtStart(instr->left());
LOperand* right = UseOrConstantAtStart(instr->right());
return new(zone()) LCmpObjectEqAndBranch(left, right);
}
LInstruction* LChunkBuilder::DoCompareHoleAndBranch(
HCompareHoleAndBranch* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
return new (zone()) LCmpHoleAndBranch(value);
}
LInstruction* LChunkBuilder::DoIsStringAndBranch(HIsStringAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
LOperand* temp = TempRegister();
return new(zone()) LIsStringAndBranch(UseRegister(instr->value()), temp);
}
LInstruction* LChunkBuilder::DoIsSmiAndBranch(HIsSmiAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LIsSmiAndBranch(Use(instr->value()));
}
LInstruction* LChunkBuilder::DoIsUndetectableAndBranch(
HIsUndetectableAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LIsUndetectableAndBranch(
UseRegisterAtStart(instr->value()), TempRegister());
}
LInstruction* LChunkBuilder::DoStringCompareAndBranch(
HStringCompareAndBranch* instr) {
DCHECK(instr->left()->representation().IsTagged());
DCHECK(instr->right()->representation().IsTagged());
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left = UseFixed(instr->left(), edx);
LOperand* right = UseFixed(instr->right(), eax);
LStringCompareAndBranch* result = new(zone())
LStringCompareAndBranch(context, left, right);
return MarkAsCall(result, instr);
}
LInstruction* LChunkBuilder::DoHasInstanceTypeAndBranch(
HHasInstanceTypeAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LHasInstanceTypeAndBranch(
UseRegisterAtStart(instr->value()),
TempRegister());
}
LInstruction* LChunkBuilder::DoGetCachedArrayIndex(
HGetCachedArrayIndex* instr) {
DCHECK(instr->value()->representation().IsTagged());
LOperand* value = UseRegisterAtStart(instr->value());
return DefineAsRegister(new(zone()) LGetCachedArrayIndex(value));
}
LInstruction* LChunkBuilder::DoHasCachedArrayIndexAndBranch(
HHasCachedArrayIndexAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LHasCachedArrayIndexAndBranch(
UseRegisterAtStart(instr->value()));
}
LInstruction* LChunkBuilder::DoClassOfTestAndBranch(
HClassOfTestAndBranch* instr) {
DCHECK(instr->value()->representation().IsTagged());
return new(zone()) LClassOfTestAndBranch(UseRegister(instr->value()),
TempRegister(),
TempRegister());
}
LInstruction* LChunkBuilder::DoSeqStringGetChar(HSeqStringGetChar* instr) {
LOperand* string = UseRegisterAtStart(instr->string());
LOperand* index = UseRegisterOrConstantAtStart(instr->index());
return DefineAsRegister(new(zone()) LSeqStringGetChar(string, index));
}
LOperand* LChunkBuilder::GetSeqStringSetCharOperand(HSeqStringSetChar* instr) {
if (instr->encoding() == String::ONE_BYTE_ENCODING) {
if (FLAG_debug_code) {
return UseFixed(instr->value(), eax);
} else {
return UseFixedOrConstant(instr->value(), eax);
}
} else {
if (FLAG_debug_code) {
return UseRegisterAtStart(instr->value());
} else {
return UseRegisterOrConstantAtStart(instr->value());
}
}
}
LInstruction* LChunkBuilder::DoSeqStringSetChar(HSeqStringSetChar* instr) {
LOperand* string = UseRegisterAtStart(instr->string());
LOperand* index = FLAG_debug_code
? UseRegisterAtStart(instr->index())
: UseRegisterOrConstantAtStart(instr->index());
LOperand* value = GetSeqStringSetCharOperand(instr);
LOperand* context = FLAG_debug_code ? UseFixed(instr->context(), esi) : NULL;
LInstruction* result = new(zone()) LSeqStringSetChar(context, string,
index, value);
if (FLAG_debug_code) {
result = MarkAsCall(result, instr);
}
return result;
}
LInstruction* LChunkBuilder::DoBoundsCheck(HBoundsCheck* instr) {
if (!FLAG_debug_code && instr->skip_check()) return NULL;
LOperand* index = UseRegisterOrConstantAtStart(instr->index());
LOperand* length = !index->IsConstantOperand()
? UseOrConstantAtStart(instr->length())
: UseAtStart(instr->length());
LInstruction* result = new(zone()) LBoundsCheck(index, length);
if (!FLAG_debug_code || !instr->skip_check()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoBoundsCheckBaseIndexInformation(
HBoundsCheckBaseIndexInformation* instr) {
UNREACHABLE();
return NULL;
}
LInstruction* LChunkBuilder::DoAbnormalExit(HAbnormalExit* instr) {
// The control instruction marking the end of a block that completed
// abruptly (e.g., threw an exception). There is nothing specific to do.
return NULL;
}
LInstruction* LChunkBuilder::DoUseConst(HUseConst* instr) {
return NULL;
}
LInstruction* LChunkBuilder::DoForceRepresentation(HForceRepresentation* bad) {
// All HForceRepresentation instructions should be eliminated in the
// representation change phase of Hydrogen.
UNREACHABLE();
return NULL;
}
LInstruction* LChunkBuilder::DoChange(HChange* instr) {
Representation from = instr->from();
Representation to = instr->to();
HValue* val = instr->value();
if (from.IsSmi()) {
if (to.IsTagged()) {
LOperand* value = UseRegister(val);
return DefineSameAsFirst(new(zone()) LDummyUse(value));
}
from = Representation::Tagged();
}
if (from.IsTagged()) {
if (to.IsDouble()) {
LOperand* value = UseRegister(val);
LOperand* temp = TempRegister();
LInstruction* result =
DefineAsRegister(new(zone()) LNumberUntagD(value, temp));
if (!val->representation().IsSmi()) result = AssignEnvironment(result);
return result;
} else if (to.IsSmi()) {
LOperand* value = UseRegister(val);
if (val->type().IsSmi()) {
return DefineSameAsFirst(new(zone()) LDummyUse(value));
}
return AssignEnvironment(DefineSameAsFirst(new(zone()) LCheckSmi(value)));
} else {
DCHECK(to.IsInteger32());
if (val->type().IsSmi() || val->representation().IsSmi()) {
LOperand* value = UseRegister(val);
return DefineSameAsFirst(new(zone()) LSmiUntag(value, false));
} else {
LOperand* value = UseRegister(val);
LInstruction* result = DefineSameAsFirst(new(zone()) LTaggedToI(value));
if (!val->representation().IsSmi()) result = AssignEnvironment(result);
return result;
}
}
} else if (from.IsDouble()) {
if (to.IsTagged()) {
info()->MarkAsDeferredCalling();
LOperand* value = UseRegisterAtStart(val);
LOperand* temp = FLAG_inline_new ? TempRegister() : NULL;
LUnallocated* result_temp = TempRegister();
LNumberTagD* result = new(zone()) LNumberTagD(value, temp);
return AssignPointerMap(Define(result, result_temp));
} else if (to.IsSmi()) {
LOperand* value = UseRegister(val);
return AssignEnvironment(
DefineAsRegister(new(zone()) LDoubleToSmi(value)));
} else {
DCHECK(to.IsInteger32());
bool truncating = instr->CanTruncateToInt32();
LOperand* value = UseRegister(val);
LInstruction* result = DefineAsRegister(new(zone()) LDoubleToI(value));
if (!truncating) result = AssignEnvironment(result);
return result;
}
} else if (from.IsInteger32()) {
info()->MarkAsDeferredCalling();
if (to.IsTagged()) {
if (!instr->CheckFlag(HValue::kCanOverflow)) {
LOperand* value = UseRegister(val);
return DefineSameAsFirst(new(zone()) LSmiTag(value));
} else if (val->CheckFlag(HInstruction::kUint32)) {
LOperand* value = UseRegister(val);
LOperand* temp = TempRegister();
LNumberTagU* result = new(zone()) LNumberTagU(value, temp);
return AssignPointerMap(DefineSameAsFirst(result));
} else {
LOperand* value = UseRegister(val);
LOperand* temp = TempRegister();
LNumberTagI* result = new(zone()) LNumberTagI(value, temp);
return AssignPointerMap(DefineSameAsFirst(result));
}
} else if (to.IsSmi()) {
LOperand* value = UseRegister(val);
LInstruction* result = DefineSameAsFirst(new(zone()) LSmiTag(value));
if (instr->CheckFlag(HValue::kCanOverflow)) {
result = AssignEnvironment(result);
}
return result;
} else {
DCHECK(to.IsDouble());
if (val->CheckFlag(HInstruction::kUint32)) {
return DefineAsRegister(new(zone()) LUint32ToDouble(UseRegister(val)));
} else {
return DefineAsRegister(new(zone()) LInteger32ToDouble(Use(val)));
}
}
}
UNREACHABLE();
return NULL;
}
LInstruction* LChunkBuilder::DoCheckHeapObject(HCheckHeapObject* instr) {
LOperand* value = UseAtStart(instr->value());
LInstruction* result = new(zone()) LCheckNonSmi(value);
if (!instr->value()->type().IsHeapObject()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoCheckSmi(HCheckSmi* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
return AssignEnvironment(new(zone()) LCheckSmi(value));
}
LInstruction* LChunkBuilder::DoCheckArrayBufferNotNeutered(
HCheckArrayBufferNotNeutered* instr) {
LOperand* view = UseRegisterAtStart(instr->value());
LOperand* scratch = TempRegister();
LCheckArrayBufferNotNeutered* result =
new (zone()) LCheckArrayBufferNotNeutered(view, scratch);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoCheckInstanceType(HCheckInstanceType* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
LOperand* temp = TempRegister();
LCheckInstanceType* result = new(zone()) LCheckInstanceType(value, temp);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoCheckValue(HCheckValue* instr) {
// If the object is in new space, we'll emit a global cell compare and so
// want the value in a register. If the object gets promoted before we
// emit code, we will still get the register but will do an immediate
// compare instead of the cell compare. This is safe.
LOperand* value = instr->object_in_new_space()
? UseRegisterAtStart(instr->value()) : UseAtStart(instr->value());
return AssignEnvironment(new(zone()) LCheckValue(value));
}
LInstruction* LChunkBuilder::DoCheckMaps(HCheckMaps* instr) {
if (instr->IsStabilityCheck()) return new(zone()) LCheckMaps;
LOperand* value = UseRegisterAtStart(instr->value());
LInstruction* result = AssignEnvironment(new(zone()) LCheckMaps(value));
if (instr->HasMigrationTarget()) {
info()->MarkAsDeferredCalling();
result = AssignPointerMap(result);
}
return result;
}
LInstruction* LChunkBuilder::DoClampToUint8(HClampToUint8* instr) {
HValue* value = instr->value();
Representation input_rep = value->representation();
if (input_rep.IsDouble()) {
LOperand* reg = UseRegister(value);
return DefineFixed(new (zone()) LClampDToUint8(reg), eax);
} else if (input_rep.IsInteger32()) {
LOperand* reg = UseFixed(value, eax);
return DefineFixed(new(zone()) LClampIToUint8(reg), eax);
} else {
DCHECK(input_rep.IsSmiOrTagged());
LOperand* value = UseRegister(instr->value());
LClampTToUint8NoSSE2* res =
new(zone()) LClampTToUint8NoSSE2(value, TempRegister(),
TempRegister(), TempRegister());
return AssignEnvironment(DefineFixed(res, ecx));
}
}
LInstruction* LChunkBuilder::DoDoubleBits(HDoubleBits* instr) {
HValue* value = instr->value();
DCHECK(value->representation().IsDouble());
return DefineAsRegister(new(zone()) LDoubleBits(UseRegister(value)));
}
LInstruction* LChunkBuilder::DoConstructDouble(HConstructDouble* instr) {
LOperand* lo = UseRegister(instr->lo());
LOperand* hi = UseRegister(instr->hi());
return DefineAsRegister(new(zone()) LConstructDouble(hi, lo));
}
LInstruction* LChunkBuilder::DoReturn(HReturn* instr) {
LOperand* context = info()->IsStub() ? UseFixed(instr->context(), esi) : NULL;
LOperand* parameter_count = UseRegisterOrConstant(instr->parameter_count());
return new(zone()) LReturn(
UseFixed(instr->value(), eax), context, parameter_count);
}
LInstruction* LChunkBuilder::DoConstant(HConstant* instr) {
Representation r = instr->representation();
if (r.IsSmi()) {
return DefineAsRegister(new(zone()) LConstantS);
} else if (r.IsInteger32()) {
return DefineAsRegister(new(zone()) LConstantI);
} else if (r.IsDouble()) {
return DefineAsRegister(new (zone()) LConstantD);
} else if (r.IsExternal()) {
return DefineAsRegister(new(zone()) LConstantE);
} else if (r.IsTagged()) {
return DefineAsRegister(new(zone()) LConstantT);
} else {
UNREACHABLE();
return NULL;
}
}
LInstruction* LChunkBuilder::DoLoadGlobalGeneric(HLoadGlobalGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* global_object =
UseFixed(instr->global_object(), LoadDescriptor::ReceiverRegister());
LOperand* vector = NULL;
if (instr->HasVectorAndSlot()) {
vector = FixedTemp(LoadWithVectorDescriptor::VectorRegister());
}
LLoadGlobalGeneric* result =
new(zone()) LLoadGlobalGeneric(context, global_object, vector);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoLoadContextSlot(HLoadContextSlot* instr) {
LOperand* context = UseRegisterAtStart(instr->value());
LInstruction* result =
DefineAsRegister(new(zone()) LLoadContextSlot(context));
if (instr->RequiresHoleCheck() && instr->DeoptimizesOnHole()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoStoreContextSlot(HStoreContextSlot* instr) {
LOperand* value;
LOperand* temp;
LOperand* context = UseRegister(instr->context());
if (instr->NeedsWriteBarrier()) {
value = UseTempRegister(instr->value());
temp = TempRegister();
} else {
value = UseRegister(instr->value());
temp = NULL;
}
LInstruction* result = new(zone()) LStoreContextSlot(context, value, temp);
if (instr->RequiresHoleCheck() && instr->DeoptimizesOnHole()) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoLoadNamedField(HLoadNamedField* instr) {
LOperand* obj = (instr->access().IsExternalMemory() &&
instr->access().offset() == 0)
? UseRegisterOrConstantAtStart(instr->object())
: UseRegisterAtStart(instr->object());
return DefineAsRegister(new(zone()) LLoadNamedField(obj));
}
LInstruction* LChunkBuilder::DoLoadNamedGeneric(HLoadNamedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), LoadDescriptor::ReceiverRegister());
LOperand* vector = NULL;
if (instr->HasVectorAndSlot()) {
vector = FixedTemp(LoadWithVectorDescriptor::VectorRegister());
}
LLoadNamedGeneric* result = new(zone()) LLoadNamedGeneric(
context, object, vector);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoLoadFunctionPrototype(
HLoadFunctionPrototype* instr) {
return AssignEnvironment(DefineAsRegister(
new(zone()) LLoadFunctionPrototype(UseRegister(instr->function()),
TempRegister())));
}
LInstruction* LChunkBuilder::DoLoadRoot(HLoadRoot* instr) {
return DefineAsRegister(new(zone()) LLoadRoot);
}
LInstruction* LChunkBuilder::DoLoadKeyed(HLoadKeyed* instr) {
DCHECK(instr->key()->representation().IsSmiOrInteger32());
ElementsKind elements_kind = instr->elements_kind();
bool clobbers_key = ExternalArrayOpRequiresTemp(
instr->key()->representation(), elements_kind);
LOperand* key = clobbers_key
? UseTempRegister(instr->key())
: UseRegisterOrConstantAtStart(instr->key());
LInstruction* result = NULL;
if (!instr->is_fixed_typed_array()) {
LOperand* obj = UseRegisterAtStart(instr->elements());
result = DefineAsRegister(new (zone()) LLoadKeyed(obj, key, nullptr));
} else {
DCHECK(
(instr->representation().IsInteger32() &&
!(IsDoubleOrFloatElementsKind(instr->elements_kind()))) ||
(instr->representation().IsDouble() &&
(IsDoubleOrFloatElementsKind(instr->elements_kind()))));
LOperand* backing_store = UseRegister(instr->elements());
LOperand* backing_store_owner = UseAny(instr->backing_store_owner());
result = DefineAsRegister(
new (zone()) LLoadKeyed(backing_store, key, backing_store_owner));
}
bool needs_environment;
if (instr->is_fixed_typed_array()) {
// see LCodeGen::DoLoadKeyedExternalArray
needs_environment = elements_kind == UINT32_ELEMENTS &&
!instr->CheckFlag(HInstruction::kUint32);
} else {
// see LCodeGen::DoLoadKeyedFixedDoubleArray and
// LCodeGen::DoLoadKeyedFixedArray
needs_environment =
instr->RequiresHoleCheck() ||
(instr->hole_mode() == CONVERT_HOLE_TO_UNDEFINED && info()->IsStub());
}
if (needs_environment) {
result = AssignEnvironment(result);
}
return result;
}
LInstruction* LChunkBuilder::DoLoadKeyedGeneric(HLoadKeyedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), LoadDescriptor::ReceiverRegister());
LOperand* key = UseFixed(instr->key(), LoadDescriptor::NameRegister());
LOperand* vector = NULL;
if (instr->HasVectorAndSlot()) {
vector = FixedTemp(LoadWithVectorDescriptor::VectorRegister());
}
LLoadKeyedGeneric* result =
new(zone()) LLoadKeyedGeneric(context, object, key, vector);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LOperand* LChunkBuilder::GetStoreKeyedValueOperand(HStoreKeyed* instr) {
ElementsKind elements_kind = instr->elements_kind();
// Determine if we need a byte register in this case for the value.
bool val_is_fixed_register =
elements_kind == UINT8_ELEMENTS ||
elements_kind == INT8_ELEMENTS ||
elements_kind == UINT8_CLAMPED_ELEMENTS;
if (val_is_fixed_register) {
return UseFixed(instr->value(), eax);
}
if (IsDoubleOrFloatElementsKind(elements_kind)) {
return UseRegisterAtStart(instr->value());
}
return UseRegister(instr->value());
}
LInstruction* LChunkBuilder::DoStoreKeyed(HStoreKeyed* instr) {
if (!instr->is_fixed_typed_array()) {
DCHECK(instr->elements()->representation().IsTagged());
DCHECK(instr->key()->representation().IsInteger32() ||
instr->key()->representation().IsSmi());
if (instr->value()->representation().IsDouble()) {
LOperand* object = UseRegisterAtStart(instr->elements());
// For storing double hole, no fp register required.
LOperand* val = instr->IsConstantHoleStore()
? NULL
: UseRegisterAtStart(instr->value());
LOperand* key = UseRegisterOrConstantAtStart(instr->key());
return new (zone()) LStoreKeyed(object, key, val, nullptr);
} else {
DCHECK(instr->value()->representation().IsSmiOrTagged());
bool needs_write_barrier = instr->NeedsWriteBarrier();
LOperand* obj = UseRegister(instr->elements());
LOperand* val;
LOperand* key;
if (needs_write_barrier) {
val = UseTempRegister(instr->value());
key = UseTempRegister(instr->key());
} else {
val = UseRegisterOrConstantAtStart(instr->value());
key = UseRegisterOrConstantAtStart(instr->key());
}
return new (zone()) LStoreKeyed(obj, key, val, nullptr);
}
}
ElementsKind elements_kind = instr->elements_kind();
DCHECK(
(instr->value()->representation().IsInteger32() &&
!IsDoubleOrFloatElementsKind(elements_kind)) ||
(instr->value()->representation().IsDouble() &&
IsDoubleOrFloatElementsKind(elements_kind)));
DCHECK(instr->elements()->representation().IsExternal());
LOperand* backing_store = UseRegister(instr->elements());
LOperand* val = GetStoreKeyedValueOperand(instr);
bool clobbers_key = ExternalArrayOpRequiresTemp(
instr->key()->representation(), elements_kind);
LOperand* key = clobbers_key
? UseTempRegister(instr->key())
: UseRegisterOrConstantAtStart(instr->key());
LOperand* backing_store_owner = UseAny(instr->backing_store_owner());
return new (zone()) LStoreKeyed(backing_store, key, val, backing_store_owner);
}
LInstruction* LChunkBuilder::DoStoreKeyedGeneric(HStoreKeyedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), StoreDescriptor::ReceiverRegister());
LOperand* key = UseFixed(instr->key(), StoreDescriptor::NameRegister());
LOperand* value = UseFixed(instr->value(), StoreDescriptor::ValueRegister());
DCHECK(instr->object()->representation().IsTagged());
DCHECK(instr->key()->representation().IsTagged());
DCHECK(instr->value()->representation().IsTagged());
LOperand* slot = NULL;
LOperand* vector = NULL;
if (instr->HasVectorAndSlot()) {
slot = FixedTemp(VectorStoreICDescriptor::SlotRegister());
vector = FixedTemp(VectorStoreICDescriptor::VectorRegister());
}
LStoreKeyedGeneric* result = new (zone())
LStoreKeyedGeneric(context, object, key, value, slot, vector);
return MarkAsCall(result, instr);
}
LInstruction* LChunkBuilder::DoTransitionElementsKind(
HTransitionElementsKind* instr) {
if (IsSimpleMapChangeTransition(instr->from_kind(), instr->to_kind())) {
LOperand* object = UseRegister(instr->object());
LOperand* new_map_reg = TempRegister();
LOperand* temp_reg = TempRegister();
LTransitionElementsKind* result =
new(zone()) LTransitionElementsKind(object, NULL,
new_map_reg, temp_reg);
return result;
} else {
LOperand* object = UseFixed(instr->object(), eax);
LOperand* context = UseFixed(instr->context(), esi);
LTransitionElementsKind* result =
new(zone()) LTransitionElementsKind(object, context, NULL, NULL);
return MarkAsCall(result, instr);
}
}
LInstruction* LChunkBuilder::DoTrapAllocationMemento(
HTrapAllocationMemento* instr) {
LOperand* object = UseRegister(instr->object());
LOperand* temp = TempRegister();
LTrapAllocationMemento* result =
new(zone()) LTrapAllocationMemento(object, temp);
return AssignEnvironment(result);
}
LInstruction* LChunkBuilder::DoMaybeGrowElements(HMaybeGrowElements* instr) {
info()->MarkAsDeferredCalling();
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object = Use(instr->object());
LOperand* elements = Use(instr->elements());
LOperand* key = UseRegisterOrConstant(instr->key());
LOperand* current_capacity = UseRegisterOrConstant(instr->current_capacity());
LMaybeGrowElements* result = new (zone())
LMaybeGrowElements(context, object, elements, key, current_capacity);
DefineFixed(result, eax);
return AssignPointerMap(AssignEnvironment(result));
}
LInstruction* LChunkBuilder::DoStoreNamedField(HStoreNamedField* instr) {
bool is_in_object = instr->access().IsInobject();
bool is_external_location = instr->access().IsExternalMemory() &&
instr->access().offset() == 0;
bool needs_write_barrier = instr->NeedsWriteBarrier();
bool needs_write_barrier_for_map = instr->has_transition() &&
instr->NeedsWriteBarrierForMap();
LOperand* obj;
if (needs_write_barrier) {
obj = is_in_object
? UseRegister(instr->object())
: UseTempRegister(instr->object());
} else if (is_external_location) {
DCHECK(!is_in_object);
DCHECK(!needs_write_barrier);
DCHECK(!needs_write_barrier_for_map);
obj = UseRegisterOrConstant(instr->object());
} else {
obj = needs_write_barrier_for_map
? UseRegister(instr->object())
: UseRegisterAtStart(instr->object());
}
bool can_be_constant = instr->value()->IsConstant() &&
HConstant::cast(instr->value())->NotInNewSpace() &&
!instr->field_representation().IsDouble();
LOperand* val;
if (instr->field_representation().IsInteger8() ||
instr->field_representation().IsUInteger8()) {
// mov_b requires a byte register (i.e. any of eax, ebx, ecx, edx).
// Just force the value to be in eax and we're safe here.
val = UseFixed(instr->value(), eax);
} else if (needs_write_barrier) {
val = UseTempRegister(instr->value());
} else if (can_be_constant) {
val = UseRegisterOrConstant(instr->value());
} else if (instr->field_representation().IsDouble()) {
val = UseRegisterAtStart(instr->value());
} else {
val = UseRegister(instr->value());
}
// We only need a scratch register if we have a write barrier or we
// have a store into the properties array (not in-object-property).
LOperand* temp = (!is_in_object || needs_write_barrier ||
needs_write_barrier_for_map) ? TempRegister() : NULL;
// We need a temporary register for write barrier of the map field.
LOperand* temp_map = needs_write_barrier_for_map ? TempRegister() : NULL;
return new(zone()) LStoreNamedField(obj, val, temp, temp_map);
}
LInstruction* LChunkBuilder::DoStoreNamedGeneric(HStoreNamedGeneric* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object =
UseFixed(instr->object(), StoreDescriptor::ReceiverRegister());
LOperand* value = UseFixed(instr->value(), StoreDescriptor::ValueRegister());
LOperand* slot = NULL;
LOperand* vector = NULL;
if (instr->HasVectorAndSlot()) {
slot = FixedTemp(VectorStoreICDescriptor::SlotRegister());
vector = FixedTemp(VectorStoreICDescriptor::VectorRegister());
}
LStoreNamedGeneric* result =
new (zone()) LStoreNamedGeneric(context, object, value, slot, vector);
return MarkAsCall(result, instr);
}
LInstruction* LChunkBuilder::DoStringAdd(HStringAdd* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* left = UseFixed(instr->left(), edx);
LOperand* right = UseFixed(instr->right(), eax);
LStringAdd* string_add = new(zone()) LStringAdd(context, left, right);
return MarkAsCall(DefineFixed(string_add, eax), instr);
}
LInstruction* LChunkBuilder::DoStringCharCodeAt(HStringCharCodeAt* instr) {
LOperand* string = UseTempRegister(instr->string());
LOperand* index = UseTempRegister(instr->index());
LOperand* context = UseAny(instr->context());
LStringCharCodeAt* result =
new(zone()) LStringCharCodeAt(context, string, index);
return AssignPointerMap(DefineAsRegister(result));
}
LInstruction* LChunkBuilder::DoStringCharFromCode(HStringCharFromCode* instr) {
LOperand* char_code = UseRegister(instr->value());
LOperand* context = UseAny(instr->context());
LStringCharFromCode* result =
new(zone()) LStringCharFromCode(context, char_code);
return AssignPointerMap(DefineAsRegister(result));
}
LInstruction* LChunkBuilder::DoAllocate(HAllocate* instr) {
info()->MarkAsDeferredCalling();
LOperand* context = UseAny(instr->context());
LOperand* size = instr->size()->IsConstant()
? UseConstant(instr->size())
: UseTempRegister(instr->size());
LOperand* temp = TempRegister();
LAllocate* result = new(zone()) LAllocate(context, size, temp);
return AssignPointerMap(DefineAsRegister(result));
}
LInstruction* LChunkBuilder::DoOsrEntry(HOsrEntry* instr) {
DCHECK(argument_count_ == 0);
allocator_->MarkAsOsrEntry();
current_block_->last_environment()->set_ast_id(instr->ast_id());
return AssignEnvironment(new(zone()) LOsrEntry);
}
LInstruction* LChunkBuilder::DoParameter(HParameter* instr) {
LParameter* result = new(zone()) LParameter;
if (instr->kind() == HParameter::STACK_PARAMETER) {
int spill_index = chunk()->GetParameterStackSlot(instr->index());
return DefineAsSpilled(result, spill_index);
} else {
DCHECK(info()->IsStub());
CallInterfaceDescriptor descriptor = graph()->descriptor();
int index = static_cast<int>(instr->index());
Register reg = descriptor.GetRegisterParameter(index);
return DefineFixed(result, reg);
}
}
LInstruction* LChunkBuilder::DoUnknownOSRValue(HUnknownOSRValue* instr) {
// Use an index that corresponds to the location in the unoptimized frame,
// which the optimized frame will subsume.
int env_index = instr->index();
int spill_index = 0;
if (instr->environment()->is_parameter_index(env_index)) {
spill_index = chunk()->GetParameterStackSlot(env_index);
} else {
spill_index = env_index - instr->environment()->first_local_index();
if (spill_index > LUnallocated::kMaxFixedSlotIndex) {
Retry(kNotEnoughSpillSlotsForOsr);
spill_index = 0;
}
if (spill_index == 0) {
// The dynamic frame alignment state overwrites the first local.
// The first local is saved at the end of the unoptimized frame.
spill_index = graph()->osr()->UnoptimizedFrameSlots();
}
spill_index += StandardFrameConstants::kFixedSlotCount;
}
return DefineAsSpilled(new(zone()) LUnknownOSRValue, spill_index);
}
LInstruction* LChunkBuilder::DoArgumentsObject(HArgumentsObject* instr) {
// There are no real uses of the arguments object.
// arguments.length and element access are supported directly on
// stack arguments, and any real arguments object use causes a bailout.
// So this value is never used.
return NULL;
}
LInstruction* LChunkBuilder::DoCapturedObject(HCapturedObject* instr) {
instr->ReplayEnvironment(current_block_->last_environment());
// There are no real uses of a captured object.
return NULL;
}
LInstruction* LChunkBuilder::DoAccessArgumentsAt(HAccessArgumentsAt* instr) {
info()->MarkAsRequiresFrame();
LOperand* args = UseRegister(instr->arguments());
LOperand* length;
LOperand* index;
if (instr->length()->IsConstant() && instr->index()->IsConstant()) {
length = UseRegisterOrConstant(instr->length());
index = UseOrConstant(instr->index());
} else {
length = UseTempRegister(instr->length());
index = Use(instr->index());
}
return DefineAsRegister(new(zone()) LAccessArgumentsAt(args, length, index));
}
LInstruction* LChunkBuilder::DoToFastProperties(HToFastProperties* instr) {
LOperand* object = UseFixed(instr->value(), eax);
LToFastProperties* result = new(zone()) LToFastProperties(object);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoTypeof(HTypeof* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* value = UseFixed(instr->value(), ebx);
LTypeof* result = new(zone()) LTypeof(context, value);
return MarkAsCall(DefineFixed(result, eax), instr);
}
LInstruction* LChunkBuilder::DoTypeofIsAndBranch(HTypeofIsAndBranch* instr) {
return new(zone()) LTypeofIsAndBranch(UseTempRegister(instr->value()));
}
LInstruction* LChunkBuilder::DoSimulate(HSimulate* instr) {
instr->ReplayEnvironment(current_block_->last_environment());
return NULL;
}
LInstruction* LChunkBuilder::DoStackCheck(HStackCheck* instr) {
info()->MarkAsDeferredCalling();
if (instr->is_function_entry()) {
LOperand* context = UseFixed(instr->context(), esi);
return MarkAsCall(new(zone()) LStackCheck(context), instr);
} else {
DCHECK(instr->is_backwards_branch());
LOperand* context = UseAny(instr->context());
return AssignEnvironment(
AssignPointerMap(new(zone()) LStackCheck(context)));
}
}
LInstruction* LChunkBuilder::DoEnterInlined(HEnterInlined* instr) {
HEnvironment* outer = current_block_->last_environment();
outer->set_ast_id(instr->ReturnId());
HConstant* undefined = graph()->GetConstantUndefined();
HEnvironment* inner = outer->CopyForInlining(instr->closure(),
instr->arguments_count(),
instr->function(),
undefined,
instr->inlining_kind());
// Only replay binding of arguments object if it wasn't removed from graph.
if (instr->arguments_var() != NULL && instr->arguments_object()->IsLinked()) {
inner->Bind(instr->arguments_var(), instr->arguments_object());
}
inner->BindContext(instr->closure_context());
inner->set_entry(instr);
current_block_->UpdateEnvironment(inner);
chunk_->AddInlinedFunction(instr->shared());
return NULL;
}
LInstruction* LChunkBuilder::DoLeaveInlined(HLeaveInlined* instr) {
LInstruction* pop = NULL;
HEnvironment* env = current_block_->last_environment();
if (env->entry()->arguments_pushed()) {
int argument_count = env->arguments_environment()->parameter_count();
pop = new(zone()) LDrop(argument_count);
DCHECK(instr->argument_delta() == -argument_count);
}
HEnvironment* outer = current_block_->last_environment()->
DiscardInlined(false);
current_block_->UpdateEnvironment(outer);
return pop;
}
LInstruction* LChunkBuilder::DoForInPrepareMap(HForInPrepareMap* instr) {
LOperand* context = UseFixed(instr->context(), esi);
LOperand* object = UseFixed(instr->enumerable(), eax);
LForInPrepareMap* result = new(zone()) LForInPrepareMap(context, object);
return MarkAsCall(DefineFixed(result, eax), instr, CAN_DEOPTIMIZE_EAGERLY);
}
LInstruction* LChunkBuilder::DoForInCacheArray(HForInCacheArray* instr) {
LOperand* map = UseRegister(instr->map());
return AssignEnvironment(DefineAsRegister(
new(zone()) LForInCacheArray(map)));
}
LInstruction* LChunkBuilder::DoCheckMapValue(HCheckMapValue* instr) {
LOperand* value = UseRegisterAtStart(instr->value());
LOperand* map = UseRegisterAtStart(instr->map());
return AssignEnvironment(new(zone()) LCheckMapValue(value, map));
}
LInstruction* LChunkBuilder::DoLoadFieldByIndex(HLoadFieldByIndex* instr) {
LOperand* object = UseRegister(instr->object());
LOperand* index = UseTempRegister(instr->index());
LLoadFieldByIndex* load = new(zone()) LLoadFieldByIndex(object, index);
LInstruction* result = DefineSameAsFirst(load);
return AssignPointerMap(result);
}
LInstruction* LChunkBuilder::DoStoreFrameContext(HStoreFrameContext* instr) {
LOperand* context = UseRegisterAtStart(instr->context());
return new(zone()) LStoreFrameContext(context);
}
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_X87
| {
"content_hash": "7919ced67f5d7ed4480637f188977e4b",
"timestamp": "",
"source": "github",
"line_count": 2664,
"max_line_length": 80,
"avg_line_length": 33.87537537537538,
"alnum_prop": 0.6794246708922477,
"repo_name": "baslr/ArangoDB",
"id": "f770509076cc137a83b62bf6b9b9839df3d74642",
"size": "90635",
"binary": false,
"copies": "2",
"ref": "refs/heads/3.1-silent",
"path": "3rdParty/V8/V8-5.0.71.39/src/crankshaft/x87/lithium-x87.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "391227"
},
{
"name": "Awk",
"bytes": "4272"
},
{
"name": "Batchfile",
"bytes": "62892"
},
{
"name": "C",
"bytes": "7932707"
},
{
"name": "C#",
"bytes": "96430"
},
{
"name": "C++",
"bytes": "284363933"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "681903"
},
{
"name": "CSS",
"bytes": "1036656"
},
{
"name": "CWeb",
"bytes": "174166"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "259402"
},
{
"name": "Emacs Lisp",
"bytes": "14637"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Groovy",
"bytes": "131"
},
{
"name": "HTML",
"bytes": "2318016"
},
{
"name": "Java",
"bytes": "2325801"
},
{
"name": "JavaScript",
"bytes": "67878359"
},
{
"name": "LLVM",
"bytes": "24129"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "M4",
"bytes": "600550"
},
{
"name": "Makefile",
"bytes": "509612"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "28404"
},
{
"name": "Objective-C",
"bytes": "19321"
},
{
"name": "Objective-C++",
"bytes": "2503"
},
{
"name": "PHP",
"bytes": "98503"
},
{
"name": "Pascal",
"bytes": "145688"
},
{
"name": "Perl",
"bytes": "720157"
},
{
"name": "Perl 6",
"bytes": "9918"
},
{
"name": "Python",
"bytes": "5859911"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "R",
"bytes": "5123"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Roff",
"bytes": "1010686"
},
{
"name": "Ruby",
"bytes": "922159"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "511077"
},
{
"name": "Swift",
"bytes": "116"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "Vim script",
"bytes": "4075"
},
{
"name": "Visual Basic",
"bytes": "11568"
},
{
"name": "XSLT",
"bytes": "551977"
},
{
"name": "Yacc",
"bytes": "53005"
}
],
"symlink_target": ""
} |
import os
import socket
import SocketServer
import sys
import threading
import time
from subprocess import Popen, PIPE
PLUGIN_PATH = "/etc/munin/plugins"
def parse_args():
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-p", "--pluginpath", dest="plugin_path",
help="path to plugins", default=PLUGIN_PATH)
(options, args) = parser.parse_args()
return options, args
def execute_plugin(path, cmd=""):
args = [path]
if cmd:
args.append(cmd)
p = Popen(args, stdout=PIPE)
output = p.communicate()[0]
return output
if os.name == 'posix':
def become_daemon(our_home_dir='.', out_log='/dev/null',
err_log='/dev/null', umask=022):
"Robustly turn into a UNIX daemon, running in our_home_dir."
# First fork
try:
if os.fork() > 0:
sys.exit(0) # kill off parent
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
os.setsid()
os.chdir(our_home_dir)
os.umask(umask)
# Second fork
try:
if os.fork() > 0:
os._exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
os._exit(1)
si = open('/dev/null', 'r')
so = open(out_log, 'a+', 0)
se = open(err_log, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# Set custom file descriptors so that they get proper buffering.
sys.stdout, sys.stderr = so, se
else:
def become_daemon(our_home_dir='.', out_log=None, err_log=None, umask=022):
"""
If we're not running under a POSIX system, just simulate the daemon
mode by doing redirections and directory changing.
"""
os.chdir(our_home_dir)
os.umask(umask)
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
if err_log:
sys.stderr = open(err_log, 'a', 0)
else:
sys.stderr = NullDevice()
if out_log:
sys.stdout = open(out_log, 'a', 0)
else:
sys.stdout = NullDevice()
class NullDevice:
"A writeable object that writes to nowhere -- like /dev/null."
def write(self, s):
pass
class MuninRequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
# self.rfile is a file-like object created by the handler;
# we can now use e.g. readline() instead of raw recv() calls
plugins = []
for x in os.listdir(self.server.options.plugin_path):
if x.startswith('.'):
continue
fullpath = os.path.join(self.server.options.plugin_path, x)
if not os.path.isfile(fullpath):
continue
plugins.append(x)
node_name = socket.gethostname().split('.')[0]
self.wfile.write("# munin node at %s\n" % node_name)
while True:
line = self.rfile.readline()
if not line:
break
line = line.strip()
cmd = line.split(' ', 1)
plugin = (len(cmd) > 1) and cmd[1] or None
if cmd[0] == "list":
self.wfile.write("%s\n" % " ".join(plugins))
elif cmd[0] == "nodes":
self.wfile.write("nodes\n%s\n.\n" % (node_name))
elif cmd[0] == "version":
self.wfile.write("munins node on chatter1 version: 1.2.6\n")
elif cmd[0] in ("fetch", "config"):
if plugin not in plugins:
self.wfile.write("# Unknown service\n.\n")
continue
c = (cmd[0] == "config") and "config" or ""
out = execute_plugin(os.path.join(self.server.options.plugin_path, plugin), c)
self.wfile.write(out)
if out and out[-1] != "\n":
self.wfile.write("\n")
self.wfile.write(".\n")
elif cmd[0] == "quit":
break
else:
self.wfile.write("# Unknown command. Try list, nodes, config, fetch, version or quit\n")
class MuninServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 4949
if sys.version_info[:3] >= (2, 6, 0):
server = MuninServer((HOST, PORT), MuninRequestHandler, bind_and_activate=False)
server.allow_reuse_address = True
server.server_bind()
server.server_activate()
else:
server = MuninServer((HOST, PORT), MuninRequestHandler)
ip, port = server.server_address
options, args = parse_args()
options.plugin_path = os.path.abspath(options.plugin_path)
server.options = options
become_daemon()
server.serve_forever()
| {
"content_hash": "a05165fd4d136057fedf84deba29a83c",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 104,
"avg_line_length": 34.12837837837838,
"alnum_prop": 0.5394971292813304,
"repo_name": "Mitali-Sodhi/CodeLingo",
"id": "34efcd2fa0d9b2972a31242888b341e72c732be2",
"size": "5074",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "Dataset/python/munin-node.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9681846"
},
{
"name": "C#",
"bytes": "1741915"
},
{
"name": "C++",
"bytes": "5686017"
},
{
"name": "HTML",
"bytes": "11812193"
},
{
"name": "Java",
"bytes": "11198971"
},
{
"name": "JavaScript",
"bytes": "21693468"
},
{
"name": "M",
"bytes": "61627"
},
{
"name": "Objective-C",
"bytes": "4085820"
},
{
"name": "Perl",
"bytes": "193472"
},
{
"name": "Perl6",
"bytes": "176248"
},
{
"name": "Python",
"bytes": "10296284"
},
{
"name": "Ruby",
"bytes": "1050136"
}
],
"symlink_target": ""
} |
@font-face {
font-family: 'Keraleeyam';
src: url('Keraleeyam/Keraleeyam.eot');
src: url('Keraleeyam/Keraleeyam.eot?#iefix') format('embedded-opentype'),
url('Keraleeyam/Keraleeyam.woff2') format('woff2'),
url('Keraleeyam/Keraleeyam.woff') format('woff'),
url('Keraleeyam/Keraleeyam.ttf') format('truetype');
font-weight: bold;
font-style: normal;
}
| {
"content_hash": "e66b4ad688196799d1d235c21a4ca272",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 74,
"avg_line_length": 36,
"alnum_prop": 0.7166666666666667,
"repo_name": "PeterDaveHello/jsdelivr",
"id": "4ea08e8884de716d96deca7f5f44fb125f70be8e",
"size": "360",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "files/smc-webfonts/0.0.5/fonts/keraleeyam.css",
"mode": "33188",
"license": "mit",
"language": [],
"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_51) on Wed Mar 12 16:32:44 BRT 2014 -->
<title>C-Index</title>
<meta name="date" content="2014-03-12">
<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="C-Index";
}
//-->
</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>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li><a href="index-3.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-2.html" target="_top">Frames</a></li>
<li><a href="index-2.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="contentContainer"><a href="index-1.html">B</a> <a href="index-2.html">C</a> <a href="index-3.html">G</a> <a href="index-4.html">J</a> <a href="index-5.html">P</a> <a href="index-6.html">R</a> <a href="index-7.html">S</a> <a href="index-8.html">T</a> <a name="_C_">
<!-- -->
</a>
<h2 class="title">C</h2>
<dl>
<dt><span class="strong"><a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html#convertPyObject(org.python.core.PyObject, java.lang.Class, java.lang.String, java.lang.String)">convertPyObject(PyObject, Class<?>, String, String)</a></span> - Method in class br.com.dgimenes.jythonDynamicCoersion.<a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html" title="class in br.com.dgimenes.jythonDynamicCoersion">JythonObjectManager</a></dt>
<dd>
<div class="block">Converts (coerse) Python object to an object of type specified in
returnInterfaceType parameter.</div>
</dd>
<dt><span class="strong"><a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html#convertPyObjectUsingAuxClass(org.python.core.PyObject, java.lang.Class, java.lang.String, java.lang.String, java.lang.String, java.lang.String)">convertPyObjectUsingAuxClass(PyObject, Class<?>, String, String, String, String)</a></span> - Method in class br.com.dgimenes.jythonDynamicCoersion.<a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html" title="class in br.com.dgimenes.jythonDynamicCoersion">JythonObjectManager</a></dt>
<dd>
<div class="block">Converts (coerse) Python object to an object of type specified in
returnInterfaceType parameter.</div>
</dd>
<dt><span class="strong"><a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html#createObject(java.lang.Class, java.lang.String, java.lang.String)">createObject(Class<?>, String, String)</a></span> - Method in class br.com.dgimenes.jythonDynamicCoersion.<a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html" title="class in br.com.dgimenes.jythonDynamicCoersion">JythonObjectManager</a></dt>
<dd>
<div class="block">Creates Python object and apply coersion to return an object of type
specified in returnInterfaceType parameter.</div>
</dd>
<dt><span class="strong"><a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html#createObjectUsingAuxClass(java.lang.Class, java.lang.String, java.lang.String, java.lang.String, java.lang.String)">createObjectUsingAuxClass(Class<?>, String, String, String, String)</a></span> - Method in class br.com.dgimenes.jythonDynamicCoersion.<a href="../br/com/dgimenes/jythonDynamicCoersion/JythonObjectManager.html" title="class in br.com.dgimenes.jythonDynamicCoersion">JythonObjectManager</a></dt>
<dd>
<div class="block">Creates Python object and apply coersion to return an object of type
specified in returnInterfaceType parameter.</div>
</dd>
</dl>
<a href="index-1.html">B</a> <a href="index-2.html">C</a> <a href="index-3.html">G</a> <a href="index-4.html">J</a> <a href="index-5.html">P</a> <a href="index-6.html">R</a> <a href="index-7.html">S</a> <a href="index-8.html">T</a> </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>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li><a href="index-3.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-2.html" target="_top">Frames</a></li>
<li><a href="index-2.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": "fa9e46e6ed9cf0f92897ce9d2fad15f2",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 558,
"avg_line_length": 47.45652173913044,
"alnum_prop": 0.6811726981218507,
"repo_name": "danielgimenes/jythonEasierCoercion",
"id": "5a84d6c9619ca69ab238c3047bd879188a5f4f22",
"size": "6549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/index-files/index-2.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "Java",
"bytes": "20841"
}
],
"symlink_target": ""
} |
require 'chef/knife/cloud/oraclepaas_service'
class Chef
class Knife
class Cloud
class SoaService < OraclepaasService
def connection
@connection ||= begin
connection = Fog::OracleCloud::SOA.new(
oracle_domain: @identity_domain,
oracle_username: @username,
oracle_password: @password,
oracle_region: @region)
rescue Excon::Errors::Unauthorized => e
error_message = "Connection failure, please check your username and password."
ui.fatal(error_message)
raise CloudExceptions::ServiceConnectionError, "#{e.message}. #{error_message}"
rescue Excon::Errors::SocketError => e
error_message = "Connection failure, please check your authentication URL."
ui.fatal(error_message)
raise CloudExceptions::ServiceConnectionError, "#{e.message}. #{error_message}"
end
end
def delete_server(options = {})
begin
server = get_server(options[:service_name])
server.dba_name = options[:dba_name]
server.dba_password = options[:dba_password]
server.force_delete = options[:force_delete]
server.skip_backup = options[:skip_backup]
msg_pair("Instance Name", server.service_name)
puts "\n"
ui.confirm("Do you really want to delete this server")
# delete the server
server.destroy
rescue NoMethodError
error_message = "Could not locate instance '#{options[:service_name]}'."
ui.error(error_message)
raise CloudExceptions::ServerDeleteError, error_message
rescue Excon::Errors::BadRequest => e
handle_excon_exception(CloudExceptions::ServerDeleteError, e)
end
end
end
end
end
end
| {
"content_hash": "674b4ecca7d461bd4f76e48fd5c85384",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 107,
"avg_line_length": 41.411764705882355,
"alnum_prop": 0.537405303030303,
"repo_name": "Joelith/knife-oraclepaas-0.1.0",
"id": "f92f4fde66d5acedef2b0612451d6a6711565470",
"size": "2144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/chef/knife/cloud/oraclepaas_soa_service.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "86980"
}
],
"symlink_target": ""
} |
package com.evernym.sdk.vcx.credential;
import com.evernym.sdk.vcx.ErrorCode;
import com.evernym.sdk.vcx.VcxException;
/**
* Created by abdussami on 13/06/18.
*/
public class InvalidCredentialDefHandle extends VcxException
{
private static final long serialVersionUID = 3294831240096535507L;
private final static String message = "VCX Exception";
public InvalidCredentialDefHandle()
{
super(message, ErrorCode.INVALID_CREDENTIAL_DEF_HANDLE.value());
}
} | {
"content_hash": "080556cb678d1c1384df303941129f0e",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 72,
"avg_line_length": 24.4,
"alnum_prop": 0.7479508196721312,
"repo_name": "Artemkaaas/indy-sdk",
"id": "a7a9d151b8b05b94530bb7a4f72ccacfadbddc0c",
"size": "488",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vcx/wrappers/java/src/main/java/com/evernym/sdk/vcx/credential/InvalidCredentialDefHandle.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "304593"
},
{
"name": "C#",
"bytes": "851667"
},
{
"name": "C++",
"bytes": "113048"
},
{
"name": "CSS",
"bytes": "137079"
},
{
"name": "Dockerfile",
"bytes": "23662"
},
{
"name": "Groovy",
"bytes": "91076"
},
{
"name": "HTML",
"bytes": "897750"
},
{
"name": "Java",
"bytes": "857349"
},
{
"name": "JavaScript",
"bytes": "187603"
},
{
"name": "Makefile",
"bytes": "328"
},
{
"name": "Objective-C",
"bytes": "567071"
},
{
"name": "Objective-C++",
"bytes": "687924"
},
{
"name": "Perl",
"bytes": "8271"
},
{
"name": "Python",
"bytes": "693656"
},
{
"name": "Ruby",
"bytes": "80312"
},
{
"name": "Rust",
"bytes": "5242907"
},
{
"name": "Shell",
"bytes": "248295"
},
{
"name": "Swift",
"bytes": "1114"
},
{
"name": "TypeScript",
"bytes": "201111"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a7ad112763da2f2505403ca202058f38",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "86ab1582be0e2ab958e1599ec32b9d2d8639fd66",
"size": "207",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Rhodophyta/Florideophyceae/Ceramiales/Delesseriaceae/Augophyllum/Augophyllum marginifructum/ Syn. Myriogramme marginifructa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package de.spricom.dessert.resolve;
public interface ClassCollector {
void addClass(ClassEntry cfe);
void addPackage(ClassPackage pckg);
}
| {
"content_hash": "e528571653712202a6b2bfe33a1ec105",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 39,
"avg_line_length": 18.75,
"alnum_prop": 0.76,
"repo_name": "hajo70/dessert",
"id": "8a998564f4db98b2449a3009639813f7a8a908de",
"size": "839",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/de/spricom/dessert/resolve/ClassCollector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "195501"
}
],
"symlink_target": ""
} |
.. _bugs:
Known Issues and Bugs
=====================
This section lists known issues and bugs and gives some information on how to
submit bug reports.
"Content is Unreadable. Open and Repair"
----------------------------------------
Very, very occasionally you may see an Excel warning when opening an XlsxWriter
file like:
Excel could not open file.xlsx because some content is unreadable. Do you
want to open and repair this workbook.
This ominous sounding message is Excel's default warning for any validation
error in the XML used for the components of the XLSX file.
If you encounter an issue like this you should open an issue on GitHub with a
program to replicate the issue (see below) or send one of the failing output
files to the :ref:`author`.
"Exception caught in workbook destructor. Explicit close() may be required"
---------------------------------------------------------------------------
The following exception, or similar, can occur if the :func:`close` method
isn't used at the end of the program::
Exception Exception: Exception('Exception caught in workbook destructor.
Explicit close() may be required for workbook.',)
in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbookobject
at 0x103297d50>>
Note, it is possible that this exception will also be raised as part of
another exception that occurs during workbook destruction. In either case
ensure that there is an explicit ``workbook.close()`` in the program.
Formulas displayed as ``#NAME?`` until edited
---------------------------------------------
Excel 2010 and 2013 added functions which weren't defined in the original file
specification. These functions are referred to as *future* functions. Examples
of these functions are ``ACOT``, ``CHISQ.DIST.RT`` , ``CONFIDENCE.NORM``,
``STDEV.P``, ``STDEV.S`` and ``WORKDAY.INTL``. The full list is given in the
`MS XLSX extensions documentation on future functions <http://msdn.microsoft.com/en-us/library/dd907480%28v=office.12%29.aspx>`_.
When written using ``write_formula()`` these functions need to be fully
qualified with the ``_xlfn.`` prefix as they are shown in the MS XLSX
documentation link above. For example::
worksheet.write_formula('A1', '=_xlfn.STDEV.S(B1:B10)')
Formula results displaying as zero in non-Excel applications
------------------------------------------------------------
Due to wide range of possible formulas and interdependencies between them
XlsxWriter doesn't, and realistically cannot, calculate the result of a
formula when it is written to an XLSX file. Instead, it stores the value 0 as
the formula result. It then sets a global flag in the XLSX file to say that
all formulas and functions should be recalculated when the file is opened.
This is the method recommended in the Excel documentation and in general it
works fine with spreadsheet applications. However, applications that don't
have a facility to calculate formulas, such as Excel Viewer, or several mobile
applications, will only display the 0 results.
If required, it is also possible to specify the calculated result of the
formula using the optional ``value`` parameter in :func:`write_formula()`::
worksheet.write_formula('A1', '=2+2', num_format, 4)
Strings aren't displayed in Apple Numbers in 'constant_memory' mode
-------------------------------------------------------------------
In :func:`Workbook` ``'constant_memory'`` mode XlsxWriter uses an optimisation
where cell strings aren't stored in an Excel structure call "shared strings"
and instead are written "in-line".
This is a documented Excel feature that is supported by most spreadsheet
applications. One known exception is Apple Numbers for Mac where the string
data isn't displayed.
Images not displayed correctly in Excel 2001 for Mac and non-Excel applications
-------------------------------------------------------------------------------
Images inserted into worksheets via :func:`insert_image` may not display
correctly in Excel 2011 for Mac and non-Excel applications such as OpenOffice
and LibreOffice. Specifically the images may looked stretched or squashed.
This is not specifically an XlsxWriter issue. It also occurs with files created
in Excel 2007 and Excel 2010.
Charts series created from Worksheet Tables cannot have user defined names
--------------------------------------------------------------------------
In Excel, charts created from :ref:`Worksheet Tables <tables>` have a
limitation where the data series name, if specifed, must refer to a cell
within the table.
To workaround this Excel limitation you can specify a user defined name in the
table and refer to that from the chart. See :ref:`charts_from_tables`.
.. _reporting_bugs:
Reporting Bugs
==============
Here are some tips on reporting bugs in XlsxWriter.
Upgrade to the latest version of the module
-------------------------------------------
The bug you are reporting may already be fixed in the latest version of the
module. You can check which version of XlsxWriter that you are using as
follows::
python -c 'import xlsxwriter; print(xlsxwriter.__version__)'
Check the :ref:`changes` section to see what has changed in the latest versions.
Read the documentation
----------------------
Read or search the XlsxWriter documentation to see if the issue you are
encountering is already explained.
Look at the example programs
----------------------------
There are many :ref:`examples` in the distribution. Try to identify an example
program that corresponds to your query and adapt it to use as a bug report.
Use the official XlsxWriter Issue tracker on GitHub
---------------------------------------------------
The official XlsxWriter
`Issue tracker is on GitHub <https://github.com/jmcnamara/XlsxWriter/issues>`_.
Pointers for submitting a bug report
------------------------------------
#. Describe the problem as clearly and as concisely as possible.
#. Include a sample program. This is probably the most important step. It is
generally easier to describe a problem in code than in written prose.
#. The sample program should be as small as possible to demonstrate the
problem. Don't copy and paste large non-relevant sections of your program.
A sample bug report is shown below. This format helps to analyse and respond to
the bug report more quickly.
**Issue with SOMETHING**
I am using XlsxWriter to do SOMETHING but it appears to do SOMETHING ELSE.
I am using Python version X.Y.Z and XlsxWriter x.y.z.
Here is some code that demonstrates the problem::
import xlsxwriter
workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello world')
workbook.close()
See also how `How to create a Minimal, Complete, and Verifiable example
<http://stackoverflow.com/help/mcve>`_ from StackOverflow.
| {
"content_hash": "2793cea5c4d8bccc3bb4bf1c497e35ab",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 129,
"avg_line_length": 37.9010989010989,
"alnum_prop": 0.6965787184691214,
"repo_name": "Thhhza/XlsxWriter",
"id": "d8eb9d20fe793beccfb4f363f796e6dbc516336e",
"size": "6898",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/docs/source/bugs.rst",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "5113"
},
{
"name": "CSS",
"bytes": "16544"
},
{
"name": "HTML",
"bytes": "13100"
},
{
"name": "Makefile",
"bytes": "7545"
},
{
"name": "Perl",
"bytes": "3504"
},
{
"name": "Python",
"bytes": "2347339"
},
{
"name": "Shell",
"bytes": "6064"
}
],
"symlink_target": ""
} |
.class Lcom/samsung/android/settings/networklock/NetworkLockUtils$1;
.super Landroid/os/CountDownTimer;
.source "NetworkLockUtils.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/samsung/android/settings/networklock/NetworkLockUtils;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/samsung/android/settings/networklock/NetworkLockUtils;
# direct methods
.method constructor <init>(Lcom/samsung/android/settings/networklock/NetworkLockUtils;JJ)V
.locals 0
iput-object p1, p0, Lcom/samsung/android/settings/networklock/NetworkLockUtils$1;->this$0:Lcom/samsung/android/settings/networklock/NetworkLockUtils;
invoke-direct {p0, p2, p3, p4, p5}, Landroid/os/CountDownTimer;-><init>(JJ)V
return-void
.end method
# virtual methods
.method public onFinish()V
.locals 4
const-string/jumbo v1, "network_lock"
new-instance v2, Ljava/lang/StringBuilder;
invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v3, "mNoResponseTimer timed out when waiting for message "
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
iget-object v3, p0, Lcom/samsung/android/settings/networklock/NetworkLockUtils$1;->this$0:Lcom/samsung/android/settings/networklock/NetworkLockUtils;
invoke-static {v3}, Lcom/samsung/android/settings/networklock/NetworkLockUtils;->-get1(Lcom/samsung/android/settings/networklock/NetworkLockUtils;)I
move-result v3
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v2
invoke-static {v1, v2}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I
iget-object v1, p0, Lcom/samsung/android/settings/networklock/NetworkLockUtils$1;->this$0:Lcom/samsung/android/settings/networklock/NetworkLockUtils;
invoke-static {v1}, Lcom/samsung/android/settings/networklock/NetworkLockUtils;->-get0(Lcom/samsung/android/settings/networklock/NetworkLockUtils;)Landroid/os/Handler;
move-result-object v1
iget-object v2, p0, Lcom/samsung/android/settings/networklock/NetworkLockUtils$1;->this$0:Lcom/samsung/android/settings/networklock/NetworkLockUtils;
invoke-static {v2}, Lcom/samsung/android/settings/networklock/NetworkLockUtils;->-get1(Lcom/samsung/android/settings/networklock/NetworkLockUtils;)I
move-result v2
invoke-virtual {v1, v2}, Landroid/os/Handler;->obtainMessage(I)Landroid/os/Message;
move-result-object v0
const/4 v1, -0x1
iput v1, v0, Landroid/os/Message;->arg1:I
iget-object v1, p0, Lcom/samsung/android/settings/networklock/NetworkLockUtils$1;->this$0:Lcom/samsung/android/settings/networklock/NetworkLockUtils;
invoke-static {v1}, Lcom/samsung/android/settings/networklock/NetworkLockUtils;->-get0(Lcom/samsung/android/settings/networklock/NetworkLockUtils;)Landroid/os/Handler;
move-result-object v1
invoke-virtual {v1, v0}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z
return-void
.end method
.method public onTick(J)V
.locals 5
const-string/jumbo v0, "network_lock"
new-instance v1, Ljava/lang/StringBuilder;
invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v2, "mNoResponseTimer "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v1
const-string/jumbo v2, " onTick + seconds remaining: "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
const-wide/16 v2, 0x3e8
div-long v2, p1, v2
invoke-virtual {v1, v2, v3}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I
return-void
.end method
| {
"content_hash": "3fca3e1be59f7282b7ca1e8825ada34b",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 171,
"avg_line_length": 32.60294117647059,
"alnum_prop": 0.7512404149751917,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "e6c07d8ae6897d1ab1f2b7d3540cf88c4f2dd7f7",
"size": "4434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SecSettings/smali/com/samsung/android/settings/networklock/NetworkLockUtils$1.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
package banco;
class ContaCorrente extends Conta implements Tributavel {
@Override
public void atualiza(double taxa) {
this.saldo += this.saldo * taxa * 2;
}
@Override
public void deposita(double valor) {
super.deposita(valor);
this.saldo -= 0.10;
}
public double calculaTributos() {
return this.getSaldo() * 0.01;
}
}
| {
"content_hash": "08caf88449ba5140c1483c093de09c5d",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 57,
"avg_line_length": 18,
"alnum_prop": 0.6900584795321637,
"repo_name": "Markuus13/java",
"id": "c707a2a55cf6a3f4d7b0a3c5ddc33b59e50ee502",
"size": "342",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "FJ-11 Java e Orientação a Objetos/11 - Exceções e Controle de erros/banco/ContaCorrente.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "24543"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<com.coco.slidinguppanel.SlidingUpPanel
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#aaa"
android:padding="20dp" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="40dp"
android:text="Button2" />
</com.coco.slidinguppanel.SlidingUpPanel>
<com.coco.slidinguppanel.SlidingUpPanel
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#bbb"
android:padding="10dp" >
</com.coco.slidinguppanel.SlidingUpPanel>
<com.coco.slidinguppanel.SlidingUpPanel
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ccc"
android:padding="10dp" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Button3" />
</com.coco.slidinguppanel.SlidingUpPanel>
<com.coco.slidinguppanel.SlidingUpPanel
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ddd"
android:padding="0dp" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:text="Button4" />
</com.coco.slidinguppanel.SlidingUpPanel>
<com.coco.slidinguppanel.SlidingUpPanel
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eee"
android:padding="0dp" >
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:text="Button4" />
</com.coco.slidinguppanel.SlidingUpPanel>
</LinearLayout> | {
"content_hash": "507a0c37cd2aceb8c3a1a7f9d58e57ff",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 72,
"avg_line_length": 33.59154929577465,
"alnum_prop": 0.6360587002096436,
"repo_name": "zzhouj/Android-SlidingUpPanel",
"id": "0a3265008a7f0d1abaf3764f88efc65a475e71f3",
"size": "2385",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "SlidingUpPanelTest/res/layout/sliding_up_panel_layout_test.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "25422"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout}">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title th:text="#{screen.pm.reset.title}">Reset Password Send Instructions View</title>
<link href="../../static/css/cas.css" rel="stylesheet" th:remove="tag" />
</head>
<body>
<main role="main" class="container mt-3 mb-3">
<div layout:fragment="content" id="reset">
<h3 th:utext="#{screen.pm.reset.title}">Reset your password</h3>
<div th:utext="#{screen.pm.reset.instructions}">Please provide your username. You will receive an email with follow-up instructions on how to reset your password.</div>
<p/>
<div class="alert alert-danger" th:if="${flowRequestContext.messageContext.hasErrorMessages()}">
<p th:each="message : ${flowRequestContext.messageContext.allMessages}" th:utext="#{${message.text}}">Message Text</p>
</div>
<form method="post" id="fm1" class="fm-v clearfix">
<input type="hidden" name="execution" th:value="${flowExecutionKey}"/>
<input type="hidden" name="_eventId" value="findAccount"/>
<div class="form-group">
<label for="username" class="fl-label" th:utext="#{screen.pm.reset.username}"/>
<input type="text" class="form-control" id="username" name="username"
size="45" tabindex="1" required/>
</div>
<input class="btn btn-submit" accesskey="s"
th:value="#{screen.pm.button.submit}" tabindex="2" type="submit" value="SUBMIT"/>
<input class="btn btn-danger"
name="cancel"
accesskey="c"
th:value="#{screen.pm.button.cancel}"
th:attr="data-processing-text=#{screen.welcome.button.loginwip}"
type="button"
onclick="location.href = location.href;" value="CANCEL"/>
</form>
<p/>
</div>
</main>
</body>
</html>
| {
"content_hash": "780566b0add57df4bca5e540ce95b2b8",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 176,
"avg_line_length": 46.234042553191486,
"alnum_prop": 0.5890473999079613,
"repo_name": "bshp/theme-cas_bshp",
"id": "4c1c9e051612a5d305effdfccc5938182a183de0",
"size": "2173",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/resources/templates/casResetPasswordSendInstructionsView.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "85728"
},
{
"name": "HTML",
"bytes": "148007"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.rds.model;
/**
* <p>
* Contains the result of a successful invocation of the following actions:
* </p>
*
* <ul>
* <li> CreateDBSnapshot </li>
* <li> DeleteDBSnapshot </li>
*
* </ul>
* <p>
* This data type is used as a response element in the DescribeDBSnapshots action.
* </p>
*/
public class DBSnapshot {
/**
* Specifies the identifier for the DB Snapshot.
*/
private String dBSnapshotIdentifier;
/**
* Specifies the the DBInstanceIdentifier of the DB Instance this DB
* Snapshot was created from.
*/
private String dBInstanceIdentifier;
/**
* Provides the time (UTC) when the snapshot was taken.
*/
private java.util.Date snapshotCreateTime;
/**
* Specifies the name of the database engine.
*/
private String engine;
/**
* Specifies the allocated storage size in gigabytes (GB).
*/
private Integer allocatedStorage;
/**
* Specifies the status of this DB Snapshot.
*/
private String status;
/**
* Specifies the port that the database engine was listening on at the
* time of the snapshot.
*/
private Integer port;
/**
* Specifies the name of the Availability Zone the DB Instance was
* located in at the time of the DB Snapshot.
*/
private String availabilityZone;
/**
* Provides the Vpc Id associated with the DB Snapshot.
*/
private String vpcId;
/**
* Specifies the time (UTC) when the snapshot was taken.
*/
private java.util.Date instanceCreateTime;
/**
* Provides the master username for the DB Instance.
*/
private String masterUsername;
/**
* Specifies the version of the database engine.
*/
private String engineVersion;
/**
* License model information for the restored DB Instance.
*/
private String licenseModel;
/**
* Provides the type of the DB Snapshot.
*/
private String snapshotType;
/**
* Specifies the identifier for the DB Snapshot.
*
* @return Specifies the identifier for the DB Snapshot.
*/
public String getDBSnapshotIdentifier() {
return dBSnapshotIdentifier;
}
/**
* Specifies the identifier for the DB Snapshot.
*
* @param dBSnapshotIdentifier Specifies the identifier for the DB Snapshot.
*/
public void setDBSnapshotIdentifier(String dBSnapshotIdentifier) {
this.dBSnapshotIdentifier = dBSnapshotIdentifier;
}
/**
* Specifies the identifier for the DB Snapshot.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param dBSnapshotIdentifier Specifies the identifier for the DB Snapshot.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withDBSnapshotIdentifier(String dBSnapshotIdentifier) {
this.dBSnapshotIdentifier = dBSnapshotIdentifier;
return this;
}
/**
* Specifies the the DBInstanceIdentifier of the DB Instance this DB
* Snapshot was created from.
*
* @return Specifies the the DBInstanceIdentifier of the DB Instance this DB
* Snapshot was created from.
*/
public String getDBInstanceIdentifier() {
return dBInstanceIdentifier;
}
/**
* Specifies the the DBInstanceIdentifier of the DB Instance this DB
* Snapshot was created from.
*
* @param dBInstanceIdentifier Specifies the the DBInstanceIdentifier of the DB Instance this DB
* Snapshot was created from.
*/
public void setDBInstanceIdentifier(String dBInstanceIdentifier) {
this.dBInstanceIdentifier = dBInstanceIdentifier;
}
/**
* Specifies the the DBInstanceIdentifier of the DB Instance this DB
* Snapshot was created from.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param dBInstanceIdentifier Specifies the the DBInstanceIdentifier of the DB Instance this DB
* Snapshot was created from.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withDBInstanceIdentifier(String dBInstanceIdentifier) {
this.dBInstanceIdentifier = dBInstanceIdentifier;
return this;
}
/**
* Provides the time (UTC) when the snapshot was taken.
*
* @return Provides the time (UTC) when the snapshot was taken.
*/
public java.util.Date getSnapshotCreateTime() {
return snapshotCreateTime;
}
/**
* Provides the time (UTC) when the snapshot was taken.
*
* @param snapshotCreateTime Provides the time (UTC) when the snapshot was taken.
*/
public void setSnapshotCreateTime(java.util.Date snapshotCreateTime) {
this.snapshotCreateTime = snapshotCreateTime;
}
/**
* Provides the time (UTC) when the snapshot was taken.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param snapshotCreateTime Provides the time (UTC) when the snapshot was taken.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withSnapshotCreateTime(java.util.Date snapshotCreateTime) {
this.snapshotCreateTime = snapshotCreateTime;
return this;
}
/**
* Specifies the name of the database engine.
*
* @return Specifies the name of the database engine.
*/
public String getEngine() {
return engine;
}
/**
* Specifies the name of the database engine.
*
* @param engine Specifies the name of the database engine.
*/
public void setEngine(String engine) {
this.engine = engine;
}
/**
* Specifies the name of the database engine.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param engine Specifies the name of the database engine.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withEngine(String engine) {
this.engine = engine;
return this;
}
/**
* Specifies the allocated storage size in gigabytes (GB).
*
* @return Specifies the allocated storage size in gigabytes (GB).
*/
public Integer getAllocatedStorage() {
return allocatedStorage;
}
/**
* Specifies the allocated storage size in gigabytes (GB).
*
* @param allocatedStorage Specifies the allocated storage size in gigabytes (GB).
*/
public void setAllocatedStorage(Integer allocatedStorage) {
this.allocatedStorage = allocatedStorage;
}
/**
* Specifies the allocated storage size in gigabytes (GB).
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param allocatedStorage Specifies the allocated storage size in gigabytes (GB).
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withAllocatedStorage(Integer allocatedStorage) {
this.allocatedStorage = allocatedStorage;
return this;
}
/**
* Specifies the status of this DB Snapshot.
*
* @return Specifies the status of this DB Snapshot.
*/
public String getStatus() {
return status;
}
/**
* Specifies the status of this DB Snapshot.
*
* @param status Specifies the status of this DB Snapshot.
*/
public void setStatus(String status) {
this.status = status;
}
/**
* Specifies the status of this DB Snapshot.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param status Specifies the status of this DB Snapshot.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withStatus(String status) {
this.status = status;
return this;
}
/**
* Specifies the port that the database engine was listening on at the
* time of the snapshot.
*
* @return Specifies the port that the database engine was listening on at the
* time of the snapshot.
*/
public Integer getPort() {
return port;
}
/**
* Specifies the port that the database engine was listening on at the
* time of the snapshot.
*
* @param port Specifies the port that the database engine was listening on at the
* time of the snapshot.
*/
public void setPort(Integer port) {
this.port = port;
}
/**
* Specifies the port that the database engine was listening on at the
* time of the snapshot.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param port Specifies the port that the database engine was listening on at the
* time of the snapshot.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withPort(Integer port) {
this.port = port;
return this;
}
/**
* Specifies the name of the Availability Zone the DB Instance was
* located in at the time of the DB Snapshot.
*
* @return Specifies the name of the Availability Zone the DB Instance was
* located in at the time of the DB Snapshot.
*/
public String getAvailabilityZone() {
return availabilityZone;
}
/**
* Specifies the name of the Availability Zone the DB Instance was
* located in at the time of the DB Snapshot.
*
* @param availabilityZone Specifies the name of the Availability Zone the DB Instance was
* located in at the time of the DB Snapshot.
*/
public void setAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
}
/**
* Specifies the name of the Availability Zone the DB Instance was
* located in at the time of the DB Snapshot.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param availabilityZone Specifies the name of the Availability Zone the DB Instance was
* located in at the time of the DB Snapshot.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
return this;
}
/**
* Provides the Vpc Id associated with the DB Snapshot.
*
* @return Provides the Vpc Id associated with the DB Snapshot.
*/
public String getVpcId() {
return vpcId;
}
/**
* Provides the Vpc Id associated with the DB Snapshot.
*
* @param vpcId Provides the Vpc Id associated with the DB Snapshot.
*/
public void setVpcId(String vpcId) {
this.vpcId = vpcId;
}
/**
* Provides the Vpc Id associated with the DB Snapshot.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param vpcId Provides the Vpc Id associated with the DB Snapshot.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withVpcId(String vpcId) {
this.vpcId = vpcId;
return this;
}
/**
* Specifies the time (UTC) when the snapshot was taken.
*
* @return Specifies the time (UTC) when the snapshot was taken.
*/
public java.util.Date getInstanceCreateTime() {
return instanceCreateTime;
}
/**
* Specifies the time (UTC) when the snapshot was taken.
*
* @param instanceCreateTime Specifies the time (UTC) when the snapshot was taken.
*/
public void setInstanceCreateTime(java.util.Date instanceCreateTime) {
this.instanceCreateTime = instanceCreateTime;
}
/**
* Specifies the time (UTC) when the snapshot was taken.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param instanceCreateTime Specifies the time (UTC) when the snapshot was taken.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withInstanceCreateTime(java.util.Date instanceCreateTime) {
this.instanceCreateTime = instanceCreateTime;
return this;
}
/**
* Provides the master username for the DB Instance.
*
* @return Provides the master username for the DB Instance.
*/
public String getMasterUsername() {
return masterUsername;
}
/**
* Provides the master username for the DB Instance.
*
* @param masterUsername Provides the master username for the DB Instance.
*/
public void setMasterUsername(String masterUsername) {
this.masterUsername = masterUsername;
}
/**
* Provides the master username for the DB Instance.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param masterUsername Provides the master username for the DB Instance.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withMasterUsername(String masterUsername) {
this.masterUsername = masterUsername;
return this;
}
/**
* Specifies the version of the database engine.
*
* @return Specifies the version of the database engine.
*/
public String getEngineVersion() {
return engineVersion;
}
/**
* Specifies the version of the database engine.
*
* @param engineVersion Specifies the version of the database engine.
*/
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
/**
* Specifies the version of the database engine.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param engineVersion Specifies the version of the database engine.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
return this;
}
/**
* License model information for the restored DB Instance.
*
* @return License model information for the restored DB Instance.
*/
public String getLicenseModel() {
return licenseModel;
}
/**
* License model information for the restored DB Instance.
*
* @param licenseModel License model information for the restored DB Instance.
*/
public void setLicenseModel(String licenseModel) {
this.licenseModel = licenseModel;
}
/**
* License model information for the restored DB Instance.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param licenseModel License model information for the restored DB Instance.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withLicenseModel(String licenseModel) {
this.licenseModel = licenseModel;
return this;
}
/**
* Provides the type of the DB Snapshot.
*
* @return Provides the type of the DB Snapshot.
*/
public String getSnapshotType() {
return snapshotType;
}
/**
* Provides the type of the DB Snapshot.
*
* @param snapshotType Provides the type of the DB Snapshot.
*/
public void setSnapshotType(String snapshotType) {
this.snapshotType = snapshotType;
}
/**
* Provides the type of the DB Snapshot.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param snapshotType Provides the type of the DB Snapshot.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DBSnapshot withSnapshotType(String snapshotType) {
this.snapshotType = snapshotType;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (dBSnapshotIdentifier != null) sb.append("DBSnapshotIdentifier: " + dBSnapshotIdentifier + ", ");
if (dBInstanceIdentifier != null) sb.append("DBInstanceIdentifier: " + dBInstanceIdentifier + ", ");
if (snapshotCreateTime != null) sb.append("SnapshotCreateTime: " + snapshotCreateTime + ", ");
if (engine != null) sb.append("Engine: " + engine + ", ");
if (allocatedStorage != null) sb.append("AllocatedStorage: " + allocatedStorage + ", ");
if (status != null) sb.append("Status: " + status + ", ");
if (port != null) sb.append("Port: " + port + ", ");
if (availabilityZone != null) sb.append("AvailabilityZone: " + availabilityZone + ", ");
if (vpcId != null) sb.append("VpcId: " + vpcId + ", ");
if (instanceCreateTime != null) sb.append("InstanceCreateTime: " + instanceCreateTime + ", ");
if (masterUsername != null) sb.append("MasterUsername: " + masterUsername + ", ");
if (engineVersion != null) sb.append("EngineVersion: " + engineVersion + ", ");
if (licenseModel != null) sb.append("LicenseModel: " + licenseModel + ", ");
if (snapshotType != null) sb.append("SnapshotType: " + snapshotType + ", ");
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getDBSnapshotIdentifier() == null) ? 0 : getDBSnapshotIdentifier().hashCode());
hashCode = prime * hashCode + ((getDBInstanceIdentifier() == null) ? 0 : getDBInstanceIdentifier().hashCode());
hashCode = prime * hashCode + ((getSnapshotCreateTime() == null) ? 0 : getSnapshotCreateTime().hashCode());
hashCode = prime * hashCode + ((getEngine() == null) ? 0 : getEngine().hashCode());
hashCode = prime * hashCode + ((getAllocatedStorage() == null) ? 0 : getAllocatedStorage().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode + ((getPort() == null) ? 0 : getPort().hashCode());
hashCode = prime * hashCode + ((getAvailabilityZone() == null) ? 0 : getAvailabilityZone().hashCode());
hashCode = prime * hashCode + ((getVpcId() == null) ? 0 : getVpcId().hashCode());
hashCode = prime * hashCode + ((getInstanceCreateTime() == null) ? 0 : getInstanceCreateTime().hashCode());
hashCode = prime * hashCode + ((getMasterUsername() == null) ? 0 : getMasterUsername().hashCode());
hashCode = prime * hashCode + ((getEngineVersion() == null) ? 0 : getEngineVersion().hashCode());
hashCode = prime * hashCode + ((getLicenseModel() == null) ? 0 : getLicenseModel().hashCode());
hashCode = prime * hashCode + ((getSnapshotType() == null) ? 0 : getSnapshotType().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof DBSnapshot == false) return false;
DBSnapshot other = (DBSnapshot)obj;
if (other.getDBSnapshotIdentifier() == null ^ this.getDBSnapshotIdentifier() == null) return false;
if (other.getDBSnapshotIdentifier() != null && other.getDBSnapshotIdentifier().equals(this.getDBSnapshotIdentifier()) == false) return false;
if (other.getDBInstanceIdentifier() == null ^ this.getDBInstanceIdentifier() == null) return false;
if (other.getDBInstanceIdentifier() != null && other.getDBInstanceIdentifier().equals(this.getDBInstanceIdentifier()) == false) return false;
if (other.getSnapshotCreateTime() == null ^ this.getSnapshotCreateTime() == null) return false;
if (other.getSnapshotCreateTime() != null && other.getSnapshotCreateTime().equals(this.getSnapshotCreateTime()) == false) return false;
if (other.getEngine() == null ^ this.getEngine() == null) return false;
if (other.getEngine() != null && other.getEngine().equals(this.getEngine()) == false) return false;
if (other.getAllocatedStorage() == null ^ this.getAllocatedStorage() == null) return false;
if (other.getAllocatedStorage() != null && other.getAllocatedStorage().equals(this.getAllocatedStorage()) == false) return false;
if (other.getStatus() == null ^ this.getStatus() == null) return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false;
if (other.getPort() == null ^ this.getPort() == null) return false;
if (other.getPort() != null && other.getPort().equals(this.getPort()) == false) return false;
if (other.getAvailabilityZone() == null ^ this.getAvailabilityZone() == null) return false;
if (other.getAvailabilityZone() != null && other.getAvailabilityZone().equals(this.getAvailabilityZone()) == false) return false;
if (other.getVpcId() == null ^ this.getVpcId() == null) return false;
if (other.getVpcId() != null && other.getVpcId().equals(this.getVpcId()) == false) return false;
if (other.getInstanceCreateTime() == null ^ this.getInstanceCreateTime() == null) return false;
if (other.getInstanceCreateTime() != null && other.getInstanceCreateTime().equals(this.getInstanceCreateTime()) == false) return false;
if (other.getMasterUsername() == null ^ this.getMasterUsername() == null) return false;
if (other.getMasterUsername() != null && other.getMasterUsername().equals(this.getMasterUsername()) == false) return false;
if (other.getEngineVersion() == null ^ this.getEngineVersion() == null) return false;
if (other.getEngineVersion() != null && other.getEngineVersion().equals(this.getEngineVersion()) == false) return false;
if (other.getLicenseModel() == null ^ this.getLicenseModel() == null) return false;
if (other.getLicenseModel() != null && other.getLicenseModel().equals(this.getLicenseModel()) == false) return false;
if (other.getSnapshotType() == null ^ this.getSnapshotType() == null) return false;
if (other.getSnapshotType() != null && other.getSnapshotType().equals(this.getSnapshotType()) == false) return false;
return true;
}
}
| {
"content_hash": "56b9e20a31aefdb56515fd7d66af0ca8",
"timestamp": "",
"source": "github",
"line_count": 679,
"max_line_length": 150,
"avg_line_length": 35.25773195876289,
"alnum_prop": 0.6294486215538847,
"repo_name": "frsyuki/aws-sdk-for-java",
"id": "7d62fa479139e8db8fe7b75890d0d41a3afd6587",
"size": "24527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/amazonaws/services/rds/model/DBSnapshot.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="create_run_jar" name="Create Runnable Jar for Project obit_annotation_tool">
<!--this file was created by Eclipse Runnable JAR Export Wizard-->
<!--ANT 1.7 is required -->
<!--define folder properties-->
<property name="dir.buildfile" value="."/>
<property name="dir.workspace" value="${dir.buildfile}/../../.."/>
<property name="dir.jarfile" value="${dir.buildfile}"/>
<target name="create_run_jar">
<jar destfile="${dir.jarfile}/AnnotationToolAdmin.jar" filesetmanifest="mergewithoutmain">
<manifest>
<attribute name="Main-Class" value="ch.ethz.scu.obit.atadmin.AnnotationToolAdmin"/>
<attribute name="Class-Path" value="."/>
</manifest>
<fileset dir="${dir.workspace}/obit_annotation_tool/bin"/>
</jar>
</target>
</project>
| {
"content_hash": "0dfdb019e49f4f68c81b2fba3674718e",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 99,
"avg_line_length": 53.05555555555556,
"alnum_prop": 0.5979057591623037,
"repo_name": "aarpon/obit_annotation_tool",
"id": "3777f04328f137ff01c2a101756d02314df89921",
"size": "955",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "dist/Linux/AnnotationToolAdminExeJar.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "914670"
},
{
"name": "XSLT",
"bytes": "64106"
}
],
"symlink_target": ""
} |
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
end
ROOT_PER_PAGE = 5
def root
@articles = Article.
order("id DESC").
page(params[:page]).
per(ROOT_PER_PAGE)
end
INDEX_PER_PAGE = 10
def index
@articles = Article.
order("id DESC").
page(params[:page]).
per(INDEX_PER_PAGE)
end
def hiragana
@article = Article.find(params[:id]).hiragana
render :show, locals: { hiragana: true }
end
private
def article_params
Article.extract_title_text(params.require(:article)[:title_text])
end
end
| {
"content_hash": "d452fd4526cb07a6cca98073309cca51",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 69,
"avg_line_length": 19.34375,
"alnum_prop": 0.6348949919224556,
"repo_name": "hogelog/blog",
"id": "7449f63d2708ec165974f4ebcb92ec2fe301846a",
"size": "619",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/articles_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6167"
},
{
"name": "CoffeeScript",
"bytes": "1798"
},
{
"name": "JavaScript",
"bytes": "722"
},
{
"name": "Ruby",
"bytes": "35007"
}
],
"symlink_target": ""
} |
/********************************************************************************
** Form generated from reading UI file 'editaddressdialog.ui'
**
** Created by: Qt User Interface Compiler version 4.8.5
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_EDITADDRESSDIALOG_H
#define UI_EDITADDRESSDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_EditAddressDialog
{
public:
QVBoxLayout *verticalLayout;
QFormLayout *formLayout;
QLabel *label;
QLineEdit *labelEdit;
QLabel *label_2;
QLineEdit *addressEdit;
QDialogButtonBox *buttonBox;
void setupUi(QDialog *EditAddressDialog)
{
if (EditAddressDialog->objectName().isEmpty())
EditAddressDialog->setObjectName(QString::fromUtf8("EditAddressDialog"));
EditAddressDialog->resize(457, 126);
verticalLayout = new QVBoxLayout(EditAddressDialog);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
formLayout = new QFormLayout();
formLayout->setObjectName(QString::fromUtf8("formLayout"));
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
label = new QLabel(EditAddressDialog);
label->setObjectName(QString::fromUtf8("label"));
formLayout->setWidget(0, QFormLayout::LabelRole, label);
labelEdit = new QLineEdit(EditAddressDialog);
labelEdit->setObjectName(QString::fromUtf8("labelEdit"));
formLayout->setWidget(0, QFormLayout::FieldRole, labelEdit);
label_2 = new QLabel(EditAddressDialog);
label_2->setObjectName(QString::fromUtf8("label_2"));
formLayout->setWidget(1, QFormLayout::LabelRole, label_2);
addressEdit = new QLineEdit(EditAddressDialog);
addressEdit->setObjectName(QString::fromUtf8("addressEdit"));
formLayout->setWidget(1, QFormLayout::FieldRole, addressEdit);
verticalLayout->addLayout(formLayout);
buttonBox = new QDialogButtonBox(EditAddressDialog);
buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
verticalLayout->addWidget(buttonBox);
#ifndef QT_NO_SHORTCUT
label->setBuddy(labelEdit);
label_2->setBuddy(addressEdit);
#endif // QT_NO_SHORTCUT
retranslateUi(EditAddressDialog);
QObject::connect(buttonBox, SIGNAL(accepted()), EditAddressDialog, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), EditAddressDialog, SLOT(reject()));
QMetaObject::connectSlotsByName(EditAddressDialog);
} // setupUi
void retranslateUi(QDialog *EditAddressDialog)
{
EditAddressDialog->setWindowTitle(QApplication::translate("EditAddressDialog", "Edit Address", 0));
label->setText(QApplication::translate("EditAddressDialog", "&Label", 0));
#ifndef QT_NO_TOOLTIP
labelEdit->setToolTip(QApplication::translate("EditAddressDialog", "The label associated with this address book entry", 0));
#endif // QT_NO_TOOLTIP
label_2->setText(QApplication::translate("EditAddressDialog", "&Address", 0));
#ifndef QT_NO_TOOLTIP
addressEdit->setToolTip(QApplication::translate("EditAddressDialog", "The address associated with this address book entry. This can only be modified for sending addresses.", 0));
#endif // QT_NO_TOOLTIP
} // retranslateUi
};
namespace Ui {
class EditAddressDialog: public Ui_EditAddressDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_EDITADDRESSDIALOG_H
| {
"content_hash": "a7c26eba9bda8c6ca93896e7dfd1fdcc",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 186,
"avg_line_length": 36.763636363636365,
"alnum_prop": 0.6894164193867458,
"repo_name": "apecoin/build",
"id": "5c6c5bad88b5158fddb4102cb901bc2000f615f7",
"size": "4044",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/ui_editaddressdialog.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "286377"
},
{
"name": "C++",
"bytes": "2465943"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "11934"
},
{
"name": "Objective-C",
"bytes": "50500"
},
{
"name": "Python",
"bytes": "18144"
},
{
"name": "Shell",
"bytes": "1144"
}
],
"symlink_target": ""
} |
package com.tazzvose.swiftly.ast;
import com.tazzvose.swiftly.type.SwiftField;
public final class StoreFieldNode
implements AstNode{
private final SwiftField field;
private final AstNode value;
public StoreFieldNode(SwiftField field, AstNode value){
this.field = field;
this.value = value;
}
public SwiftField getField(){
return this.field;
}
public AstNode getValue(){
return this.value;
}
@Override
public void visit(AstNodeVisitor vis){
vis.visitStoreFieldNode(this);
}
@Override
public void visitChildren(AstNodeVisitor vis){
this.getValue().visit(vis);
}
} | {
"content_hash": "b34861e48bd630a907d7b5d46c77bcfc",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 57,
"avg_line_length": 19.40625,
"alnum_prop": 0.7214170692431562,
"repo_name": "s0cks/Swiftly",
"id": "ccb15c7c4228ce33d51630990214bb3cc6417866",
"size": "621",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/tazzvose/swiftly/ast/StoreFieldNode.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "25495"
},
{
"name": "Swift",
"bytes": "107"
}
],
"symlink_target": ""
} |
<div id="switch_page">
<canvas id="switch_canvas" width="800px" height="600px"></canvas>
</div> | {
"content_hash": "9b412a69cd15788f765a3ee8d64b1116",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 69,
"avg_line_length": 33,
"alnum_prop": 0.6565656565656566,
"repo_name": "simonidnov/okaoka_restauth",
"id": "5964ea0d73e583a45de25ebef82e3150816e40bf",
"size": "99",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "okaoka_online/pages/switcher/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "389"
},
{
"name": "CSS",
"bytes": "96117"
},
{
"name": "HTML",
"bytes": "8138781"
},
{
"name": "JavaScript",
"bytes": "7574704"
},
{
"name": "PHP",
"bytes": "1911483"
}
],
"symlink_target": ""
} |
package com.google.cloud.orgpolicy.v2.samples;
// [START orgpolicy_v2_generated_OrgPolicy_DeletePolicy_Policyname_sync]
import com.google.cloud.orgpolicy.v2.OrgPolicyClient;
import com.google.cloud.orgpolicy.v2.PolicyName;
import com.google.protobuf.Empty;
public class SyncDeletePolicyPolicyname {
public static void main(String[] args) throws Exception {
syncDeletePolicyPolicyname();
}
public static void syncDeletePolicyPolicyname() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (OrgPolicyClient orgPolicyClient = OrgPolicyClient.create()) {
PolicyName name = PolicyName.ofProjectPolicyName("[PROJECT]", "[POLICY]");
orgPolicyClient.deletePolicy(name);
}
}
}
// [END orgpolicy_v2_generated_OrgPolicy_DeletePolicy_Policyname_sync]
| {
"content_hash": "b37dbe30a8a3247562196e6665c01090",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 100,
"avg_line_length": 41.5,
"alnum_prop": 0.7650602409638554,
"repo_name": "googleapis/java-orgpolicy",
"id": "b8765cac24dee927aed040216c16b22712e042b2",
"size": "1757",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "samples/snippets/generated/com/google/cloud/orgpolicy/v2/orgpolicy/deletepolicy/SyncDeletePolicyPolicyname.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "1192475"
},
{
"name": "Python",
"bytes": "863"
},
{
"name": "Shell",
"bytes": "22851"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Draggable Element Element</title>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<meta name="title" content="Draggable Element Element"/>
<meta name="generator" content="Org-mode"/>
<meta name="generated" content="2014-11-12 19:51:09 CST"/>
<meta name="author" content="Rusty Klophaus (@rustyio)"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
html { font-family: Times, serif; font-size: 12pt; }
.title { text-align: center; }
.todo { color: red; }
.done { color: green; }
.tag { background-color: #add8e6; font-weight:normal }
.target { }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.right {margin-left:auto; margin-right:0px; text-align:right;}
.left {margin-left:0px; margin-right:auto; text-align:left;}
.center {margin-left:auto; margin-right:auto; text-align:center;}
p.verse { margin-left: 3% }
pre {
border: 1pt solid #AEBDCC;
background-color: #F3F5F7;
padding: 5pt;
font-family: courier, monospace;
font-size: 90%;
overflow:auto;
}
table { border-collapse: collapse; }
td, th { vertical-align: top; }
th.right { text-align:center; }
th.left { text-align:center; }
th.center { text-align:center; }
td.right { text-align:right; }
td.left { text-align:left; }
td.center { text-align:center; }
dt { font-weight: bold; }
div.figure { padding: 0.5em; }
div.figure p { text-align: center; }
div.inlinetask {
padding:10px;
border:2px solid gray;
margin:10px;
background: #ffffcc;
}
textarea { overflow-x: auto; }
.linenr { font-size:smaller }
.code-highlighted {background-color:#ffff00;}
.org-info-js_info-navigation { border-style:none; }
#org-info-js_console-label { font-size:10px; font-weight:bold;
white-space:nowrap; }
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
font-weight:bold; }
/*]]>*/-->
</style>
<LINK href='../stylesheet.css' rel='stylesheet' type='text/css' />
<script type="text/javascript">
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
</head>
<body>
<div id="preamble">
</div>
<div id="content">
<h1 class="title">Draggable Element Element</h1>
<p><a href="http://nitrogenproject.com">Home</a> | <a href="../index.html">Getting Started</a> | <a href="../api.html">API</a> | <a href="../elements.html"><b>Elements</b></a> | <a href="../actions.html">Actions</a> | <a href="../validators.html">Validators</a> | <a href="../handlers.html">Handlers</a> | <a href="../config.html">Configuration Options</a> | <a href="../advanced.html">Advanced Guides</a> | <a href="../troubleshooting.html">Troubleshooting</a> | <a href="../about.html">About</a>
</p>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#sec-1">1 Draggable Element - #draggable {}</a></li>
</ul>
</div>
</div>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1"><span class="section-number-2">1</span> Draggable Element - #draggable {}</h2>
<div class="outline-text-2" id="text-1">
<p>
The draggable element allows you to make a block of Nitrogen elements
draggable by the user.
</p>
<p>
Combine the draggable element with the droppable element to allow drag and
drop behavior.
</p>
</div>
<div id="outline-container-1-1" class="outline-3">
<h3 id="sec-1-1"><span class="section-number-3"></span> Usage</h3>
<div class="outline-text-3" id="text-1-1">
<pre class="src src-erlang">#<span class="org-type">draggable</span> { tag=drag1, clone=true, revert=false, handle=grip, body=[
#<span class="org-type">image</span> { class=grip, url=<span class="org-string">"/images/handle.png"</span> },
#<span class="org-type">span</span> { text=<span class="org-string">"This is a draggable block."</span> }
]}
</pre>
</div>
</div>
<div id="outline-container-1-2" class="outline-3">
<h3 id="sec-1-2"><span class="section-number-3"></span> Attributes</h3>
<div class="outline-text-3" id="text-1-2">
<dl>
<dt>tag - (<i>Erlang term</i>)</dt><dd>The drag term to pass into the <code>drop_event/2</code>
event.
</dd>
<dt>body - (<i>Nitrogen elements</i>)</dt><dd>The elements that will be draggable.
</dd>
<dt>group - (<i>atom or string</i>)</dt><dd>The name of this drag group, for use in the
droppable element's accept_groups attribute.
</dd>
<dt>handle - (<i>atom or string</i>)</dt><dd>The class of the handle element on the page.
Then handle will then be the part of the element that will be clicked and
dragged around.
</dd>
<dt>clone - (<i>boolean</i>)</dt><dd>If true, the element will be cloned in the DOM while
dragged. If false, the element will be detached from the DOM while dragging.
</dd>
<dt>revert - (<i>boolean</i>)</dt><dd>If true, the element will be reverted back to its
original position if the drop fails.
</dd>
<dt>scroll - (<i>boolean</i>)</dt><dd>If true, the window or container will scroll when
the item is dragged to the edge.
</dd>
<dt>distance - (<i>integer</i>)</dt><dd>Set to the minimum number of pixels the cursor
must move with the mouse down before the drag actually begins. (default: 3)
</dd>
<dt>container - (<i>atom or string</i>)</dt><dd>How you wish to contain the draggable
element. Common containers are <code>window</code>, <code>document</code>, or <code>parent</code>.
Otherwise, it can be specified in the form of a jquery selector. See the
documentation on the "Containment" option for the jquery Draggable element
for more information.
</dd>
<dt>zindex - (<i>integer</i>)</dt><dd>The z-index of the element to be dragged around the
page.
</dd>
<dt>options - (<i>proplist</i>)</dt><dd>A list of additional options to be passed to the
draggable function. (See the jQuery Draggable Documentation below for the
complete list of options).
</dd>
</dl>
</div>
</div>
<div id="outline-container-1-3" class="outline-3">
<h3 id="sec-1-3"><span class="section-number-3"></span> See Also</h3>
<div class="outline-text-3" id="text-1-3">
<ul>
<li><a href="./droppable.html">Droppable Element</a>
</li>
<li><a href="file:///demos/dragdrop">Drag and Drop Demo</a>
</li>
<li><a href="http://api.jqueryui.com/draggable/">jQuery Draggable Documentation</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div id="postamble">
<p class="date">Date: 2014-11-12 19:51:09 CST</p>
<p class="author">Author: Rusty Klophaus (@rustyio)</p>
<p class="creator">Org version 7.8.02 with Emacs version 23</p>
<a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
</div><h2>Comments</h2>
<b>Note:</b><!-- Disqus does not currently support Erlang for its syntax highlighting, so t-->To specify <!--Erlang--> code blocks, just use the generic code block syntax: <pre><b><pre><code>your code here</code></pre></b></pre>
<br />
<br />
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'nitrogenproject'; // required: replace example with your forum shortname
var disqus_identifier = 'html/elements/draggable.html'; //This will be replaced with the path part of the url
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</body>
</html>
| {
"content_hash": "4b2fd946ad29b9ff17b33f2880cac2a5",
"timestamp": "",
"source": "github",
"line_count": 252,
"max_line_length": 497,
"avg_line_length": 34.62301587301587,
"alnum_prop": 0.6600573065902579,
"repo_name": "SovereignPrime/nitrogen_core",
"id": "b9d7dee9f6b7af5056c3473b7fd44b5501cc4319",
"size": "8725",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/html/elements/draggable.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10089"
},
{
"name": "Emacs Lisp",
"bytes": "611"
},
{
"name": "Erlang",
"bytes": "473696"
},
{
"name": "JavaScript",
"bytes": "765735"
},
{
"name": "Makefile",
"bytes": "1602"
},
{
"name": "PHP",
"bytes": "19"
},
{
"name": "Shell",
"bytes": "1668"
}
],
"symlink_target": ""
} |
class CallIndexTests < Test::Unit::TestCase
def setup
@calls = [
{:method => :hello, :target => :world, :call => {} },
{:method => :goodbye, :target => :world, :call => {} },
{:method => :foo, :target => :world, :call => {} },
{:method => :foo, :target => :the_bar, :call => {} },
{:method => :foo, :target => :the_baz, :call => {} },
{:method => :do_it, :target => nil, :call => {} },
{:method => :do_it_now, :target => nil, :call => {} },
]
@call_index = Brakeman::CallIndex.new(@calls)
end
def assert_found num, opts
assert @call_index.find_calls(opts).length
end
def test_find_by_method_regex
assert_found 2, :method => %r{do_it(?:_now)?}
end
def test_find_by_method
assert_found 1, :method => :hello
end
def test_find_by_target
assert_found 3, :target => :world
end
def test_find_by_methods
assert_found 5, :methods => [:foo, :hello, :goodbye]
end
def test_find_by_targets
assert_found 4, :targets => [:world, :the_bar]
end
def test_find_by_target_and_method
assert_found 1, :target => :the_bar, :method => :foo
end
def test_find_by_target_and_methods
assert_found 2, :target => :world, :methods => [:foo, :hello]
end
def test_find_by_targets_and_method
assert_found 2, :target => [:world, :the_bar], :methods => :foo
end
def test_find_by_no_target_and_method
assert_found 1, :target => nil, :method => :do_it
end
def test_find_by_no_target_and_methods
assert_found 2, :target => nil, :method => [:do_it, :do_it_now]
end
end
| {
"content_hash": "0638118b5a8e354777e20493a5b1a0d5",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 67,
"avg_line_length": 27.362068965517242,
"alnum_prop": 0.5778197857592943,
"repo_name": "spcoder/brakeman",
"id": "6a3293115296d9cb789423e172e9e31823d697aa",
"size": "1587",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/tests/call_index.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7943"
},
{
"name": "CoffeeScript",
"bytes": "687"
},
{
"name": "HTML",
"bytes": "71428"
},
{
"name": "JavaScript",
"bytes": "9810"
},
{
"name": "Ruby",
"bytes": "946433"
}
],
"symlink_target": ""
} |
module Twilio
module REST
class Api < Domain
class V2010 < Version
class AccountContext < InstanceContext
class UsageList < ListResource
class RecordList < ListResource
class TodayList < ListResource
##
# Initialize the TodayList
# @param [Version] version Version that contains the resource
# @param [String] account_sid A 34 character string that uniquely identifies this
# resource.
# @return [TodayList] TodayList
def initialize(version, account_sid: nil)
super(version)
# Path Solution
@solution = {account_sid: account_sid}
@uri = "/Accounts/#{@solution[:account_sid]}/Usage/Records/Today.json"
end
##
# Lists TodayInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [today.Category] category The {usage
# category}[https://www.twilio.com/docs/usage/api/usage-record#usage-categories]
# of the UsageRecord resources to read. Only UsageRecord resources in the
# specified category are retrieved.
# @param [Date] start_date Only include usage that has occurred on or after this
# date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify
# offsets from the current date, such as: `-30days`, which will set the start date
# to be 30 days before the current date.
# @param [Date] end_date Only include usage that occurred on or before this date.
# Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify
# offsets from the current date, such as: `+30days`, which will set the end date
# to 30 days from the current date.
# @param [Boolean] include_subaccounts Whether to include usage from the master
# account and all its subaccounts. Can be: `true` (the default) to include usage
# from the master account and all subaccounts or `false` to retrieve usage from
# only the specified account.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(category: :unset, start_date: :unset, end_date: :unset, include_subaccounts: :unset, limit: nil, page_size: nil)
self.stream(
category: category,
start_date: start_date,
end_date: end_date,
include_subaccounts: include_subaccounts,
limit: limit,
page_size: page_size
).entries
end
##
# Streams TodayInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [today.Category] category The {usage
# category}[https://www.twilio.com/docs/usage/api/usage-record#usage-categories]
# of the UsageRecord resources to read. Only UsageRecord resources in the
# specified category are retrieved.
# @param [Date] start_date Only include usage that has occurred on or after this
# date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify
# offsets from the current date, such as: `-30days`, which will set the start date
# to be 30 days before the current date.
# @param [Date] end_date Only include usage that occurred on or before this date.
# Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify
# offsets from the current date, such as: `+30days`, which will set the end date
# to 30 days from the current date.
# @param [Boolean] include_subaccounts Whether to include usage from the master
# account and all its subaccounts. Can be: `true` (the default) to include usage
# from the master account and all subaccounts or `false` to retrieve usage from
# only the specified account.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit.
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(category: :unset, start_date: :unset, end_date: :unset, include_subaccounts: :unset, limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(
category: category,
start_date: start_date,
end_date: end_date,
include_subaccounts: include_subaccounts,
page_size: limits[:page_size],
)
@version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
end
##
# When passed a block, yields TodayInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
def each
limits = @version.read_limits
page = self.page(page_size: limits[:page_size], )
@version.stream(page,
limit: limits[:limit],
page_limit: limits[:page_limit]).each {|x| yield x}
end
##
# Retrieve a single page of TodayInstance records from the API.
# Request is executed immediately.
# @param [today.Category] category The {usage
# category}[https://www.twilio.com/docs/usage/api/usage-record#usage-categories]
# of the UsageRecord resources to read. Only UsageRecord resources in the
# specified category are retrieved.
# @param [Date] start_date Only include usage that has occurred on or after this
# date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify
# offsets from the current date, such as: `-30days`, which will set the start date
# to be 30 days before the current date.
# @param [Date] end_date Only include usage that occurred on or before this date.
# Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify
# offsets from the current date, such as: `+30days`, which will set the end date
# to 30 days from the current date.
# @param [Boolean] include_subaccounts Whether to include usage from the master
# account and all its subaccounts. Can be: `true` (the default) to include usage
# from the master account and all subaccounts or `false` to retrieve usage from
# only the specified account.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of TodayInstance
def page(category: :unset, start_date: :unset, end_date: :unset, include_subaccounts: :unset, page_token: :unset, page_number: :unset, page_size: :unset)
params = Twilio::Values.of({
'Category' => category,
'StartDate' => Twilio.serialize_iso8601_date(start_date),
'EndDate' => Twilio.serialize_iso8601_date(end_date),
'IncludeSubaccounts' => include_subaccounts,
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
})
response = @version.page('GET', @uri, params: params)
TodayPage.new(@version, response, @solution)
end
##
# Retrieve a single page of TodayInstance records from the API.
# Request is executed immediately.
# @param [String] target_url API-generated URL for the requested results page
# @return [Page] Page of TodayInstance
def get_page(target_url)
response = @version.domain.request(
'GET',
target_url
)
TodayPage.new(@version, response, @solution)
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Api.V2010.TodayList>'
end
end
class TodayPage < Page
##
# Initialize the TodayPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [TodayPage] TodayPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of TodayInstance
# @param [Hash] payload Payload response from the API
# @return [TodayInstance] TodayInstance
def get_instance(payload)
TodayInstance.new(@version, payload, account_sid: @solution[:account_sid], )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Api.V2010.TodayPage>'
end
end
class TodayInstance < InstanceResource
##
# Initialize the TodayInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] account_sid A 34 character string that uniquely identifies this
# resource.
# @return [TodayInstance] TodayInstance
def initialize(version, payload, account_sid: nil)
super(version)
# Marshaled Properties
@properties = {
'account_sid' => payload['account_sid'],
'api_version' => payload['api_version'],
'as_of' => payload['as_of'],
'category' => payload['category'],
'count' => payload['count'],
'count_unit' => payload['count_unit'],
'description' => payload['description'],
'end_date' => Twilio.deserialize_iso8601_date(payload['end_date']),
'price' => payload['price'].to_f,
'price_unit' => payload['price_unit'],
'start_date' => Twilio.deserialize_iso8601_date(payload['start_date']),
'subresource_uris' => payload['subresource_uris'],
'uri' => payload['uri'],
'usage' => payload['usage'],
'usage_unit' => payload['usage_unit'],
}
end
##
# @return [String] The SID of the Account accrued the usage
def account_sid
@properties['account_sid']
end
##
# @return [String] The API version used to create the resource
def api_version
@properties['api_version']
end
##
# @return [String] Usage records up to date as of this timestamp
def as_of
@properties['as_of']
end
##
# @return [today.Category] The category of usage
def category
@properties['category']
end
##
# @return [String] The number of usage events
def count
@properties['count']
end
##
# @return [String] The units in which count is measured
def count_unit
@properties['count_unit']
end
##
# @return [String] A plain-language description of the usage category
def description
@properties['description']
end
##
# @return [Date] The last date for which usage is included in the UsageRecord
def end_date
@properties['end_date']
end
##
# @return [String] The total price of the usage
def price
@properties['price']
end
##
# @return [String] The currency in which `price` is measured
def price_unit
@properties['price_unit']
end
##
# @return [Date] The first date for which usage is included in this UsageRecord
def start_date
@properties['start_date']
end
##
# @return [String] A list of related resources identified by their relative URIs
def subresource_uris
@properties['subresource_uris']
end
##
# @return [String] The URI of the resource, relative to `https://api.twilio.com`
def uri
@properties['uri']
end
##
# @return [String] The amount of usage
def usage
@properties['usage']
end
##
# @return [String] The units in which usage is measured
def usage_unit
@properties['usage_unit']
end
##
# Provide a user friendly representation
def to_s
"<Twilio.Api.V2010.TodayInstance>"
end
##
# Provide a detailed, user friendly representation
def inspect
"<Twilio.Api.V2010.TodayInstance>"
end
end
end
end
end
end
end
end
end | {
"content_hash": "15af30801ce559610f9ae3aba0a211b0",
"timestamp": "",
"source": "github",
"line_count": 343,
"max_line_length": 169,
"avg_line_length": 47.62390670553936,
"alnum_prop": 0.5087235996326905,
"repo_name": "philnash/twilio-ruby",
"id": "c086d242cd775c4ef13749cbfacce6e774942e69",
"size": "16475",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/twilio-ruby/rest/api/v2010/account/usage/record/today.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "108"
},
{
"name": "Makefile",
"bytes": "1003"
},
{
"name": "Ruby",
"bytes": "10247081"
}
],
"symlink_target": ""
} |
var searchData=
[
['refinement',['Refinement',['../group___refinement.html',1,'']]]
];
| {
"content_hash": "51af3d8ef5c3e7cbc10cf6cf78dc971e",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 67,
"avg_line_length": 22.25,
"alnum_prop": 0.5955056179775281,
"repo_name": "pbosler/lpm-v2",
"id": "5203aff7e9d6648c92ae6ecef1f01a1b1e323559",
"size": "89",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/html/search/groups_8.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CMake",
"bytes": "7795"
},
{
"name": "Fortran",
"bytes": "1380233"
},
{
"name": "Python",
"bytes": "31894"
},
{
"name": "Shell",
"bytes": "5958"
}
],
"symlink_target": ""
} |
struct PPB_MessageLoop_1_0;
namespace ppapi {
namespace proxy {
class PPAPI_PROXY_EXPORT MessageLoopResource : public MessageLoopShared {
public:
explicit MessageLoopResource(PP_Instance instance);
// Construct the one MessageLoopResource for the main thread. This must be
// invoked on the main thread.
explicit MessageLoopResource(ForMainThread);
~MessageLoopResource() override;
// Resource overrides.
thunk::PPB_MessageLoop_API* AsPPB_MessageLoop_API() override;
// PPB_MessageLoop_API implementation.
int32_t AttachToCurrentThread() override;
int32_t Run() override;
int32_t PostWork(PP_CompletionCallback callback, int64_t delay_ms) override;
int32_t PostQuit(PP_Bool should_destroy) override;
static MessageLoopResource* GetCurrent();
void DetachFromThread();
bool is_main_thread_loop() const {
return is_main_thread_loop_;
}
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner() {
return task_runner_;
}
void set_currently_handling_blocking_message(bool handling_blocking_message) {
currently_handling_blocking_message_ = handling_blocking_message;
}
private:
struct TaskInfo {
tracked_objects::Location from_here;
base::Closure closure;
int64_t delay_ms;
};
// Returns true if the object is associated with the current thread.
bool IsCurrent() const;
// MessageLoopShared implementation.
//
// Handles posting to the message loop if there is one, or the pending queue
// if there isn't.
// NOTE: The given closure will be run *WITHOUT* acquiring the Proxy lock.
// This only makes sense for user code and completely thread-safe
// proxy operations (e.g., MessageLoop::QuitClosure).
void PostClosure(const tracked_objects::Location& from_here,
const base::Closure& closure,
int64_t delay_ms) override;
base::SingleThreadTaskRunner* GetTaskRunner() override;
bool CurrentlyHandlingBlockingMessage() override;
// TLS destructor function.
static void ReleaseMessageLoop(void* value);
// Created when we attach to the current thread, since MessageLoop assumes
// that it's created on the thread it will run on. NULL for the main thread
// loop, since that's owned by somebody else. This is needed for Run and Quit.
// Any time we post tasks, we should post them using task_runner_.
scoped_ptr<base::MessageLoop> loop_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
// Number of invocations of Run currently on the stack.
int nested_invocations_;
// Set to true when the message loop is destroyed to prevent forther
// posting of work.
bool destroyed_;
// Set to true if all message loop invocations should exit and that the
// loop should be destroyed once it reaches the outermost Run invocation.
bool should_destroy_;
bool is_main_thread_loop_;
bool currently_handling_blocking_message_;
// Since we allow tasks to be posted before the message loop is actually
// created (when it's associated with a thread), we keep tasks posted here
// until that happens. Once the loop_ is created, this is unused.
std::vector<TaskInfo> pending_tasks_;
DISALLOW_COPY_AND_ASSIGN(MessageLoopResource);
};
class PPB_MessageLoop_Proxy : public InterfaceProxy {
public:
explicit PPB_MessageLoop_Proxy(Dispatcher* dispatcher);
virtual ~PPB_MessageLoop_Proxy();
static const PPB_MessageLoop_1_0* GetInterface();
private:
DISALLOW_COPY_AND_ASSIGN(PPB_MessageLoop_Proxy);
};
} // namespace proxy
} // namespace ppapi
#endif // PPAPI_PROXY_PPB_MESSAGE_LOOP_PROXY_H_
| {
"content_hash": "80379c03582fc40b81b2751c0cc972a7",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 80,
"avg_line_length": 33.63551401869159,
"alnum_prop": 0.7321478188385663,
"repo_name": "joone/chromium-crosswalk",
"id": "e8213a9820f57ec270777b9dde84c1ee798c2309",
"size": "4279",
"binary": false,
"copies": "9",
"ref": "refs/heads/2016.04.css-round-display-edtior-draft-1",
"path": "ppapi/proxy/ppb_message_loop_proxy.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package CPSC331Assignment4;
import java.lang.NullPointerException;
import java.lang.IndexOutOfBoundsException;
import java.lang.IllegalStateException;
import CPSC331Assignment3.Pair;
/**
*
* Interface for a hash table’s data structure,
* for use in CPSC 331.
* <br />
*
* <p>
* <strong>Interface Invariant:</strong>
* <p>
* <ul>
* <li> Any implementing class will provide the data structure
* that serves as a component of a hash table storing
* key-value pairs, where keys are of type <code>K</code>
* and values are of type <code>V</code>
* </li>
* </ul>
*
* <p>
* <strong>Note:</strong> Any class implementing this interface
* must be used together with a class implementing a hash function.
* If an object in a class implementing this interface is used
* in combination with a consistent hash function — one
* associating the same hash value to a given <code>key</code>
* every time the function is evaluated at this <code>key</code>,
* then an object in a class implementing this interface should
* behave as a hash structure is expected to, that is, it should
* never contain more than one key-value pair for a given key,
* and searches for a given key will successfully find and report
* the key-value pair for it, if one exists.
* </p>
*
* <p>
* This behaviour cannot be guaranteed if this object is combined
* with a hash function that is <i>not</i> consistent (that is,
* if it does not implement a function, at all)
* </p>
*
* <p>
* <strong>Note:</strong>
* In order to allow the efficiency of various hashing
* structures and strategies to be analyzed, various properties
* of this structure can also be reported. Details about this
* are provided in the documentations of the methods that
* this interface provides.
* </p>
*
*/
public interface HashStructure<K, V>
extends Iterable<Pair<K, V>> {
/**
*
* Reports the length of the array that is the main part of this
* hash table (which would also be the maximum size if open hashing
* was being used).
* <br />
*
* <p>
* <strong>Precondition:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The interface invariant is satisfied. </li>
* </ol>
*
* <p>
* <strong>Postcondition:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The hash structure has not been changed, so the interface
* invariant is still satisfied.
* </li>
* <li> The value returned is the length of the array that is
* the main part of the hash structure. For a hash table
* with chaining, this would be equal to the number of
* different linked lists that are used to store key-value
* pairs. For a hash table with open hashing this would
* be equal to the “capacity” of the structure,
* that is, the maximum number of key-value pairs that
* could possibly be stored.
* </li>
* </ol>
*
* @return the length of the array that is the main part of this
* hash table
*
*/
public int numberPositions();
/**
*
* Reports the number of key-value pairs that are currently stored.
* <br />
*
* <p>
* <strong>Precondition:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The interface invariant is satisfied. </li>
* </ol>
*
* <p>
* <strong>Postcondition:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The hash structure has not been changed, so the interface
* invariant is still satisfied.
* </li>
* <li> The value returned is the number of key-value pairs that
* are currently stored in this structure.
* </li>
* </ol>
*
* @return the number of key-value pairs currently stored in
* this hash table
*
*/
public int size();
/**
*
* Reports the maximum number of comparison with keys used
* for a successful search in this table.
* <br />
*
* <p>
* <strong>Precondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The interface invariant is satisfied. </li>
* <li> The structure is not empty, that is, at least
* one key-value pair is stored in it. </li>
* </ol>
*
* <p>
* <strong>Postcondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The hash structure has not been changed, so the interface
* invariant is still satisfied.
* </li>
* <li> The maximum number of comparisons with keys, used for
* a successful search in this table, is returned.
* The manner in which this is defined and computed depends
* on the type of hash structure that is implemented.
* </li>
* </ol>
*
* <p>
* <strong>Precondition 2:</strong>
* </p>
* <ol style = "list-style-type: lower-alpha">
* <li> The interface invariant is satisfied. </li>
* <li> The structure is empty, that is, no key-value pairs
* are stored in it. </li>
* </ol>
*
* <p>
* <strong>Postcondition 2:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The hash structure has not changed, so the interface
* invariant is still satisfied.
* </li>
* <li> An <code>IllegalStateException</code> is thrown
* </li>
* </ol>
*
* @return the maximum number of comparisons with keys used
* for a successful search in this table
* @throws IllegalStateException if the table is empty
*
*/
public int maxAccess();
/**
*
* Reports the expected number of comparisons with keys used
* for a successful search in this table, assuming that one
* searches for each value that is currently stored.
* <br />
*
* <p>
* <strong>Precondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The interface invariant is satisfied. </li>
* <li> The structure is not empty, that is, at least
* one key-value pair is stored in it. </li>
* </ol>
*
* <p>
* <strong>Postcondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The hash structure has not been changed, so the interface
* invariant is still satisfied.
* </li>
* <li> The expected number of comparisons with keys, used for
* a successful search in this table, is returned. It is
* assumed that that all keys (currently in the table)
* are searched for with the same probability, so that this
* value is equal to the sum of the numbers of comparisons
* needed to search for each of the keys, divided by the
* number of keys that are currently stored.
* </li>
* </ol>
*
* <p>
* <strong>Precondition 2:</strong>
* </p>
* <ol style = "list-style-type: lower-alpha">
* <li> The interface invariant is satisfied. </li>
* <li> The structure is empty, that is, no key-value pairs
* are stored in it. </li>
* </ol>
*
* <p>
* <strong>Postcondition 2:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The hash structure has not changed, so the interface
* invariant is still satisfied.
* </li>
* <li> An <code>IllegalStateException</code> is thrown
* </li>
* </ol>
*
*
* @return the expected number of comparisons with keys used
* for a sucessful search
* @throws IllegalStateException if the table is empty
*
*/
public float eSuccess();
/**
*
* Reports the expected number of comparisons (including a
* final comparison with a null key) for an unsuccessful
* search, assuming that the hash value of the given key
* is equal to each of the hash table locations with the
* same probability.
* <br />
*
* <p>
* <strong>Precondition:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The interface invariant is satisfied. </li>
* </ol>
*
* <p>
* <strong>Postcondition:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> The hash structure has not been changed, so the interface
* invariant is still satisfied.
* </li>
* <li> The expected number of comparisons with keys, used for
* an unsuccessful search in this table, is returned. It is
* assumed here, for an unsuccessful search, that the value
* of the hash function (that is, the initial hash table
* position searched) is equal to each of the possible
* hash table positions with the same probability.
* </li>
* </ol>
*
* @return the expected number of comparisons with keys
* (including a null value) for an unsuccessful search
*
*/
public float eFail();
/**
*
* Returns the value corresponding to a given key or null if
* no key-value pair for the given key is currently stored.
* <br />
*
* <p>
* <strong>Precondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is valid, that is, it
* is a nonnegative integer that is less than the number
* of positions in this hash structure </li>
* <li> there is already a key-value pair with the given
* <code>key</code> that would be found by a search in this
* hash structure, assuming that the given <code>location</code>
* is this <code>key</code>’s hash value </li>
* </ol>
*
* <p>
* <strong>Postcondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> the <code>value</code> returned is the value associated with
* the given <code>key</code> in the key-value pair that can
* be found, using the given <code>location</code> as the
* <code>key</code>’s hash value </li>
* </ol>
*
* <p>
* <strong>Precondition 2:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is valid, that is, it
* is a nonnegative integer that is less than the number
* of positions in this hash structure </li>
* <li> there is no key-value pair with the given
* <code>key</code> that would be found by a search in this
* hash structure, assuming that the given <code>location</code>
* is this <code>key</code>’s hash value </li>
* </ol>
*
* <p>
* <strong>Postcondition 2:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> <code>null</code> is returned as output </li>
* </ol>
*
* <p>
* <strong>Precondition 3:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is <code>null</code> </li>
* </ol>
*
* <p>
* <strong>Postcondition 3:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> a <code>NullPointerException</code> is thrown </li>
* </ol>
*
* <p>
* <strong>Precondition 4:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is not valid, that is,
* it is either less than zero or greater than or equal to
* the number of positions in this hash structure </li>
* </ol>
*
* <p>
* <strong>Postcondition 4:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> an <code>IndexOutOfBoundsException</code> is thrown </li>
* </ol>
*
* @param key the key whose value is to be searched for
* @param location the value of the hash function for the
* given key
*
* @return the value mapped to the given key, or <code>null</code>
* if no key-value pair for this key is found
*
* @throws NullPointerException if the given key is null
* @throws IndexOutOfBoundsException is the given key is not
* null, but the given location is
* negative, or greater than or equal to the number of
* positions in this hash structure
*
*/
public V get(K key, int location);
/**
*
* Associates the specified value with the specified key in this
* map, using the specified location as the value of the hash
* function for this key. If the map previously contained a value
* for this key — and the same location has been consistently
* supplied for it, so that this value can be found —
* then the old value is replaced by the input value and the
* the old value is returned as output. A new key-value pair is
* inserted using the given hash table location, and <code>null</code>
* is returned, otherwise
* <br />
*
* <p>
* <strong>Precondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is valid, that is, it
* is a nonnegative integer that is less than the number
* of positions in this hash structure </li>
* <li> there is already a key-value pair with the given
* <code>key</code> that would be found by a search in this
* hash structure, assuming that the given <code>location</code>
* is this <code>key</code>’s hash value </li>
* </ol>
*
* <p>
* <strong>Postcondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the key-value pair, with the given <code>key</code>,
* that could be found assuming that the given
* <code>location</code> is the <code>key</code>’s
* hash value, is replaced by one (at the same location)
* with the same <code>key</code> and with the given
* <code>value</code> </li>
* <li> no other changes are made to the hash strucrure, so
* the interface invariant is still satisfied </li>
* <li> the value returned is the value that was formerly
* associated with the key and that has replaced (in the
* hash structure) with the <code>value</code> supplied
* as input </li>
* </ol>
*
* <p>
* <strong>Precondition 2:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is valid, that is, it
* is a nonnegative integer that is less than the number
* of positions in this hash structure </li>
* <li> there is no key-value pair with the given
* <code>key</code> that would be found by a search in this
* hash structure, assuming that the given <code>location</code>
* is this <code>key</code>’s hash value </li>
* </ol>
*
* <strong>Postcondition 2:</strong>
* <ol style="list-style-type: lower-alpha">
* <li> a key-value pair, with the given <code>key</code>
* and <code>value,</code> is inserted into the structure
* assuming that the given location is the hash value for the
* <code>key</code> </li>
* <li> no other changes are made, so that the interface
* invariant is still satisfied </li>
* <li> <code>null</code> is returned as output </li>
* </ol>
*
* <p>
* <strong>Precondition 3:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> one or both of the given <code>key</code> and the
* given <code>value</code> is <code>null</code> </li>
* </ol>
*
* <p>
* <strong>Postcondition 3:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> a <code>NullPointerException</code> is thrown </li>
* </ol>
*
* <p>
* <strong>Precondition 4:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> and <code>value</code>
* are not <code>null</code> </li>
* <li> the given <code>location</code> is not valid, that is,
* it is either less than zero or greater than or equal to
* the number of positions in this hash structure </li>
* </ol>
*
* <p>
* <strong>Postcondition 4:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> an <code>IndexOutOfBoundsException</code> is thrown </li>
* </ol>
*
* @param key the key whose value is to be updated
* @param location the value of the hash function for this key
* @param value the value to be associated with this key in the
* mapping
*
* @return the value that was formerly associated with this key,
* if one is found using the specified key and location;
* <code>null,</code> otherwise
*
* @throws NullPointerException if the given key or value is null
* @throws IndexOutOfBoundsException if the given key and value
* are not null, but the given location is
* negative, or greater than or equal to the number of positions
* in this structure
*
*/
public V put(K key, int location, V value);
/**
*
* Removes the key-value pair if it is present and can be found
* using the specified location.
* <br />
*
* <p>
* <strong>Precondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is valid, that is, it
* is a nonnegative integer that is less than the number
* of positions in this hash structure </li>
* <li> there is already a key-value pair with the given
* <code>key</code> that would be found by a search in this
* hash structure, assuming that the given <code>location</code>
* is this <code>key</code>’s hash value </li>
* </ol>
*
* <p>
* <strong>Postcondition 1:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the key-value pairing that includes the given
* <code>key</code>, mentioned in the above precondition,
* is removed from the structure, and the value included
* in this pair is returned as output </li>
* <li> no other changes are made to the structure, so the
* interface invariant is still satisfied </li>
* </ol>
*
* <p>
* <strong>Precondition 2:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is valid, that is, it
* is a nonnegative integer that is less than the number
* of positions in this hash structure </li>
* <li> there is no key-value pair with the given
* <code>key</code> that would be found by a search in this
* hash structure, assuming that the given <code>location</code>
* is this <code>key</code>’s hash value </li>
* </ol>
*
* <strong>Postcondition 2:</strong>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> <code>null</code> is returned as output </li>
* </ol>
*
* <p>
* <strong>Precondition 3:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is <code>null</code> </li>
* </ol>
*
* <p>
* <strong>Postcondition 3:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> a <code>NullPointerException</code> is thrown </li>
* </ol>
*
* <p>
* <strong>Precondition 4:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the interface invariant is satisfied </li>
* <li> the given <code>key</code> is not <code>null</code> </li>
* <li> the given <code>location</code> is not valid, that is,
* it is either less than zero or greater than or equal to
* the number of positions in this hash structure </li>
* </ol>
*
* <p>
* <strong>Postcondition 4:</strong>
* </p>
* <ol style="list-style-type: lower-alpha">
* <li> the hash structure is not changed, so the interface
* invariant is still satisfied </li>
* <li> an <code>IndexOutOfBoundsException</code> is thrown </li>
* </ol>
*
* @param key the key whose key-value pair is to removed
* @param location the value of the hash function for this key
*
* @return the value of the key that was found in the mapping using
* the specified key and location, of <code>null</code>
* if no key-value pair was found
*
* @throws NullPointerException if the given key is null
* @throws IndexOutOfBoundsException if the given key and value
* are not null, but the given location is
* negative, or greater than or equal to the number of
* positions in this hash structure
*
*/
public V remove(K key, int location);
}
| {
"content_hash": "f93a8039c3b29437adcf81710c922a1d",
"timestamp": "",
"source": "github",
"line_count": 638,
"max_line_length": 73,
"avg_line_length": 36.21786833855799,
"alnum_prop": 0.601808975635089,
"repo_name": "ahelwer/UofC",
"id": "52e0a2a458c04e33a40aae40b43373de4e8aa756",
"size": "23107",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cpsc331/as5/CPSC331Assignment4/HashStructure.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "89571"
},
{
"name": "C",
"bytes": "44414"
},
{
"name": "C++",
"bytes": "455"
},
{
"name": "Haskell",
"bytes": "22807"
},
{
"name": "Java",
"bytes": "344379"
},
{
"name": "M",
"bytes": "13600"
},
{
"name": "Matlab",
"bytes": "19868"
},
{
"name": "Perl",
"bytes": "274"
},
{
"name": "Prolog",
"bytes": "3572"
},
{
"name": "Python",
"bytes": "29151"
},
{
"name": "TeX",
"bytes": "94864"
}
],
"symlink_target": ""
} |
<?php
class ShareAction extends UserAction{
public $tokenWhere;
public function _initialize() {
parent::_initialize();
$this->canUseFunction('share');
$this->tokenWhere=array('token'=>$this->token);
}
public function set(){
$record=M('Share_set')->where($this->tokenWhere)->find();
if (IS_POST){
$row=array();
$row['score']=intval($_POST['score']);
$row['daylimit']=intval($_POST['daylimit']);
if ($record){
M('Share_set')->where($this->tokenWhere)->save($row);
}else {
$row['token']=$this->token;
M('Share_set')->add($row);
}
$this->success('设置成功');
}else {
if (!$record){
}
$this->assign('record',$record);
$this->assign('tab','set');
$this->display();
}
}
public function records(){
$db=D('Share');
$where['token']=$this->token;
$count=$db->where($where)->count();
$page=new Page($count,25);
$info=$db->where($where)->order('id DESC')->limit($page->firstRow.','.$page->listRows)->select();
$wecha_ids=array();
if ($info){
foreach ($info as $item){
if (!in_array($item['wecha_id'],$wecha_ids)){
array_push($wecha_ids,$item['wecha_id']);
}
}
$users=M('Userinfo')->where(array('wecha_id'=>array('in',$wecha_ids)))->select();
if ($users){
foreach ($users as $useritem){
$users[$useritem['wecha_id']]=$useritem;
}
}
$i=0;
foreach ($info as $item){
$info[$i]['user']=$users[$item['wecha_id']];
$info[$i]['moduleName']=funcDict::moduleName($item['module']);
$i++;
}
}
$this->assign('page',$page->show());
$this->assign('info',$info);
$this->assign('tab','records');
$this->display();
}
public function index(){
$days=7;
$this->assign('days',$days);
$where=array('token'=>$this->token);
$where['time']=array('gt',time()-$days*24*3600);
$where['module']=array('neq','');
$db=M('Share');
$items=$db->where($where)->select();
$datas=array();
if ($items){
foreach ($items as $item){
if (trim($item['module'])){
if (!key_exists($item['module'],$datas)){
$datas[$item['module']]=array('module'=>$item['module'],'count'=>1,'moduleName'=>funcDict::moduleName($item['module']));
}else {
$datas[$item['module']]['count']++;
}
}
}
}
$xml='<chart borderThickness="0" caption="'.$days.'日内分享统计" baseFontColor="666666" baseFont="宋体" baseFontSize="14" bgColor="FFFFFF" bgAlpha="0" showBorder="0" bgAngle="360" pieYScale="90" pieSliceDepth="5" smartLineColor="666666">';
if ($datas){
foreach ($datas as $item){
$xml.='<set label="'.$item['moduleName'].'" value="'.$item['count'].'"/>';
}
}
$xml.='</chart>';
$this->assign('items',$items);
$this->assign('xml',$xml);
//
$this->assign('list',$datas);
$this->assign('listinfo',1);
$this->assign('tab','stastic');
$this->display();
}
}
?> | {
"content_hash": "7b6c60ab1f8294821fffacc3d3a24b89",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 234,
"avg_line_length": 28.686274509803923,
"alnum_prop": 0.550580997949419,
"repo_name": "royalwang/saivi",
"id": "76b4adc66a0c3869299157cdfa210d078957c582",
"size": "2950",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Saivi/Lib/Action/User/ShareAction.class.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "30814"
},
{
"name": "ActionScript",
"bytes": "28251"
},
{
"name": "ApacheConf",
"bytes": "931"
},
{
"name": "CSS",
"bytes": "16883296"
},
{
"name": "HTML",
"bytes": "16526868"
},
{
"name": "Java",
"bytes": "11028"
},
{
"name": "JavaScript",
"bytes": "21292928"
},
{
"name": "Limbo",
"bytes": "6033"
},
{
"name": "PHP",
"bytes": "10997419"
},
{
"name": "Ruby",
"bytes": "2434"
},
{
"name": "Shell",
"bytes": "1414"
},
{
"name": "Smarty",
"bytes": "30131"
}
],
"symlink_target": ""
} |
package org.scalatest
import SharedHelpers._
class SequentialNestedSuiteExecutionSpec extends Spec {
object `the SequentialNestedSuiteExecution trait` {
object `when mixed into a Suite` {
def `should override runNestedSuites such that it calls super.runNestedSuites with the distributor set to None` {
class SuperSuite extends Suite {
@volatile var distributorWasPropagated = false
@volatile var firstNestedSuiteHasBeenRun = false
@volatile var lastNestedSuiteWasRunAfterFirst = false
class FirstSuite extends Suite {
override def run(testName: Option[String], args: Args): Status = {
firstNestedSuiteHasBeenRun = true
if (args.distributor.isDefined)
distributorWasPropagated = true
super.run(testName, args)
}
}
class LastSuite extends Suite {
override def run(testName: Option[String], args: Args): Status = {
if (firstNestedSuiteHasBeenRun)
lastNestedSuiteWasRunAfterFirst = true
super.run(testName, args)
}
}
var distributorWasDefined: Boolean = false
override def nestedSuites = Vector(new FirstSuite, new LastSuite)
override protected def runNestedSuites(args: Args): Status = {
if (args.distributor.isDefined)
distributorWasDefined = true
super.runNestedSuites(args)
}
}
class ParSubSuite extends SuperSuite
class SeqSubSuite extends SuperSuite with SequentialNestedSuiteExecution
val par = new ParSubSuite
val seq = new SeqSubSuite
val parStatus = par.run(None, Args(SilentReporter, distributor = Some(new TestConcurrentDistributor(2))))
parStatus.waitUntilCompleted()
assert(par.distributorWasDefined)
assert(par.distributorWasPropagated)
val seqStatus = seq.run(None, Args(SilentReporter, distributor = Some(new TestConcurrentDistributor(2))))
assert(seqStatus.isCompleted) // When a seqential execution returns, the whole thing should be completed already
assert(!seq.distributorWasDefined)
assert(!seq.distributorWasPropagated)
assert(seq.lastNestedSuiteWasRunAfterFirst)
}
}
}
}
| {
"content_hash": "42f64eadff7a37ad30d79330dbf06e9c",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 120,
"avg_line_length": 44.094339622641506,
"alnum_prop": 0.6636713735558408,
"repo_name": "flicken/scalatest",
"id": "b2ce3e3f93c01b67b0de6fdb8bd0c6e4a3d5fb35",
"size": "2937",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "scalatest-test/src/test/scala/org/scalatest/SequentialNestedSuiteExecutionSpec.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "14110"
},
{
"name": "HTML",
"bytes": "11321"
},
{
"name": "Java",
"bytes": "47034"
},
{
"name": "JavaScript",
"bytes": "19211"
},
{
"name": "Scala",
"bytes": "24339065"
},
{
"name": "Shell",
"bytes": "14579"
}
],
"symlink_target": ""
} |
'''
Convert a music21 object into JSON and send it to the browser for music21j to use.
'''
import unittest
from music21.exceptions21 import Music21Exception
from music21 import freezeThaw
from music21 import stream
supportedDisplayModes = [
'html',
'jsbody',
'jsbodyScript',
'json'
]
def fromObject(thisObject, mode='html', local=False):
'''
returns a string of data for a given Music21Object such as a Score, Note, etc. that
can be displayed in a browser using the music21j package. Called by .show('vexflow').
>>> n = note.Note('C#4')
>>> #_DOCS_SHOW print(vexflow.toMusic21j.fromObject(n))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- for MSIE 10 on Windows 8 -->
<meta http-equiv="X-UA-Compatible" content="requiresActiveX=true"/>
<title>Music21 Fragment</title>
<script data-main='http://web.mit.edu/music21/music21j/src/music21' src='http://web.mit.edu/music21/music21j/ext/require/require.js'></script>
<script>
require(['music21'], function() {
var pickleIn = '{"m21Version": {"py/tuple": [1, 9, 2]}, "stream": {"_mutable": true, "_activeSite": null, "xPosition": null, "' +
'_priority": 0, "_elements": [], "_cache": {}, "definesExplicitPageBreaks": false, "_unlinkedDuration": null, "' +
'id": ..., "_duration": null, "py/object": "music21.stream.Stream", "streamStatus": {"py/object": "music' +
'21.stream.streamStatus.StreamStatus", "_enharmonics": null, "_dirty": null, "_concertPitch": null, "_accidenta' +
'ls": null, "_ties": null, "_rests": null, "_ornaments": null, "_client": null, "_beams": null, "_measures": nu' +
...
'd": null}, "definesExplicitSystemBreaks": false, ...}}';
var jpc = new music21.fromPython.Converter();
streamObj = jpc.run(pickleIn);
streamObj.renderOptions.events.resize = "reflow";
streamObj.appendNewCanvas();
});
</script>
<BLANKLINE>
</head>
<body>
</body>
</html>
'''
conv = VexflowPickler()
conv.mode = mode
conv.useLocal = local
return conv.fromObject(thisObject)
class VexflowPickler(object):
templateHtml = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- for MSIE 10 on Windows 8 -->
<meta http-equiv="X-UA-Compatible" content="requiresActiveX=true"/>
<title>{title}</title>
{loadM21Template}
{jsBodyScript}
</head>
<body>
</body>
</html>
'''
jsBodyScript = '''<script>\n{jsBody}\n</script>'''
jsBody = '''require(['music21'], function() {{
var pickleIn = {pickleOutput};
var jpc = new music21.jsonPickle.Converter();
streamObj = jpc.run(pickleIn);
{callback}
}});'''
loadM21Template = '''<script data-main='{m21URI}' src='{requireURI}'></script>'''
def __init__(self):
self.defaults = {
'pickleOutput' : '{"py/object": "hello"}',
'm21URI' : 'http://web.mit.edu/music21/music21j/src/music21',
'requireURI' :'http://web.mit.edu/music21/music21j/ext/require/require.js',
'callback' :'streamObj.renderOptions.events.resize = "reflow";\n\t\tstreamObj.appendNewCanvas();',
'm21URIlocal' : 'file:///Users/Cuthbert/git/music21j/src/music21',
'requireURIlocal' : 'file:///Users/Cuthbert/git/music21j/ext/require/require.js',
}
self.mode = 'html'
self.useLocal = False
def fromObject(self, thisObject, mode=None):
if mode is None:
mode = self.mode
if (thisObject.isStream is False):
retStream = stream.Stream()
retStream.append(thisObject)
else:
retStream = thisObject
return self.fromStream(retStream, mode=mode)
def splitLongJSON(self, jsonString, chunkSize=110):
allJSONList = []
for i in range(0, len(jsonString), chunkSize):
allJSONList.append('\'' + jsonString[i:i+chunkSize] + '\'')
return ' + \n '.join(allJSONList)
def getLoadTemplate(self, urls=None):
'''
Gets the <script> tag for loading music21 from require.js
>>> vfp = vexflow.toMusic21j.VexflowPickler()
>>> vfp.getLoadTemplate()
"<script data-main='http://web.mit.edu/music21/music21j/src/music21' src='http://web.mit.edu/music21/music21j/ext/require/require.js'></script>"
>>> d = {'m21URI': 'file:///tmp/music21', 'requireURI': 'http://requirejs.com/require.js'}
>>> vfp.getLoadTemplate(d)
"<script data-main='file:///tmp/music21' src='http://requirejs.com/require.js'></script>"
'''
if urls is None:
urls = self.defaults
if self.useLocal is False:
loadM21formatted = self.loadM21Template.format(m21URI = urls['m21URI'],
requireURI = urls['requireURI'],)
else:
loadM21formatted = self.loadM21Template.format(m21URI = urls['m21URIlocal'],
requireURI = urls['requireURIlocal'],)
return loadM21formatted
def getJSBodyScript(self, dataSplit, defaults = None):
'''
Get the <script>...</script> tag to render the JSON
>>> vfp = vexflow.toMusic21j.VexflowPickler()
>>> print(vfp.getJSBodyScript('{"hi": "hello"}'))
<script>
require(['music21'], function() {
var pickleIn = {"hi": "hello"};
var jpc = new music21.jsonPickle.Converter();
streamObj = jpc.run(pickleIn);
streamObj.renderOptions.events.resize = "reflow";
streamObj.appendNewCanvas();
});
</script>
'''
if defaults is None:
defaults = self.defaults
jsBody = self.getJSBody(dataSplit, defaults)
jsBodyScript = self.jsBodyScript.format(jsBody = jsBody)
return jsBodyScript
def getJSBody(self, dataSplit, defaults = None):
'''
Get the javascript code without the <script> tags to render the JSON
>>> vfp = vexflow.toMusic21j.VexflowPickler()
>>> print(vfp.getJSBody('{"hi": "hello"}'))
require(['music21'], function() {
var pickleIn = {"hi": "hello"};
var jpc = new music21.jsonPickle.Converter();
streamObj = jpc.run(pickleIn);
streamObj.renderOptions.events.resize = "reflow";
streamObj.appendNewCanvas();
});
'''
if defaults is None:
d = self.defaults
else:
d = defaults
jsBody = self.jsBody.format(pickleOutput = dataSplit,
callback = d['callback'])
return jsBody
def getHTML(self, dataSplit, title=None, defaults=None):
'''
Get the complete HTML page to pass to the browser:
>>> vfp = vexflow.toMusic21j.VexflowPickler()
>>> print(vfp.getHTML('{"hi": "hello"}', 'myPiece'))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- for MSIE 10 on Windows 8 -->
<meta http-equiv="X-UA-Compatible" content="requiresActiveX=true"/>
<title>myPiece</title>
<script data-main='http://web.mit.edu/music21/music21j/src/music21' src='http://web.mit.edu/music21/music21j/ext/require/require.js'></script>
<script>
require(['music21'], function() {
var pickleIn = {"hi": "hello"};
var jpc = new music21.jsonPickle.Converter();
streamObj = jpc.run(pickleIn);
streamObj.renderOptions.events.resize = "reflow";
streamObj.appendNewCanvas();
});
</script>
</head>
<body>
</body>
</html>
'''
if defaults is None:
d = self.defaults
else:
d = defaults
loadM21Formatted = self.getLoadTemplate(d)
jsBodyScript = self.getJSBodyScript(dataSplit, d)
formatted = self.templateHtml.format(title = title,
loadM21Template=loadM21Formatted,
jsBodyScript=jsBodyScript)
return formatted
def fromStream(self, thisStream, mode=None):
if mode is None:
mode = self.mode
if (thisStream.metadata is not None and thisStream.metadata.title != ""):
title = thisStream.metadata.title
else:
title = "Music21 Fragment"
sf = freezeThaw.StreamFreezer(thisStream)
## recursive data structures will be expanded up to a high depth -- make sure there are none...
data = sf.writeStr(fmt='jsonpickle')
dataSplit = self.splitLongJSON(data)
if mode == 'json':
return data
elif mode == 'jsonSplit':
return dataSplit
elif mode == 'jsbody':
return self.getJSBody(dataSplit)
elif mode == 'jsbodyScript':
return self.getJSBodyScript(dataSplit)
elif mode == 'html':
return self.getHTML(dataSplit, title)
else:
raise VexflowToM21JException("Cannot deal with mode: %r" % mode)
class VexflowToM21JException(Music21Exception):
pass
class Test(unittest.TestCase):
def runTest(self):
pass
def testDummy(self):
pass
class TestExternal(unittest.TestCase):
def runTest(self):
pass
def testCuthbertLocal(self):
'''
test a local version of this mess...
'''
from music21 import corpus, environment
environLocal = environment.Environment()
s = corpus.parse('luca/gloria').measures(1,19)
#s = corpus.parse('beethoven/opus18no1', 2).parts[0].measures(4,10)
vfp = VexflowPickler()
vfp.defaults['m21URI'] = 'file:///Users/Cuthbert/git/music21j/src/music21'
vfp.defaults['requireURI'] = 'file:///Users/Cuthbert/git/music21j/ext/require/require.js'
data = vfp.fromObject(s)
fp = environLocal.getTempFile('.html')
with open(fp, 'w') as f:
f.write(data)
environLocal.launch('vexflow', fp)
if __name__ == "__main__":
import music21
music21.mainTest(Test)
# from music21 import note, clef, meter
# s = stream.Measure()
# s.insert(0, clef.TrebleClef())
# s.insert(0, meter.TimeSignature('1/4'))
# n = note.Note()
# n.duration.quarterLength = 1/3.
# s.repeatAppend(n, 3)
# p = stream.Part()
# p.repeatAppend(s, 2)
# p.show('vexflow', local=True)
#
#s.show('vexflow')
| {
"content_hash": "d66fb678feec8f03c19f3a93e35d5e22",
"timestamp": "",
"source": "github",
"line_count": 297,
"max_line_length": 154,
"avg_line_length": 39.67003367003367,
"alnum_prop": 0.5576302834832796,
"repo_name": "arnavd96/Cinemiezer",
"id": "6384f3ce95c6ca623403d707e0ffb7f38c308093",
"size": "12314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "myvenv/lib/python3.4/site-packages/music21/vexflow/toMusic21j.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "300501"
},
{
"name": "C++",
"bytes": "14430"
},
{
"name": "CSS",
"bytes": "105126"
},
{
"name": "FORTRAN",
"bytes": "3200"
},
{
"name": "HTML",
"bytes": "290903"
},
{
"name": "JavaScript",
"bytes": "154747"
},
{
"name": "Jupyter Notebook",
"bytes": "558334"
},
{
"name": "Objective-C",
"bytes": "567"
},
{
"name": "Python",
"bytes": "37092739"
},
{
"name": "Shell",
"bytes": "3668"
},
{
"name": "TeX",
"bytes": "1527"
}
],
"symlink_target": ""
} |
<?php
namespace Fenchy\MessageBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
class RequestMessageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('content', NULL, array('label' => 'message.content'))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Fenchy\MessageBundle\Entity\Message'
));
}
public function getName()
{
return 'fenchy_message_request';
}
}
| {
"content_hash": "0450c31796e3b25fd7775facfb7ca67a",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 76,
"avg_line_length": 24.548387096774192,
"alnum_prop": 0.6898817345597897,
"repo_name": "PollyandBob/PollyAndBob",
"id": "726d26f0b352e31b2e642b7371e2358e2113b822",
"size": "761",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Fenchy/Fenchy/MessageBundle/Form/RequestMessageType.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "922025"
},
{
"name": "JavaScript",
"bytes": "1099915"
},
{
"name": "PHP",
"bytes": "2967675"
},
{
"name": "Shell",
"bytes": "385"
}
],
"symlink_target": ""
} |
<jqxChart #myChart
[width]="850" [height]="500"
[title]="'EU Population between 2003 and 2014'"
[description]="'data source: Eurostat'"
[showLegend]="false" [enableAnimations]="true" [padding]="padding"
[titlePadding]="titlePadding" [source]="data" [xAxis]="xAxis"
[valueAxis]="valueAxis" [seriesGroups]="seriesGroups" [colorScheme]="'scheme06'">
</jqxChart> | {
"content_hash": "102162b80bd2aaf7b641c5ece148bdbd",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 85,
"avg_line_length": 47.875,
"alnum_prop": 0.6736292428198434,
"repo_name": "UCF/IKM-APIM",
"id": "95ffdbacf3ed2182143098d8910460e4deaa0382",
"size": "385",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "jqwidgets/demos/angular/app/chart/waterfallseries/app.component.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "449"
},
{
"name": "CSS",
"bytes": "788651"
},
{
"name": "HTML",
"bytes": "6501313"
},
{
"name": "JavaScript",
"bytes": "2791022"
},
{
"name": "PHP",
"bytes": "2129306"
},
{
"name": "TypeScript",
"bytes": "1426843"
}
],
"symlink_target": ""
} |
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {User} from './user';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
url: string;
users: User[];
constructor(private _http: Http) {
this.url = "http://jsonplaceholder.typicode.com/users";
}
getUsers() {
console.log('getUsers');
return this._http.get(this.url)
.map(res => res.json());
}
//postImage() { }
} | {
"content_hash": "fc952dbd9404837e8f4e8f99846c8c9c",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 63,
"avg_line_length": 19.64,
"alnum_prop": 0.5906313645621182,
"repo_name": "Schludnik/PacketwerkAufgabe",
"id": "47c66c330d61c773f9b553a38ae2875f317885dc",
"size": "493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/app/user/user.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "296"
},
{
"name": "HTML",
"bytes": "2495"
},
{
"name": "JavaScript",
"bytes": "3432"
},
{
"name": "TypeScript",
"bytes": "2775"
}
],
"symlink_target": ""
} |
#ifndef _CRYPT_H
#define _CRYPT_H 1
#include <features.h>
__BEGIN_DECLS
/* Encrypt at most 8 characters from KEY using salt to perturb DES. */
extern char *crypt (const char *__key, const char *__salt)
__THROW __nonnull ((1, 2));
/* Setup DES tables according KEY. */
extern void setkey (const char *__key) __THROW __nonnull ((1));
/* Encrypt data in BLOCK in place if EDFLAG is zero; otherwise decrypt
block in place. */
extern void encrypt (char *__glibc_block, int __edflag)
__THROW __nonnull ((1));
#ifdef __USE_GNU
/* Reentrant versions of the functions above. The additional argument
points to a structure where the results are placed in. */
struct crypt_data
{
char keysched[16 * 8];
char sb0[32768];
char sb1[32768];
char sb2[32768];
char sb3[32768];
/* end-of-aligment-critical-data */
char crypt_3_buf[14];
char current_salt[2];
long int current_saltbits;
int direction, initialized;
};
extern char *crypt_r (const char *__key, const char *__salt,
struct crypt_data * __restrict __data)
__THROW __nonnull ((1, 2, 3));
extern void setkey_r (const char *__key,
struct crypt_data * __restrict __data)
__THROW __nonnull ((1, 2));
extern void encrypt_r (char *__glibc_block, int __edflag,
struct crypt_data * __restrict __data)
__THROW __nonnull ((1, 3));
#endif
__END_DECLS
#endif /* crypt.h */
| {
"content_hash": "282d6b80bb7601608ae8c29bf76e15e4",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 71,
"avg_line_length": 26.296296296296298,
"alnum_prop": 0.6295774647887324,
"repo_name": "JahodaPavel/Recipe_Manager",
"id": "e29e1ef8b786225af643ec21acfe6bb690a7de26",
"size": "2259",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "lib/libpq/crypt.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2180799"
},
{
"name": "C++",
"bytes": "720637"
},
{
"name": "CMake",
"bytes": "13314"
},
{
"name": "Makefile",
"bytes": "12716"
},
{
"name": "Shell",
"bytes": "633"
}
],
"symlink_target": ""
} |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Seno Aiko
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 338709;
var summary = 'ReadOnly properties should not be overwritten by using ' +
'Object and try..throw..catch';
var actual = '';
var expect = '';
printBugNumber(BUGNUMBER);
printStatus (summary);
Object = function () { return Math };
expect = Math.LN2;
try
{
throw 1990;
}
catch (LN2)
{
}
actual = Math.LN2;
print("Math.LN2 = " + Math.LN2)
reportCompare(expect, actual, summary);
var s = new String("abc");
Object = function () { return s };
expect = s.length;
try
{
throw -8
}
catch (length)
{
}
actual = s.length;
print("length of '" + s + "' = " + s.length)
reportCompare(expect, actual, summary);
var re = /xy/m;
Object = function () { return re };
expect = re.multiline;
try
{
throw false
}
catch (multiline)
{
}
actual = re.multiline;
print("re.multiline = " + re.multiline)
reportCompare(expect, actual, summary);
if ("document" in this) {
// Let the document be its own documentElement.
Object = function () { return document }
expect = document.documentElement + '';
try
{
throw document;
}
catch (documentElement)
{
}
actual = document.documentElement + '';
print("document.documentElement = " + document.documentElement)
}
else
Object = this.constructor
reportCompare(expect, actual, summary);
| {
"content_hash": "2a9c9892fa124e0aecc4de96ff9134d5",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 79,
"avg_line_length": 29.81132075471698,
"alnum_prop": 0.6781645569620253,
"repo_name": "daejunpark/jsaf",
"id": "3145a4a70fe3d3eebdf136243fa8511723abe511",
"size": "3160",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "tests/interpreter_mozilla_tests/NPY/js1_5/Object/regress-338709.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "379"
},
{
"name": "C",
"bytes": "59067"
},
{
"name": "C++",
"bytes": "13294"
},
{
"name": "CSS",
"bytes": "9351891"
},
{
"name": "Emacs Lisp",
"bytes": "9812"
},
{
"name": "HTML",
"bytes": "19106074"
},
{
"name": "Jasmin",
"bytes": "46"
},
{
"name": "Java",
"bytes": "375421"
},
{
"name": "JavaScript",
"bytes": "51177272"
},
{
"name": "Makefile",
"bytes": "3558"
},
{
"name": "Objective-C",
"bytes": "345276"
},
{
"name": "Objective-J",
"bytes": "4500028"
},
{
"name": "PHP",
"bytes": "12684"
},
{
"name": "Perl",
"bytes": "5278"
},
{
"name": "Python",
"bytes": "75059"
},
{
"name": "Ruby",
"bytes": "22932"
},
{
"name": "Scala",
"bytes": "5542753"
},
{
"name": "Shell",
"bytes": "91018"
},
{
"name": "VimL",
"bytes": "6985"
},
{
"name": "XML",
"bytes": "1288109"
}
],
"symlink_target": ""
} |
from twisted.internet.defer import Deferred
def send_poem(d):
print('Sending poem')
d.callback('Once upon a midnight dreary')
def get_poem():
"""Return a poem 5 seconds later."""
def canceler(d):
# They don't want the poem anymore, so cancel the delayed call
delayed_call.cancel()
# At this point we have three choices:
# 1. Do nothing, and the deferred will fire the errback
# chain with CancelledError.
# 2. Fire the errback chain with a different error.
# 3. Fire the callback chain with an alternative result.
d = Deferred(canceler)
from twisted.internet import reactor
delayed_call = reactor.callLater(5, send_poem, d)
return d
def got_poem(poem):
print('I got a poem:', poem)
def poem_error(err):
print('get_poem failed:', err)
def main():
from twisted.internet import reactor
reactor.callLater(10, reactor.stop) # stop the reactor in 10 seconds
d = get_poem()
d.addCallbacks(got_poem, poem_error)
reactor.callLater(2, d.cancel) # cancel after 2 seconds
reactor.run()
main()
| {
"content_hash": "26ac964d2123dc2f5867612d4d284931",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 72,
"avg_line_length": 25.044444444444444,
"alnum_prop": 0.6512866015971606,
"repo_name": "jdavisp3/twisted-intro",
"id": "7e88e54cd1f6c8698f6dba58ae2ea668c96716e2",
"size": "1127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deferred-cancel/defer-cancel-11.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Erlang",
"bytes": "2523"
},
{
"name": "Haskell",
"bytes": "3262"
},
{
"name": "Makefile",
"bytes": "137"
},
{
"name": "Python",
"bytes": "118095"
},
{
"name": "Shell",
"bytes": "86"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.devicefarm.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.devicefarm.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* TagResourceRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class TagResourceRequestProtocolMarshaller implements Marshaller<Request<TagResourceRequest>, TagResourceRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).operationIdentifier("DeviceFarm_20150623.TagResource")
.serviceName("AWSDeviceFarm").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public TagResourceRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<TagResourceRequest> marshall(TagResourceRequest tagResourceRequest) {
if (tagResourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<TagResourceRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
tagResourceRequest);
protocolMarshaller.startMarshalling();
TagResourceRequestMarshaller.getInstance().marshall(tagResourceRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| {
"content_hash": "b944ce75dab6ed51f1c7f5997b1e10d7",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 159,
"avg_line_length": 39.78846153846154,
"alnum_prop": 0.7573707104881585,
"repo_name": "aws/aws-sdk-java",
"id": "d887e707401bfc0698912a0e2771ef5048b48308",
"size": "2649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/transform/TagResourceRequestProtocolMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
class Google_Service_Compute_NodeTemplatesScopedList extends Google_Collection
{
protected $collection_key = 'nodeTemplates';
protected $nodeTemplatesType = 'Google_Service_Compute_NodeTemplate';
protected $nodeTemplatesDataType = 'array';
protected $warningType = 'Google_Service_Compute_NodeTemplatesScopedListWarning';
protected $warningDataType = '';
/**
* @param Google_Service_Compute_NodeTemplate[]
*/
public function setNodeTemplates($nodeTemplates)
{
$this->nodeTemplates = $nodeTemplates;
}
/**
* @return Google_Service_Compute_NodeTemplate[]
*/
public function getNodeTemplates()
{
return $this->nodeTemplates;
}
/**
* @param Google_Service_Compute_NodeTemplatesScopedListWarning
*/
public function setWarning(Google_Service_Compute_NodeTemplatesScopedListWarning $warning)
{
$this->warning = $warning;
}
/**
* @return Google_Service_Compute_NodeTemplatesScopedListWarning
*/
public function getWarning()
{
return $this->warning;
}
}
| {
"content_hash": "dbdfff040da06dfcb18cc2df598221dd",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 92,
"avg_line_length": 25.9,
"alnum_prop": 0.722007722007722,
"repo_name": "bshaffer/google-api-php-client-services",
"id": "8bd7dd8580c976c524622cdd904bdaa4b772b16c",
"size": "1626",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Google/Service/Compute/NodeTemplatesScopedList.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "9540154"
}
],
"symlink_target": ""
} |
/*
* The Plaid API
*
* The Plaid REST API. Please see https://plaid.com/docs/api for more details.
*
* API version: 2020-09-14_1.205.3
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package plaid
import (
"encoding/json"
"fmt"
)
// IndividualWatchlistCode Shorthand identifier for a specific screening list for individuals.
type IndividualWatchlistCode string
var _ = fmt.Printf
// List of IndividualWatchlistCode
const (
INDIVIDUALWATCHLISTCODE_AU_CON IndividualWatchlistCode = "AU_CON"
INDIVIDUALWATCHLISTCODE_CA_CON IndividualWatchlistCode = "CA_CON"
INDIVIDUALWATCHLISTCODE_EU_CON IndividualWatchlistCode = "EU_CON"
INDIVIDUALWATCHLISTCODE_IZ_CIA IndividualWatchlistCode = "IZ_CIA"
INDIVIDUALWATCHLISTCODE_IZ_IPL IndividualWatchlistCode = "IZ_IPL"
INDIVIDUALWATCHLISTCODE_IZ_PEP IndividualWatchlistCode = "IZ_PEP"
INDIVIDUALWATCHLISTCODE_IZ_UNC IndividualWatchlistCode = "IZ_UNC"
INDIVIDUALWATCHLISTCODE_UK_HMC IndividualWatchlistCode = "UK_HMC"
INDIVIDUALWATCHLISTCODE_US_DPL IndividualWatchlistCode = "US_DPL"
INDIVIDUALWATCHLISTCODE_US_DTC IndividualWatchlistCode = "US_DTC"
INDIVIDUALWATCHLISTCODE_US_FBI IndividualWatchlistCode = "US_FBI"
INDIVIDUALWATCHLISTCODE_US_FSE IndividualWatchlistCode = "US_FSE"
INDIVIDUALWATCHLISTCODE_US_ISN IndividualWatchlistCode = "US_ISN"
INDIVIDUALWATCHLISTCODE_US_MBC IndividualWatchlistCode = "US_MBC"
INDIVIDUALWATCHLISTCODE_US_PLC IndividualWatchlistCode = "US_PLC"
INDIVIDUALWATCHLISTCODE_US_SDN IndividualWatchlistCode = "US_SDN"
INDIVIDUALWATCHLISTCODE_US_SSI IndividualWatchlistCode = "US_SSI"
INDIVIDUALWATCHLISTCODE_SG_SOF IndividualWatchlistCode = "SG_SOF"
INDIVIDUALWATCHLISTCODE_TR_TWL IndividualWatchlistCode = "TR_TWL"
INDIVIDUALWATCHLISTCODE_TR_DFD IndividualWatchlistCode = "TR_DFD"
INDIVIDUALWATCHLISTCODE_TR_FOR IndividualWatchlistCode = "TR_FOR"
INDIVIDUALWATCHLISTCODE_TR_WMD IndividualWatchlistCode = "TR_WMD"
)
var allowedIndividualWatchlistCodeEnumValues = []IndividualWatchlistCode{
"AU_CON",
"CA_CON",
"EU_CON",
"IZ_CIA",
"IZ_IPL",
"IZ_PEP",
"IZ_UNC",
"UK_HMC",
"US_DPL",
"US_DTC",
"US_FBI",
"US_FSE",
"US_ISN",
"US_MBC",
"US_PLC",
"US_SDN",
"US_SSI",
"SG_SOF",
"TR_TWL",
"TR_DFD",
"TR_FOR",
"TR_WMD",
}
func (v *IndividualWatchlistCode) UnmarshalJSON(src []byte) error {
var value string
err := json.Unmarshal(src, &value)
if err != nil {
return err
}
enumTypeValue := IndividualWatchlistCode(value)
*v = enumTypeValue
return nil
}
// NewIndividualWatchlistCodeFromValue returns a pointer to a valid IndividualWatchlistCode
// for the value passed as argument, or an error if the value passed is not allowed by the enum
func NewIndividualWatchlistCodeFromValue(v string) (*IndividualWatchlistCode, error) {
ev := IndividualWatchlistCode(v)
return &ev, nil
}
// IsValid return true if the value is valid for the enum, false otherwise
func (v IndividualWatchlistCode) IsValid() bool {
for _, existing := range allowedIndividualWatchlistCodeEnumValues {
if existing == v {
return true
}
}
return false
}
// Ptr returns reference to IndividualWatchlistCode value
func (v IndividualWatchlistCode) Ptr() *IndividualWatchlistCode {
return &v
}
type NullableIndividualWatchlistCode struct {
value *IndividualWatchlistCode
isSet bool
}
func (v NullableIndividualWatchlistCode) Get() *IndividualWatchlistCode {
return v.value
}
func (v *NullableIndividualWatchlistCode) Set(val *IndividualWatchlistCode) {
v.value = val
v.isSet = true
}
func (v NullableIndividualWatchlistCode) IsSet() bool {
return v.isSet
}
func (v *NullableIndividualWatchlistCode) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableIndividualWatchlistCode(val *IndividualWatchlistCode) *NullableIndividualWatchlistCode {
return &NullableIndividualWatchlistCode{value: val, isSet: true}
}
func (v NullableIndividualWatchlistCode) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableIndividualWatchlistCode) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
| {
"content_hash": "272067b2e6fd8e2c2372258af300d7ad",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 104,
"avg_line_length": 27.972789115646258,
"alnum_prop": 0.7711575875486382,
"repo_name": "plaid/plaid-go",
"id": "651e1c872c1cccc123288cb80905e093b2acf638",
"size": "4112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plaid/model_individual_watchlist_code.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "129"
},
{
"name": "Go",
"bytes": "61884"
},
{
"name": "Makefile",
"bytes": "114"
},
{
"name": "Mustache",
"bytes": "46930"
}
],
"symlink_target": ""
} |
#ifndef _RTE_OCTEONTX_ZIP_VF_H_
#define _RTE_OCTEONTX_ZIP_VF_H_
#include <unistd.h>
#include <rte_bus_pci.h>
#include <rte_comp.h>
#include <rte_compressdev.h>
#include <rte_compressdev_pmd.h>
#include <rte_malloc.h>
#include <rte_memory.h>
#include <rte_spinlock.h>
#include <zip_regs.h>
extern int octtx_zip_logtype_driver;
/* ZIP VF Control/Status registers (CSRs): */
/* VF_BAR0: */
#define ZIP_VQ_ENA (0x10)
#define ZIP_VQ_SBUF_ADDR (0x20)
#define ZIP_VF_PF_MBOXX(x) (0x400 | (x)<<3)
#define ZIP_VQ_DOORBELL (0x1000)
/**< Vendor ID */
#define PCI_VENDOR_ID_CAVIUM 0x177D
/**< PCI device id of ZIP VF */
#define PCI_DEVICE_ID_OCTEONTX_ZIPVF 0xA037
/* maximum number of zip vf devices */
#define ZIP_MAX_VFS 8
/* max size of one chunk */
#define ZIP_MAX_CHUNK_SIZE 8192
/* each instruction is fixed 128 bytes */
#define ZIP_CMD_SIZE 128
#define ZIP_CMD_SIZE_WORDS (ZIP_CMD_SIZE >> 3) /* 16 64_bit words */
/* size of next chunk buffer pointer */
#define ZIP_MAX_NCBP_SIZE 8
/* size of instruction queue in units of instruction size */
#define ZIP_MAX_NUM_CMDS ((ZIP_MAX_CHUNK_SIZE - ZIP_MAX_NCBP_SIZE) / \
ZIP_CMD_SIZE) /* 63 */
/* size of instruct queue in bytes */
#define ZIP_MAX_CMDQ_SIZE ((ZIP_MAX_NUM_CMDS * ZIP_CMD_SIZE) + \
ZIP_MAX_NCBP_SIZE)/* ~8072ull */
#define ZIP_BUF_SIZE 256
#define ZIP_SGPTR_ALIGN 16
#define ZIP_CMDQ_ALIGN 128
#define MAX_SG_LEN ((ZIP_BUF_SIZE - ZIP_SGPTR_ALIGN) / sizeof(void *))
/**< ZIP PMD specified queue pairs */
#define ZIP_MAX_VF_QUEUE 1
#define ZIP_ALIGN_ROUNDUP(x, _align) \
((_align) * (((x) + (_align) - 1) / (_align)))
/**< ZIP PMD device name */
#define COMPRESSDEV_NAME_ZIP_PMD compress_octeonx
#define ZIP_PMD_LOG(level, fmt, args...) \
rte_log(RTE_LOG_ ## level, \
octtx_zip_logtype_driver, "%s(): "fmt "\n", \
__func__, ##args)
#define ZIP_PMD_INFO(fmt, args...) \
ZIP_PMD_LOG(INFO, fmt, ## args)
#define ZIP_PMD_ERR(fmt, args...) \
ZIP_PMD_LOG(ERR, fmt, ## args)
/* resources required to process stream */
enum NUM_BUFS_PER_STREAM {
RES_BUF = 0,
CMD_BUF,
HASH_CTX_BUF,
DECOMP_CTX_BUF,
IN_DATA_BUF,
OUT_DATA_BUF,
HISTORY_DATA_BUF,
MAX_BUFS_PER_STREAM
};
struct zip_stream;
struct zipvf_qp;
/* Algorithm handler function prototype */
typedef int (*comp_func_t)(struct rte_comp_op *op,
struct zipvf_qp *qp, struct zip_stream *zstrm);
/**
* ZIP private stream structure
*/
struct zip_stream {
union zip_inst_s *inst;
/* zip instruction pointer */
comp_func_t func;
/* function to process comp operation */
void *bufs[MAX_BUFS_PER_STREAM];
} __rte_cache_aligned;
/**
* ZIP instruction Queue
*/
struct zipvf_cmdq {
rte_spinlock_t qlock;
/* queue lock */
uint64_t *sw_head;
/* pointer to start of 8-byte word length queue-head */
uint8_t *va;
/* pointer to instruction queue virtual address */
rte_iova_t iova;
/* iova addr of cmdq head*/
};
/**
* ZIP device queue structure
*/
struct zipvf_qp {
struct zipvf_cmdq cmdq;
/* Hardware instruction queue structure */
struct rte_ring *processed_pkts;
/* Ring for placing processed packets */
struct rte_compressdev_stats qp_stats;
/* Queue pair statistics */
uint16_t id;
/* Queue Pair Identifier */
const char *name;
/* Unique Queue Pair Name */
struct zip_vf *vf;
/* pointer to device, queue belongs to */
} __rte_cache_aligned;
/**
* ZIP VF device structure.
*/
struct zip_vf {
int vfid;
/* vf index */
struct rte_pci_device *pdev;
/* pci device */
void *vbar0;
/* CSR base address for underlying BAR0 VF.*/
uint64_t dom_sdom;
/* Storing mbox domain and subdomain id for app rerun*/
uint32_t max_nb_queue_pairs;
/* pointer to device qps */
struct rte_mempool *zip_mp;
/* pointer to pools */
} __rte_cache_aligned;
static inline void
zipvf_prepare_in_buf(struct zip_stream *zstrm, struct rte_comp_op *op)
{
uint32_t offset, inlen;
struct rte_mbuf *m_src;
union zip_inst_s *inst = zstrm->inst;
inlen = op->src.length;
offset = op->src.offset;
m_src = op->m_src;
/* Prepare direct input data pointer */
inst->s.dg = 0;
inst->s.inp_ptr_addr.s.addr =
rte_pktmbuf_iova_offset(m_src, offset);
inst->s.inp_ptr_ctl.s.length = inlen;
}
static inline void
zipvf_prepare_out_buf(struct zip_stream *zstrm, struct rte_comp_op *op)
{
uint32_t offset;
struct rte_mbuf *m_dst;
union zip_inst_s *inst = zstrm->inst;
offset = op->dst.offset;
m_dst = op->m_dst;
/* Prepare direct input data pointer */
inst->s.ds = 0;
inst->s.out_ptr_addr.s.addr =
rte_pktmbuf_iova_offset(m_dst, offset);
inst->s.totaloutputlength = rte_pktmbuf_pkt_len(m_dst) -
op->dst.offset;
inst->s.out_ptr_ctl.s.length = inst->s.totaloutputlength;
}
static inline void
zipvf_prepare_cmd_stateless(struct rte_comp_op *op, struct zip_stream *zstrm)
{
union zip_inst_s *inst = zstrm->inst;
/* set flush flag to always 1*/
inst->s.ef = 1;
if (inst->s.op == ZIP_OP_E_DECOMP)
inst->s.sf = 1;
else
inst->s.sf = 0;
/* Set input checksum */
inst->s.adlercrc32 = op->input_chksum;
/* Prepare gather buffers */
zipvf_prepare_in_buf(zstrm, op);
zipvf_prepare_out_buf(zstrm, op);
}
#ifdef ZIP_DBG
static inline void
zip_dump_instruction(void *inst)
{
union zip_inst_s *cmd83 = (union zip_inst_s *)inst;
printf("####### START ########\n");
printf("doneint:%d totaloutputlength:%d\n", cmd83->s.doneint,
cmd83->s.totaloutputlength);
printf("exnum:%d iv:%d exbits:%d hmif:%d halg:%d\n", cmd83->s.exn,
cmd83->s.iv, cmd83->s.exbits, cmd83->s.hmif, cmd83->s.halg);
printf("flush:%d speed:%d cc:%d\n", cmd83->s.sf,
cmd83->s.ss, cmd83->s.cc);
printf("eof:%d bof:%d op:%d dscatter:%d dgather:%d hgather:%d\n",
cmd83->s.ef, cmd83->s.bf, cmd83->s.op, cmd83->s.ds,
cmd83->s.dg, cmd83->s.hg);
printf("historylength:%d adler32:%d\n", cmd83->s.historylength,
cmd83->s.adlercrc32);
printf("ctx_ptr.addr:0x%"PRIx64"\n", cmd83->s.ctx_ptr_addr.s.addr);
printf("ctx_ptr.len:%d\n", cmd83->s.ctx_ptr_ctl.s.length);
printf("history_ptr.addr:0x%"PRIx64"\n", cmd83->s.his_ptr_addr.s.addr);
printf("history_ptr.len:%d\n", cmd83->s.his_ptr_ctl.s.length);
printf("inp_ptr.addr:0x%"PRIx64"\n", cmd83->s.inp_ptr_addr.s.addr);
printf("inp_ptr.len:%d\n", cmd83->s.inp_ptr_ctl.s.length);
printf("out_ptr.addr:0x%"PRIx64"\n", cmd83->s.out_ptr_addr.s.addr);
printf("out_ptr.len:%d\n", cmd83->s.out_ptr_ctl.s.length);
printf("result_ptr.len:%d\n", cmd83->s.res_ptr_ctl.s.length);
printf("####### END ########\n");
}
#endif
int
zipvf_create(struct rte_compressdev *compressdev);
int
zipvf_destroy(struct rte_compressdev *compressdev);
int
zipvf_q_init(struct zipvf_qp *qp);
int
zipvf_q_term(struct zipvf_qp *qp);
void
zipvf_push_command(struct zipvf_qp *qp, union zip_inst_s *zcmd);
int
zip_process_op(struct rte_comp_op *op,
struct zipvf_qp *qp,
struct zip_stream *zstrm);
uint64_t
zip_reg_read64(uint8_t *hw_addr, uint64_t offset);
void
zip_reg_write64(uint8_t *hw_addr, uint64_t offset, uint64_t val);
#endif /* _RTE_ZIP_VF_H_ */
| {
"content_hash": "68082c4b603974d72586b3d452a5a7b5",
"timestamp": "",
"source": "github",
"line_count": 275,
"max_line_length": 77,
"avg_line_length": 25.345454545454544,
"alnum_prop": 0.6648493543758967,
"repo_name": "john-mcnamara-intel/dpdk",
"id": "118a95d738c5a60c3b67660bebce1ea138077a46",
"size": "7047",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "drivers/compress/octeontx/otx_zip.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "1623"
},
{
"name": "C",
"bytes": "39269990"
},
{
"name": "C++",
"bytes": "860345"
},
{
"name": "Makefile",
"bytes": "342834"
},
{
"name": "Meson",
"bytes": "144875"
},
{
"name": "Objective-C",
"bytes": "224248"
},
{
"name": "Python",
"bytes": "115929"
},
{
"name": "Shell",
"bytes": "77250"
},
{
"name": "SmPL",
"bytes": "2074"
}
],
"symlink_target": ""
} |
package org.shenit.tutorial.android.anim;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import org.shenit.tutorial.android.R;
import org.shenit.tutorial.android.TutorialUtils;
public class LayoutAnimationByXmlExampleActivity extends AppCompatActivity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_animation_xml_example);
img = (ImageView) findViewById(R.id.img);
}
public void onToggleVisibleClick(View v){
TutorialUtils.toggleInvisible(img);
}
}
| {
"content_hash": "af59a2804190e38157a560e84fd6e8f6",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 76,
"avg_line_length": 30.703703703703702,
"alnum_prop": 0.7768395657418576,
"repo_name": "jgnan/edu",
"id": "ef2c14f5dc5cb26731a366b2a0ceda06150000a9",
"size": "829",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/AndroidTutorial/app/src/main/java/org/shenit/tutorial/android/anim/LayoutAnimationByXmlExampleActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9715"
},
{
"name": "CoffeeScript",
"bytes": "422"
},
{
"name": "HTML",
"bytes": "41115"
},
{
"name": "Java",
"bytes": "241993"
},
{
"name": "JavaScript",
"bytes": "6416"
},
{
"name": "Ruby",
"bytes": "84616"
}
],
"symlink_target": ""
} |
package terrastore.util.annotation;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author Sergio Bossa
*/
public class AutowiringMap extends AbstractMap {
private final Map map = new HashMap();
public AutowiringMap(Map presets, AnnotationScanner scanner, Class type) {
this.map.putAll(scanner.scanByType(type));
this.map.putAll(presets);
}
@Override
public Set entrySet() {
return map.entrySet();
}
}
| {
"content_hash": "0ff31eb4a1da5bfa5dbf47a54ba22ad0",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 78,
"avg_line_length": 20.68,
"alnum_prop": 0.688588007736944,
"repo_name": "est/terrastore",
"id": "e8f2efda5be2c12bdc46eec813e25d5ff085999e",
"size": "1172",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/terrastore/util/annotation/AutowiringMap.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "9116"
},
{
"name": "Java",
"bytes": "1239945"
},
{
"name": "JavaScript",
"bytes": "17488"
},
{
"name": "Shell",
"bytes": "1134"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using Server;
using Server.Items;
using Mat = Server.Engines.BulkOrders.BulkMaterialType;
using System.Collections.Generic;
namespace Server.Engines.BulkOrders
{
[TypeAlias( "Scripts.Engines.BulkOrders.LargeSmithBOD" )]
public class LargeSmithBOD : LargeBOD
{
public static double[] m_BlacksmithMaterialChances = new double[]
{
0.501953125, // None
0.250000000, // Dull Copper
0.125000000, // Shadow Iron
0.062500000, // Copper
0.031250000, // Bronze
0.015625000, // Gold
0.007812500, // Agapite
0.003906250, // Verite
0.001953125 // Valorite
};
public override int ComputeFame()
{
return SmithRewardCalculator.Instance.ComputeFame( this );
}
public override int ComputeGold()
{
return SmithRewardCalculator.Instance.ComputeGold( this );
}
[Constructable]
public LargeSmithBOD()
{
LargeBulkEntry[] entries;
bool useMaterials = true;
int rand = Utility.Random( 8 );
switch ( rand )
{
default:
case 0: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargeRing ); break;
case 1: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargePlate ); break;
case 2: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargeChain ); break;
case 3: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargeAxes ); break;
case 4: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargeFencing ); break;
case 5: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargeMaces ); break;
case 6: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargePolearms ); break;
case 7: entries = LargeBulkEntry.ConvertEntries( this, LargeBulkEntry.LargeSwords ); break;
}
if( rand > 2 && rand < 8 )
useMaterials = false;
int hue = 0x44E;
int amountMax = Utility.RandomList( 10, 15, 20, 20 );
bool reqExceptional = ( 0.825 > Utility.RandomDouble() );
BulkMaterialType material;
if ( useMaterials )
material = GetRandomMaterial( BulkMaterialType.DullCopper, m_BlacksmithMaterialChances );
else
material = BulkMaterialType.None;
this.Hue = hue;
this.AmountMax = amountMax;
this.Entries = entries;
this.RequireExceptional = reqExceptional;
this.Material = material;
}
public LargeSmithBOD( int amountMax, bool reqExceptional, BulkMaterialType mat, LargeBulkEntry[] entries )
{
this.Hue = 0x44E;
this.AmountMax = amountMax;
this.Entries = entries;
this.RequireExceptional = reqExceptional;
this.Material = mat;
}
public override List<Item> ComputeRewards( bool full )
{
List<Item> list = new List<Item>();
RewardGroup rewardGroup = SmithRewardCalculator.Instance.LookupRewards( SmithRewardCalculator.Instance.ComputePoints( this ) );
if ( rewardGroup != null )
{
if ( full )
{
for ( int i = 0; i < rewardGroup.Items.Length; ++i )
{
Item item = rewardGroup.Items[i].Construct();
if ( item != null )
list.Add( item );
}
}
else
{
RewardItem rewardItem = rewardGroup.AcquireItem();
if ( rewardItem != null )
{
Item item = rewardItem.Construct();
if ( item != null )
list.Add( item );
}
}
}
return list;
}
public LargeSmithBOD( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | {
"content_hash": "de7b5f8258e4bbf5f469108623104a9e",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 130,
"avg_line_length": 26.364285714285714,
"alnum_prop": 0.6759685722026552,
"repo_name": "ggobbe/vivre-uo",
"id": "b1d2635c8cf8bd3aa9c91474428436928b792a1a",
"size": "3691",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "Scripts/Engines/BulkOrders/LargeSmithBOD.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C#",
"bytes": "19852349"
},
{
"name": "CSS",
"bytes": "699"
},
{
"name": "HTML",
"bytes": "3008"
}
],
"symlink_target": ""
} |
package com.mesosphere.dcos.cassandra.scheduler;
import com.mesosphere.dcos.cassandra.common.offer.PersistentOfferRequirementProvider;
import com.mesosphere.dcos.cassandra.common.persistence.PersistenceException;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraDaemonTask;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraState;
import org.apache.commons.lang3.StringUtils;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.config.ConfigStoreException;
import org.apache.mesos.offer.OfferAccepter;
import org.apache.mesos.offer.OfferEvaluator;
import org.apache.mesos.offer.OfferRecommendation;
import org.apache.mesos.offer.OfferRequirement;
import org.apache.mesos.scheduler.ChainedObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Collectors;
public class CassandraRecoveryScheduler extends ChainedObserver {
private static final Logger LOGGER = LoggerFactory.getLogger(
CassandraRecoveryScheduler.class);
private final OfferAccepter offerAccepter;
private final PersistentOfferRequirementProvider offerRequirementProvider;
private final CassandraState cassandraState;
private final OfferEvaluator offerEvaluator;
private final Random random = new Random();
public CassandraRecoveryScheduler(
PersistentOfferRequirementProvider requirementProvider,
OfferAccepter offerAccepter, CassandraState cassandraState) {
this.offerAccepter = offerAccepter;
this.cassandraState = cassandraState;
this.offerRequirementProvider = requirementProvider;
this.offerEvaluator = new OfferEvaluator(cassandraState.getStateStore());
this.cassandraState.subscribe(this);
}
public boolean hasOperations() {
return getTerminatedTask(new HashSet<>()).isPresent();
}
public List<Protos.OfferID> resourceOffers(final SchedulerDriver driver,
final List<Protos.Offer> offers,
final Set<String> ignore) {
List<Protos.OfferID> acceptedOffers = Collections.emptyList();
Optional<CassandraDaemonTask> terminatedOption = getTerminatedTask(ignore);
if (terminatedOption.isPresent()) {
try {
CassandraDaemonTask terminated = terminatedOption.get();
terminated = cassandraState.replaceDaemon(terminated);
Optional<OfferRequirement> offerReq;
String replaceIp = terminated.getConfig().getReplaceIp();
if (StringUtils.isEmpty(replaceIp)) {
offerReq = offerRequirementProvider.getReplacementOfferRequirement(
cassandraState.getOrCreateContainer(terminated.getName()));
} else {
offerReq = offerRequirementProvider.getNewOfferRequirement(
cassandraState.createCassandraContainer(terminated.getName(), replaceIp));
}
if (offerReq.isPresent()) {
LOGGER.info("Attempting to satisfy OfferRequirement: " + offerReq.get());
List<OfferRecommendation> recommendations =
offerEvaluator.evaluate(offerReq.get(), offers);
LOGGER.debug(
"Got recommendations: {} for terminated task: {}",
recommendations,
terminated.getId());
acceptedOffers = offerAccepter.accept(driver,
recommendations);
}
} catch (PersistenceException | ConfigStoreException ex) {
LOGGER.error(
String.format("Persistence error recovering " +
"terminated task %s", terminatedOption),
ex);
}
}
return acceptedOffers;
}
private Optional<CassandraDaemonTask> getTerminatedTask(
final Set<String> ignore) {
LOGGER.info("Ignoring steps: {}", ignore);
cassandraState.refreshTasks();
List<CassandraDaemonTask> terminated =
cassandraState.getDaemons().values().stream()
.filter(task -> cassandraState.isTerminated(task))
.filter(task -> !ignore.contains(task.getName()))
.collect(Collectors.toList());
LOGGER.info("Terminated tasks size: {}", terminated.size());
if (terminated.size() > 0) {
return Optional.of(terminated.get(
random.nextInt(terminated.size())));
} else {
return Optional.empty();
}
}
}
| {
"content_hash": "f8ae3fceca2e88a6623896655b414e79",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 102,
"avg_line_length": 43.88181818181818,
"alnum_prop": 0.6374559767971825,
"repo_name": "niteshjain1/dcos-cassandra-service",
"id": "1badfba5de57b96ad0fa8c3701562296e3a1a4cf",
"size": "4827",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "cassandra-scheduler/src/main/java/com/mesosphere/dcos/cassandra/scheduler/CassandraRecoveryScheduler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "1245"
},
{
"name": "Go",
"bytes": "11675"
},
{
"name": "Groovy",
"bytes": "1678"
},
{
"name": "HTML",
"bytes": "9653"
},
{
"name": "Java",
"bytes": "1091055"
},
{
"name": "Python",
"bytes": "202047"
},
{
"name": "Shell",
"bytes": "55036"
}
],
"symlink_target": ""
} |
namespace TG.INI
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// A collection to store <see cref="IniSection"/>.
/// </summary>
public class SectionCollection : System.Collections.CollectionBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of <see cref="SectionCollection"/>.
/// </summary>
protected internal SectionCollection(IniDocument document)
{
this.ParentDocument = document;
}
#endregion Constructors
#region Indexers
/// <summary>
/// Gets the <see cref="IniSection"/> by name.
/// </summary>
/// <param name="name">The name of the <see cref="IniSection"/> to get.</param>
/// <returns>The <see cref="IniSection"/>, if found; otherwise a new <see cref="IniSection"/> will be created.</returns>
public IniSection this[string name]
{
get
{
IniSection section = Find(name);
if (section == null)
return this.Add(name);
else
return section;
}
}
/// <summary>
/// Gets the <see cref="IniSection"/> as a given index.
/// </summary>
/// <param name="index">The index of the section.</param>
/// <returns><see cref="IniSection"/></returns>
public IniSection this[int index]
{
get
{
return List[index] as IniSection;
}
}
#endregion Indexers
#region Methods
/// <summary>
/// Adds an <see cref="IniSection"/> to the collection.
/// </summary>
/// <param name="section">The <see cref="IniSection"/> to be added.</param>
/// <returns>The value of param section.</returns>
public IniSection Add(IniSection section)
{
List.Add(section);
section.ParentDocument = this.ParentDocument;
return section;
}
/// <summary>
/// Initializes a new <see cref="IniSection"/> with the provided name and adds it to the collection.
/// </summary>
/// <param name="name">The name of the section.</param>
/// <returns>The instance of the new <see cref="IniSection"/>.</returns>
public IniSection Add(string name)
{
var section = new IniSection(name) { ParentDocument = this.ParentDocument };
List.Add(section);
return section;
}
/// <summary>
/// Determines if the collection contains a section with the provided name.
/// </summary>
/// <param name="name">The name of the section to find.</param>
/// <returns>True if the collection contains the section; otherwise false.</returns>
public bool Contains(string name)
{
return Find(name) != null;
}
/// <summary>
/// Searches the collection for an <see cref="IniSection"/> by the name.
/// </summary>
/// <param name="name">The name of the <see cref="IniSection"/> to find.</param>
/// <returns>The <see cref="IniSection"/>, if found; otherwise null.</returns>
public IniSection Find(string name)
{
for (int i = 0; i < Count; i++)
{
IniSection sec = List[i] as IniSection;
if (string.Equals(sec.Name, name, StringComparison.CurrentCultureIgnoreCase))
return sec;
}
return null;
}
/// <summary>
/// Remove an <see cref="IniSection"/> from the collection.
/// </summary>
/// <param name="section"></param>
public void Remove(IniSection section)
{
if (section != null)
{
section.ParentDocument = null;
List.Remove(section);
}
}
/// <summary>
/// Remove an <see cref="IniSection"/> from the collection, by name.
/// </summary>
/// <param name="name">The name of the section to remove.</param>
public void Remove(string name)
{
var sec = Find(name);
sec.ParentDocument = null;
if (sec != null)
List.Remove(sec);
}
#endregion Methods
/// <summary>
/// Gets the parent <see cref="IniDocument"/>.
/// </summary>
public IniDocument ParentDocument { get; internal set; }
}
} | {
"content_hash": "30d8aded75b1a4a0ae032a8cc8b5df03",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 128,
"avg_line_length": 32.54225352112676,
"alnum_prop": 0.5232633629084614,
"repo_name": "troygeiger/TG.INI",
"id": "e6d88086dc31187983df82ca5ed43cf6d836d570",
"size": "4623",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.3",
"path": "TG.INI/SectionCollection.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "123081"
}
],
"symlink_target": ""
} |
#ifndef ISCSID_H
#define ISCSID_H
#include <stdbool.h>
#include <stdint.h>
#include <openssl/md5.h>
#include <iscsi_ioctl.h>
#define DEFAULT_PIDFILE "/var/run/iscsid.pid"
#define CONN_DIGEST_NONE 0
#define CONN_DIGEST_CRC32C 1
#define CONN_MUTUAL_CHALLENGE_LEN 1024
#define SOCKBUF_SIZE 1048576
struct connection {
int conn_iscsi_fd;
int conn_socket;
unsigned int conn_session_id;
struct iscsi_session_conf conn_conf;
char conn_target_alias[ISCSI_ADDR_LEN];
uint8_t conn_isid[6];
uint16_t conn_tsih;
uint32_t conn_statsn;
int conn_header_digest;
int conn_data_digest;
bool conn_initial_r2t;
bool conn_immediate_data;
size_t conn_max_data_segment_length;
size_t conn_max_burst_length;
size_t conn_first_burst_length;
struct chap *conn_mutual_chap;
};
struct pdu {
struct connection *pdu_connection;
struct iscsi_bhs *pdu_bhs;
char *pdu_data;
size_t pdu_data_len;
};
#define KEYS_MAX 1024
struct keys {
char *keys_names[KEYS_MAX];
char *keys_values[KEYS_MAX];
char *keys_data;
size_t keys_data_len;
};
#define CHAP_CHALLENGE_LEN 1024
struct chap {
unsigned char chap_id;
char chap_challenge[CHAP_CHALLENGE_LEN];
char chap_response[MD5_DIGEST_LENGTH];
};
struct rchap {
char *rchap_secret;
unsigned char rchap_id;
void *rchap_challenge;
size_t rchap_challenge_len;
};
struct chap *chap_new(void);
char *chap_get_id(const struct chap *chap);
char *chap_get_challenge(const struct chap *chap);
int chap_receive(struct chap *chap, const char *response);
int chap_authenticate(struct chap *chap,
const char *secret);
void chap_delete(struct chap *chap);
struct rchap *rchap_new(const char *secret);
int rchap_receive(struct rchap *rchap,
const char *id, const char *challenge);
char *rchap_get_response(struct rchap *rchap);
void rchap_delete(struct rchap *rchap);
struct keys *keys_new(void);
void keys_delete(struct keys *key);
void keys_load(struct keys *keys, const struct pdu *pdu);
void keys_save(struct keys *keys, struct pdu *pdu);
const char *keys_find(struct keys *keys, const char *name);
int keys_find_int(struct keys *keys, const char *name);
void keys_add(struct keys *keys,
const char *name, const char *value);
void keys_add_int(struct keys *keys,
const char *name, int value);
struct pdu *pdu_new(struct connection *ic);
struct pdu *pdu_new_response(struct pdu *request);
void pdu_receive(struct pdu *request);
void pdu_send(struct pdu *response);
void pdu_delete(struct pdu *ip);
void login(struct connection *ic);
void discovery(struct connection *ic);
void log_init(int level);
void log_set_peer_name(const char *name);
void log_set_peer_addr(const char *addr);
void log_err(int, const char *, ...)
__dead2 __printflike(2, 3);
void log_errx(int, const char *, ...)
__dead2 __printflike(2, 3);
void log_warn(const char *, ...) __printflike(1, 2);
void log_warnx(const char *, ...) __printflike(1, 2);
void log_debugx(const char *, ...) __printflike(1, 2);
char *checked_strdup(const char *);
bool timed_out(void);
void fail(const struct connection *, const char *);
#endif /* !ISCSID_H */
| {
"content_hash": "05ea08c6b78f0ba4dcb2198bffad9500",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 60,
"avg_line_length": 26.775,
"alnum_prop": 0.6884531590413944,
"repo_name": "jrobhoward/SCADAbase",
"id": "9ad3325cf17e9cfa38516fe6402a142b97ad8917",
"size": "4703",
"binary": false,
"copies": "1",
"ref": "refs/heads/SCADAbase",
"path": "usr.sbin/iscsid/iscsid.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "62471"
},
{
"name": "Assembly",
"bytes": "4615704"
},
{
"name": "Awk",
"bytes": "273794"
},
{
"name": "Batchfile",
"bytes": "20333"
},
{
"name": "C",
"bytes": "457666547"
},
{
"name": "C++",
"bytes": "91495356"
},
{
"name": "CMake",
"bytes": "17632"
},
{
"name": "CSS",
"bytes": "104220"
},
{
"name": "ChucK",
"bytes": "39"
},
{
"name": "D",
"bytes": "6321"
},
{
"name": "DIGITAL Command Language",
"bytes": "10638"
},
{
"name": "DTrace",
"bytes": "1904158"
},
{
"name": "Emacs Lisp",
"bytes": "32010"
},
{
"name": "EmberScript",
"bytes": "286"
},
{
"name": "Forth",
"bytes": "204603"
},
{
"name": "GAP",
"bytes": "72078"
},
{
"name": "Groff",
"bytes": "32376243"
},
{
"name": "HTML",
"bytes": "5776268"
},
{
"name": "Haskell",
"bytes": "2458"
},
{
"name": "IGOR Pro",
"bytes": "6510"
},
{
"name": "Java",
"bytes": "112547"
},
{
"name": "KRL",
"bytes": "4950"
},
{
"name": "Lex",
"bytes": "425858"
},
{
"name": "Limbo",
"bytes": "4037"
},
{
"name": "Logos",
"bytes": "179088"
},
{
"name": "Makefile",
"bytes": "12750766"
},
{
"name": "Mathematica",
"bytes": "21782"
},
{
"name": "Max",
"bytes": "4105"
},
{
"name": "Module Management System",
"bytes": "816"
},
{
"name": "Objective-C",
"bytes": "1571960"
},
{
"name": "PHP",
"bytes": "2471"
},
{
"name": "PLSQL",
"bytes": "96552"
},
{
"name": "PLpgSQL",
"bytes": "2212"
},
{
"name": "Perl",
"bytes": "3947402"
},
{
"name": "Perl6",
"bytes": "122803"
},
{
"name": "PostScript",
"bytes": "152255"
},
{
"name": "Prolog",
"bytes": "42792"
},
{
"name": "Protocol Buffer",
"bytes": "54964"
},
{
"name": "Python",
"bytes": "381066"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "Ruby",
"bytes": "67015"
},
{
"name": "Scheme",
"bytes": "5087"
},
{
"name": "Scilab",
"bytes": "196"
},
{
"name": "Shell",
"bytes": "10963470"
},
{
"name": "SourcePawn",
"bytes": "2293"
},
{
"name": "SuperCollider",
"bytes": "80208"
},
{
"name": "Tcl",
"bytes": "7102"
},
{
"name": "TeX",
"bytes": "720582"
},
{
"name": "VimL",
"bytes": "19597"
},
{
"name": "XS",
"bytes": "17496"
},
{
"name": "XSLT",
"bytes": "4564"
},
{
"name": "Yacc",
"bytes": "1881915"
}
],
"symlink_target": ""
} |
/*
* Created on Feb 16, 2007
*/
package edu.wustl.common.util.tag;
/**
* @author Santosh Chandak
* JSP tag for Autocomplete feature. The body of this tag is executed once for every call of the tag
* when the page is rendered.
* To use this tag, include AutocompleterCommon.jsp in your page
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.util.global.Constants;
public class AutoCompleteTag extends TagSupport
{
/**
* version ID
*/
private static final long serialVersionUID = 1L;
/**
* property on which Autocompleter is to be applied
*/
private String property;
/**
* Object containing values of the dropdown. Supported datatypes
* 1. String Array 2. List of Name Value Beans
*
*/
private Object optionsList;
/**
* Default style
*/
private String styleClass = "formFieldSized15";
/**
* Number of results to be shown
*/
private String numberOfResults = "10";
/**
* Trigger matching when user enters these number of characters
*/
private String numberOfCharacters = "1";
/**
* set to true if the textbox is readOnly
*/
private Object readOnly = "false";
/**
* set to true if the textbox is disabled
*/
private Object disabled = "false";
/**
* Functions to be called when textbox loses focus
*/
private String onChange = "";
/**
* initial value in the textbox, this is compulsary attribute
*/
private Object initialValue = "";
/**
* if the property is dependent on some other property
* eg. type depends on class
*
*/
private String dependsOn = "";
/**
* size
*/
private String size = "300";
/**
* true - in case of static lists eg. class, type
* false - in case of dynamic lists eg. site, user
*/
private String staticField = "true";
/**
* A call back function, which gets executed by JSP runtime when opening tag
* for this custom tag is encountered.
*/
public int doStartTag() throws JspException
{
try {
JspWriter out = pageContext.getOut();
String autocompleteHTMLStr=null;
if(staticField.equalsIgnoreCase("true"))
{
autocompleteHTMLStr = getAutocompleteHTML();
}
else
{
autocompleteHTMLStr = getAutocompleteHTMLForDynamicProperty();
}
/**
* Clearing the variables
*/
onChange = "";
initialValue = "";
readOnly = "false";
dependsOn = "";
size="300";
disabled="false";
out.print(autocompleteHTMLStr);
} catch (IOException ioe) {
throw new JspTagException("Error:IOException while writing to the user");
}
return SKIP_BODY;
}
@SuppressWarnings("unchecked")
private String getAutocompleteHTML() {
String autoCompleteResult = "";
prepareCommonData();
/**
* Always pass the function with brackets, appending '()' will not be done
*/
if(onChange.equals(""))
{
onChange = "trimByAutoTag(this)";
}
else
{
onChange = "trimByAutoTag(this);" + onChange;
}
String div = "divFor" + property;
autoCompleteResult += "<div id=\"" + div + "\" style=\"display: none;\" class=\"autocomplete\">";
autoCompleteResult += "</div>";
autoCompleteResult += "<input type=\"text\" class=\"" + styleClass + "\" value=\"" + initialValue + "\"size=\"" + size + "\" id=\"" + property + "\" name=\"" + property + "\"" + "onmouseover=\"showTip(this.id)\" onmouseout=\"hideTip(this.id)\"";
if (readOnly.toString().equalsIgnoreCase("true"))
{
autoCompleteResult += "readonly";
} else
{
autoCompleteResult += "onblur=\"" + onChange + "\"";
}
autoCompleteResult += "/>";
String nameOfArrow = property + "arrow";
autoCompleteResult += "<image id='" + nameOfArrow + "' src='images/autocompleter.gif'/>";
autoCompleteResult += "<script> var valuesInList = new Array();";
/* ("new Autocompleter.Combobox('name-field',
'lookup_auto_complete', 'name-arrow',
all_options,{partialChars:1, ignoreCase:true, fullSearch:true, frequency:0.1,
choices:6, defaultArray:default_options, tokens: ',' });")*/
if (optionsList instanceof List) {
List nvbList = (List) optionsList;
if (nvbList != null && nvbList.size() > 0 && !readOnly.toString().equalsIgnoreCase("true")) {
// TODO other than NVB
for (int i = 0; i < nvbList.size(); i++) {
NameValueBean nvb = (NameValueBean) nvbList.get(i);
autoCompleteResult += "valuesInList[" + i + "] = \""
+ nvb.getName() + "\";";
}
autoCompleteResult += "new Autocompleter.Combobox(\"" + property + "\",\"" + div + "\",\"" + nameOfArrow + "\"" + ",valuesInList, { tokens: new Array(), fullSearch: true, partialSearch: true,defaultArray:" + "valuesInList" + ",choices: " + numberOfResults + ",autoSelect:true, minChars: "+ numberOfCharacters +" });";
}
}
autoCompleteResult += "</script>";
return autoCompleteResult;
}
@SuppressWarnings("unchecked")
private void prepareCommonData() {
if(initialValue == null || initialValue.equals(""))
{
initialValue = pageContext.getRequest().getParameter(property);
if(initialValue == null || initialValue.equals(""))
{
String[] title = (String[])
pageContext.getRequest().getParameterValues(property);
if (title != null && title.length > 0) { if (title[0] != null) {
initialValue = title[0]; } }
}
}
if (initialValue == null) {
initialValue = "";
}
/**
* As Type depends on class, get the optionsList as List from optionsList which was passed as a map
*/
if(property.equalsIgnoreCase(Constants.SPECIMEN_TYPE) && dependsOn!=null && !dependsOn.equals(""))
{
String className = dependsOn;
List specimenTypeList = (List) ((Map)optionsList).get(className);
optionsList = specimenTypeList;
}
/**
* Converting other data types to list of Name Value Beans
*/
if (optionsList instanceof String[]) {
String[] stringArray = (String[]) optionsList;
List tempNVBList = new ArrayList();
if(stringArray!=null)
{
for(int i=0;i<stringArray.length;i++)
{
tempNVBList.add(new NameValueBean(stringArray[i],stringArray[i]));
}
}
optionsList = tempNVBList;
}
if (optionsList instanceof List) {
List nvbList = (List) optionsList;
if (nvbList != null && nvbList.size() > 0) {
// TODO other than NVB
NameValueBean nvb1 = (NameValueBean) nvbList.get(0);
if (nvb1.getName().equals(Constants.SELECT_OPTION)) {
nvbList.remove(0);
}
}
/* if(nvbList == null || nvbList.size() == 0)
{
initialValue = "No Records Present"; // needed?
} */
}
}
/**
* This function prepares the HTML to be rendered
* @return String - containing HTML to be rendered
*
*/
@SuppressWarnings("unchecked")
private String getAutocompleteHTMLForDynamicProperty() {
String autoCompleteResult = "";
String displayProperty = "display" + property;
prepareCommonData();
/**
* Always pass the function with brackets, appending '()' will not be done
*/
if(onChange.equals(""))
{
onChange = "trimByAutoTagAndSetIdInForm(this)";
}
else
{
onChange = "trimByAutoTagAndSetIdInForm(this);" + onChange;
}
String name = "";
if(initialValue.equals("0") || initialValue.toString().equalsIgnoreCase("undefined") || initialValue.equals(""))
{
name = pageContext.getRequest().getParameter(displayProperty);
if(name == null || name.equals(""))
{
String[] title = (String[])
pageContext.getRequest().getParameterValues(displayProperty);
if (title != null && title.length > 0) { if (title[0] != null) {
name = title[0]; } }
}
}
if(name == null)
{
name = "";
}
String value = "";
if (optionsList instanceof List) {
List nvbList = (List) optionsList;
for(int i=0;i<nvbList.size();i++)
{
NameValueBean nvb1 = (NameValueBean) nvbList.get(i);
if(nvb1.getValue().equals(initialValue))
{
name = nvb1.getName();
value = nvb1.getValue();
break;
}
}
}
String div = "divFor" + displayProperty;
autoCompleteResult += "<div id=\"" + div + "\" style=\"display: none;\" class=\"autocomplete\">";
autoCompleteResult += "</div>";
autoCompleteResult += "<input type=\"text\" class=\"" + styleClass + "\" value=\"" + name + "\"size=\"" + size + "\" id=\"" + displayProperty + "\" name=\"" + displayProperty + "\"" + "onmouseover=\"showTip(this.id)\" onmouseout=\"hideTip(this.id)\"";
if (readOnly.toString().equalsIgnoreCase("true"))
{
autoCompleteResult += "readonly";
} else
{
autoCompleteResult += "onblur=\"" + onChange + "\"";
}
if (disabled.toString().equalsIgnoreCase("true"))
{
autoCompleteResult += "disabled=\"true\"";
}
autoCompleteResult += "/>";
String nameOfArrow = property + "arrow";
autoCompleteResult += "<image id='" + nameOfArrow + "' src='images/autocompleter.gif'/>";
autoCompleteResult += "<input type=\"hidden\" id=\"" + property + "\" name=\"" + property + "\"value=\"" + value + "\"/>";
autoCompleteResult += "<script> var valuesInListOf" + displayProperty + " = new Array();";
autoCompleteResult += "var idsInListOf" + displayProperty + " = new Array();";
if (optionsList instanceof List) {
List nvbList = (List) optionsList;
if (nvbList != null && nvbList.size() > 0 && !readOnly.toString().equalsIgnoreCase("true")) {
for (int i = 0; i < nvbList.size(); i++) {
NameValueBean nvb = (NameValueBean) nvbList.get(i);
autoCompleteResult += "valuesInListOf" + displayProperty + "[" + i + "] = \""
+ nvb.getName() + "\";";
autoCompleteResult += "idsInListOf" + displayProperty + "[" + i + "] = \""
+ nvb.getValue() + "\";";
}
/**
* Giving call to autocompleter constructor
*/
autoCompleteResult += "new Autocompleter.Combobox(\"" + displayProperty + "\",\"" + div + "\",\"" + nameOfArrow + "\"" + ",valuesInListOf" + displayProperty + ", { tokens: new Array(), fullSearch: true, partialSearch: true,defaultArray:" + "valuesInListOf" + displayProperty + ",choices: " + numberOfResults + ",autoSelect:true, minChars: "+ numberOfCharacters +" });";
// autoCompleteResult += "new Autocompleter.Combobox(\"" + property + "\",\"" + div + "\",'nameofarrow',valuesInList, { tokens: new Array(), fullSearch: true, partialSearch: true,defaultArray:" + "valuesInList" + ",choices: " + numberOfResults + ",autoSelect:true, minChars: "+ numberOfCharacters +" });";
}
}
autoCompleteResult += "</script>";
return autoCompleteResult;
}
/**
* A call back function
*/
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
/**
* @return
*/
public String getNumberOfCharacters() {
return numberOfCharacters;
}
/**
* @param numberOfCharacters
*/
public void setNumberOfCharacters(String numberOfCharacters) {
this.numberOfCharacters = numberOfCharacters;
}
/**
* @return
*/
public String getNumberOfResults() {
return numberOfResults;
}
/**
* @param numberOfResults
*/
public void setNumberOfResults(String numberOfResults) {
this.numberOfResults = numberOfResults;
}
/**
* @return
*/
public Object getOptionsList() {
return optionsList;
}
/**
* @param optionsList
*/
public void setOptionsList(Object optionsList) {
this.optionsList = optionsList;
}
/**
* @return
*/
public String getProperty() {
return property;
}
/**
* @param property
*/
public void setProperty(String property) {
this.property = property;
}
/**
* @return
*/
public String getSize() {
return size;
}
/**
* @param size
*/
public void setSize(String size) {
this.size = size;
}
/**
* @return
*/
public String getStyleClass() {
return styleClass;
}
/**
* @param styleClass
*/
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
public Object getInitialValue() {
return initialValue;
}
public void setInitialValue(Object initialValue) {
if (initialValue != null) {
this.initialValue = initialValue.toString();
}
}
/**
* @return Returns the onChange.
*/
public String getOnChange() {
return onChange;
}
/**
* @param onChange The onChange to set.
*/
public void setOnChange(String onChange) {
this.onChange = onChange;
}
/**
* @return Returns the readOnly.
*/
public Object getReadOnly() {
return readOnly;
}
/**
* @param readOnly The readOnly to set.
*/
public void setReadOnly(Object readOnly) {
this.readOnly = readOnly;
}
/**
* @return Returns the dependsOn.
*/
public String getDependsOn() {
return dependsOn;
}
/**
* @param dependsOn The dependsOn to set.
*/
public void setDependsOn(String dependsOn) {
this.dependsOn = dependsOn;
}
/**
* @return Returns the staticField.
*/
public String getStaticField() {
return staticField;
}
/**
* @param staticField The staticField to set.
*/
public void setStaticField(String staticField) {
this.staticField = staticField;
}
/**
* @return Returns the disabled.
*/
public Object getDisabled() {
return disabled;
}
/**
* @param disabled The disabled to set.
*/
public void setDisabled(Object disabled) {
this.disabled = disabled;
}
} | {
"content_hash": "4f4d41b1fbaea9884b0fd33676d0397d",
"timestamp": "",
"source": "github",
"line_count": 551,
"max_line_length": 380,
"avg_line_length": 26.1524500907441,
"alnum_prop": 0.5959056210964608,
"repo_name": "NCIP/wustl-common-package",
"id": "f5d6723717f7006d1854ac1f93daf258d1514573",
"size": "14655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/edu/wustl/common/util/tag/AutoCompleteTag.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1316"
},
{
"name": "Java",
"bytes": "2229133"
},
{
"name": "JavaScript",
"bytes": "8330"
},
{
"name": "Shell",
"bytes": "3704"
},
{
"name": "XSLT",
"bytes": "80151"
}
],
"symlink_target": ""
} |
from .entity_health_state import EntityHealthState
class ReplicaHealthState(EntityHealthState):
"""Represents a base class for stateful service replica or stateless service
instance health state.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: StatefulServiceReplicaHealthState,
StatelessServiceInstanceHealthState
:param aggregated_health_state: The health state of a Service Fabric
entity such as Cluster, Node, Application, Service, Partition, Replica
etc. Possible values include: 'Invalid', 'Ok', 'Warning', 'Error',
'Unknown'
:type aggregated_health_state: str or
~azure.servicefabric.models.HealthState
:param partition_id: The ID of the partition to which this replica
belongs.
:type partition_id: str
:param service_kind: Constant filled by server.
:type service_kind: str
"""
_validation = {
'service_kind': {'required': True},
}
_attribute_map = {
'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'},
'partition_id': {'key': 'PartitionId', 'type': 'str'},
'service_kind': {'key': 'ServiceKind', 'type': 'str'},
}
_subtype_map = {
'service_kind': {'Stateful': 'StatefulServiceReplicaHealthState', 'Stateless': 'StatelessServiceInstanceHealthState'}
}
def __init__(self, aggregated_health_state=None, partition_id=None):
super(ReplicaHealthState, self).__init__(aggregated_health_state=aggregated_health_state)
self.partition_id = partition_id
self.service_kind = None
self.service_kind = 'ReplicaHealthState'
| {
"content_hash": "4ec35d4a64f6cb541618cfea89fd32f5",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 125,
"avg_line_length": 38.7906976744186,
"alnum_prop": 0.684052757793765,
"repo_name": "lmazuel/azure-sdk-for-python",
"id": "894b4bc3c12de48a13694ae68d608b8744df4ea1",
"size": "2142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "azure-servicefabric/azure/servicefabric/models/replica_health_state.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "42572767"
}
],
"symlink_target": ""
} |
using System;
namespace SonicAPI.Exceptions
{
public class WrongUsernameOrPassword : ASonicApiException
{
public WrongUsernameOrPassword() { }
public WrongUsernameOrPassword(string desc)
: base(desc) { }
public WrongUsernameOrPassword(string desc, Exception innerException)
: base(desc, innerException) { }
}
} | {
"content_hash": "cf58577b10e78dbc1b6b86fedeef66fe",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 77,
"avg_line_length": 24.933333333333334,
"alnum_prop": 0.6684491978609626,
"repo_name": "kaylynb/SonicMetro",
"id": "1f1e8e1122d215d24f0a4200e0cc77911c34c8b6",
"size": "376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SonicAPI/Exceptions/WrongUsernameOrPassword.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "203711"
}
],
"symlink_target": ""
} |
<?php
/**
* Tests for \Magento\Framework\Data\Form\Element\Image
*/
namespace Magento\Framework\Data\Form\Element;
class ImageTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Framework\Data\Form\Element\Image
*/
protected $imageElement;
protected function setUp()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $elementFactory \Magento\Framework\Data\Form\ElementFactory */
$elementFactory = $objectManager->create('Magento\Framework\Data\Form\ElementFactory');
$this->imageElement = $elementFactory->create('Magento\Framework\Data\Form\Element\Image', []);
$form = $objectManager->create('Magento\Framework\Data\Form');
$this->imageElement->setForm($form);
}
public function testGetElementHtml()
{
$filePath = 'some/path/to/file.jpg';
$this->imageElement->setValue($filePath);
$html = $this->imageElement->getElementHtml();
$this->assertContains('media/' . $filePath, $html);
}
}
| {
"content_hash": "1fc7c0e150bcba4c6cd31daf1daf22e5",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 103,
"avg_line_length": 32.303030303030305,
"alnum_prop": 0.6641651031894934,
"repo_name": "florentinaa/magento",
"id": "bdced61577e03d792d5a184f5d1d30b588b91738",
"size": "1164",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "store/dev/tests/integration/testsuite/Magento/Framework/Data/Form/Element/ImageTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "23874"
},
{
"name": "CSS",
"bytes": "3779785"
},
{
"name": "HTML",
"bytes": "6149486"
},
{
"name": "JavaScript",
"bytes": "4396691"
},
{
"name": "PHP",
"bytes": "22079463"
},
{
"name": "Shell",
"bytes": "6072"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
<header>
<copyright>
<year>2001</year><year>2022</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
</legalnotice>
<title>fprof - The File Trace Profiler</title>
<prepared>Raimo Niskanen</prepared>
<responsible>nobody</responsible>
<docno></docno>
<approved>nobody</approved>
<checked>no</checked>
<date>2001-08-14</date>
<rev>PA1</rev>
<file>fprof_chapter.xml</file>
</header>
<p><c>fprof</c> is a profiling tool that can be used to get a picture of
how much processing time different functions consumes and in which
processes.
</p>
<p><c>fprof</c> uses tracing with timestamps to collect profiling
data. Therefore there is no need for special compilation of any
module to be profiled.
</p>
<p><c>fprof</c> presents wall clock times from the host machine OS,
with the assumption that OS scheduling will randomly load the
profiled functions in a fair way. Both <em>own time</em> i.e the
time used by a function for its own execution, and
<em>accumulated time</em> i.e execution time including called
functions.
</p>
<p>Profiling is essentially done in 3 steps:</p>
<taglist>
<tag><c>1</c></tag>
<item>Tracing; to file, as mentioned in the previous paragraph.</item>
<tag><c>2</c></tag>
<item>Profiling; the trace file is read and raw profile data is
collected into an internal RAM storage on the node. During
this step the trace data may be dumped in text format to file
or console.</item>
<tag><c>3</c></tag>
<item>Analysing; the raw profile data is sorted and dumped
in text format either to file or console.</item>
</taglist>
<p>Since <c>fprof</c> uses trace to file, the runtime performance
degradation is minimized, but still far from negligible,
especially not for programs that use the filesystem heavily
by themselves. Where you place the trace file is also important,
e.g on Solaris <c>/tmp</c> is usually a good choice,
while any NFS mounted disk is a lousy choice.
</p>
<p>Fprof can also skip the file step and trace to a tracer process
of its own that does the profiling in runtime.
</p>
<p>The following sections show some examples of how to profile with
Fprof. See also the reference manual
<seeerl marker="fprof">fprof(3)</seeerl>.
</p>
<section>
<title>Profiling from the source code</title>
<p>If you can edit and recompile the source code, it is convenient
to insert <c>fprof:trace(start)</c> and
<c>fprof:trace(stop)</c> before and after the code to be
profiled. All spawned processes are also traced. If you want
some other filename than the default try
<c>fprof:trace(start, "my_fprof.trace")</c>.
</p>
<p>Then read the trace file and create the raw profile data with
<c>fprof:profile()</c>, or perhaps
<c>fprof:profile(file, "my_fprof.trace")</c> for non-default
filename.
</p>
<p>Finally create an informative table dumped on the console with
<c>fprof:analyse()</c>, or on file with
<c>fprof:analyse(dest, [])</c>, or perhaps even
<c>fprof:analyse([{dest, "my_fprof.analysis"}, {cols, 120}])</c>
for a wider listing on non-default filename.
</p>
<p>See the <seeerl marker="fprof">fprof(3)</seeerl> manual page
for more options and arguments to the functions
<seemfa marker="fprof#trace/2">trace</seemfa>,
<seemfa marker="fprof#profile/0">profile</seemfa>
and
<seemfa marker="fprof#analyse/0">analyse</seemfa>.
</p>
</section>
<section>
<title>Profiling a function</title>
<p>If you have one function that does the task that you want to
profile, and the function returns when the profiling should
stop, it is convenient to use
<c>fprof:apply(Module, Function, Args)</c> and related for the
tracing step.
</p>
<p>If the tracing should continue after the function returns, for
example if it is a start function that spawns processes to be
profiled, you can use
<c>fprof:apply(M, F, Args, [continue | OtherOpts])</c>.
The tracing has to be stopped at a suitable later time using
<c>fprof:trace(stop)</c>.
</p>
</section>
<section>
<title>Immediate profiling</title>
<p>It is also possible to trace immediately into the profiling
process that creates the raw profile data, that is to short
circuit the tracing and profiling steps so that the filesystem
is not used.
</p>
<p>Do something like this:</p>
<pre>
{ok, Tracer} = fprof:profile(start),
fprof:trace([start, {tracer, Tracer}]),
%% Code to profile
fprof:trace(stop);</pre>
<p>This puts less load on the filesystem, but much more on the
Erlang runtime system.
</p>
</section>
</chapter>
| {
"content_hash": "1a5dd7cc87b9f8dfa45efe00c6b2402f",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 78,
"avg_line_length": 39.46478873239437,
"alnum_prop": 0.6686295503211992,
"repo_name": "rlipscombe/otp",
"id": "b07eef2637a326973047f77dd91a07963a551126",
"size": "5604",
"binary": false,
"copies": "12",
"ref": "refs/heads/maint",
"path": "lib/tools/doc/src/fprof_chapter.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "206346"
},
{
"name": "Batchfile",
"bytes": "4669"
},
{
"name": "C",
"bytes": "17445914"
},
{
"name": "C++",
"bytes": "8364867"
},
{
"name": "CSS",
"bytes": "18556"
},
{
"name": "DIGITAL Command Language",
"bytes": "21"
},
{
"name": "DTrace",
"bytes": "225425"
},
{
"name": "Elixir",
"bytes": "4459"
},
{
"name": "Emacs Lisp",
"bytes": "470592"
},
{
"name": "Erlang",
"bytes": "73828121"
},
{
"name": "HTML",
"bytes": "471200"
},
{
"name": "Java",
"bytes": "529333"
},
{
"name": "JavaScript",
"bytes": "32494"
},
{
"name": "M4",
"bytes": "364784"
},
{
"name": "Makefile",
"bytes": "1055184"
},
{
"name": "NSIS",
"bytes": "16409"
},
{
"name": "Objective-C",
"bytes": "2485"
},
{
"name": "PHP",
"bytes": "4110"
},
{
"name": "Perl",
"bytes": "209603"
},
{
"name": "Python",
"bytes": "152585"
},
{
"name": "Roff",
"bytes": "1954"
},
{
"name": "Ruby",
"bytes": "81"
},
{
"name": "Shell",
"bytes": "626504"
},
{
"name": "SmPL",
"bytes": "24294"
},
{
"name": "TLA",
"bytes": "7516"
},
{
"name": "XSLT",
"bytes": "258226"
},
{
"name": "sed",
"bytes": "7660"
}
],
"symlink_target": ""
} |
import {Container} from 'aurelia-dependency-injection';
import {
ViewCompiler,
ViewResources,
ResourceRegistry
} from 'aurelia-templating';
import {configure as configureBindingLanguage} from 'aurelia-templating-binding';
var container = new Container(),
resourceRegistry = document.body.aurelia.container.get(ResourceRegistry),
viewCompiler,
resources;
configureBindingLanguage({ container: container });
viewCompiler = container.get(ViewCompiler);
resources = new ViewResources(resourceRegistry, 'app.html');
const iterations = 1000;
export function createBenchmark(benchType, templateOrFragment) {
switch(benchType) {
case 'ViewCompiler':
return deferred => {
var i = iterations;
while(i--) {
viewCompiler.compile(templateOrFragment, resources);
}
deferred.resolve();
};
case 'ViewFactory':
let viewFactory = viewCompiler.compile(templateOrFragment, resources);
return deferred => {
var i = iterations;
while(i--) {
viewFactory.create(container, new ExecutionContext());
}
deferred.resolve();
};
case 'Both':
return deferred => {
var i = iterations;
while(i--) {
viewCompiler.compile(templateOrFragment, resources).create(container, new ExecutionContext());
}
deferred.resolve();
};
}
}
export var template = {
vanilla:
`<template>
<section>
<header class="a">Hello World</header>
<nav class="b">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<article class="c">
<p>Bacon ipsum dolor amet filet mignon shankle t-bone pig ham, short loin pork belly brisket. Pastrami filet mignon porchetta boudin beef tri-tip. Swine pork loin pastrami drumstick, fatback capicola ham jerky pork chop. Bresaola chicken tongue pork belly venison porchetta t-bone, frankfurter boudin ham hock spare ribs ribeye tail pig rump. Flank drumstick short loin capicola, pork loin doner tail porchetta shank kevin boudin alcatra. Sirloin pork ground round turkey turducken, ball tip pork chop cow jerky pork belly andouille ribeye brisket beef ribs fatback.</p>
<p>Shankle frankfurter cow, brisket turducken shank ball tip ground round filet mignon swine flank. Shankle ball tip pig turducken corned beef. Shankle ball tip venison jowl biltong pastrami, cow kielbasa filet mignon meatloaf. Frankfurter chicken brisket doner, tongue beef turducken bacon tail.</p>
</article>
<aside class="e">
<ul>
<li><a href="#buy-this">Buy this!</a></li>
<li><a href="#buy-that">Buy that!</a></li>
<li><a href="#buy-those">Buy those!</a></li>
</ul>
</aside>
<footer class="f">Goodbye World</footer>
</section>
</template>`,
bindingsOnly:
`<template>
<section>
<header class="\${a}">Hello World</header>
<nav class="\${b}">
<ul>
<li repeat.for="nav of navs"><a href.bind="nav.href">\${nav.title}</a></li>
</ul>
</nav>
<article class="\${c}">
<p>Bacon ipsum \${dolor} amet filet mignon shankle t-bone pig ham, short loin pork belly brisket. Pastrami filet mignon porchetta boudin beef tri-tip. Swine pork loin pastrami drumstick, fatback capicola ham jerky pork chop. Bresaola chicken tongue pork belly venison porchetta t-bone, frankfurter boudin ham hock \${spare} ribs ribeye tail pig rump. Flank drumstick short loin capicola, pork loin doner tail porchetta shank kevin boudin alcatra. Sirloin pork ground round turkey turducken, ball tip pork chop cow jerky pork belly andouille ribeye brisket beef ribs fatback.</p>
<p>Shankle frankfurter cow, \${brisket} turducken shank ball \${tip} ground round filet mignon swine flank. Shankle ball tip pig turducken corned beef. Shankle ball tip venison jowl biltong pastrami, cow kielbasa filet mignon meatloaf. Frankfurter chicken brisket doner, tongue beef turducken bacon tail.</p>
</article>
<aside class="\${e}">
<ul>
<li repeat.for="ad of ads"><a href.bind="ad.href">\${ad.title}</a></li>
</ul>
</aside>
<footer class="f">Goodbye World</footer>
</section>
</template>`,
behaviorsOnly:
`<template>
<section>
<point foo></point>
<point bar></point>
<point baz></point>
<point foo></point>
<point bar></point>
<point baz></point>
<point foo></point>
<point bar></point>
<point baz></point>
<point foo></point>
<point bar></point>
<point baz></point>
</section>
</template>`,
bindingsAndBehaviors:
`<template>
<section>
<header class="\${a}">Hello World</header>
<nav class="\${b}">
<ul>
<li repeat.for="nav of navs"><a href.bind="nav.href">\${nav.title}</a></li>
</ul>
</nav>
<article class="\${c}">
<p>Bacon ipsum \${dolor} amet filet mignon shankle t-bone pig ham, short loin pork belly brisket. Pastrami filet mignon porchetta boudin beef tri-tip. Swine pork loin pastrami drumstick, fatback capicola ham jerky pork chop. Bresaola chicken tongue pork belly venison porchetta t-bone, frankfurter boudin ham hock \${spare} ribs ribeye tail pig rump. Flank drumstick short loin capicola, pork loin doner tail porchetta shank kevin boudin alcatra. Sirloin pork ground round turkey turducken, ball tip pork chop cow jerky pork belly andouille ribeye brisket beef ribs fatback.</p>
<p>Shankle frankfurter cow, \${brisket} turducken shank ball \${tip} ground round filet mignon swine flank. Shankle ball tip pig turducken corned beef. Shankle ball tip venison jowl biltong pastrami, cow kielbasa filet mignon meatloaf. Frankfurter chicken brisket doner, tongue beef turducken bacon tail.</p>
</article>
<aside class="\${e}">
<ul>
<li repeat.for="ad of ads"><a href.bind="ad.href">\${ad.title}</a></li>
</ul>
</aside>
<footer class="f">Goodbye World</footer>
</section>
<section>
<point foo x.bind="a" y.bind="n"></point>
<point bar x.bind="b" y.bind="o"></point>
<point baz x.bind="c" y.bind="p"></point>
<point foo x.bind="d" y.bind="q"></point>
<point bar x.bind="e" y.bind="r"></point>
<point baz x.bind="f" y.bind="s"></point>
<point foo x.bind="g" y.bind="t"></point>
<point bar x.bind="h" y.bind="u"></point>
<point baz x.bind="i" y.bind="v"></point>
<point foo x.bind="j" y.bind="w"></point>
<point bar x.bind="k" y.bind="x"></point>
<point baz x.bind="l" y.bind="y"></point>
<point foo x.bind="m" y.bind="z"></point>
</section>
</template>`,
contentSelectors:
`<template>
<content-selectors>
<modal-header>foo</modal-header>
<modal-body>bar</modal-body>
<modal-footer>baz</modal-footer>
</content-selectors>
</template>`,
templateParts:
`<template-parts items.bind="planets">
<template replace-part="item-template">
<li>\${item.name} \${item.diameter}</li>
</template>
</template-parts>`,
compileSurrogateBehaviors:
`<template class="\${foo} \${bar} \${baz}" hello.bind="world">
<div>
</div>
</template>`,
createSurrogateBehaviors:
`<template>
<surrogate-behaviors></surrogate-behaviors>
</template>`
}
class ExecutionContext {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
e = 'e';
f = 'f';
g = 'g';
h = 'h';
i = 'i';
j = 'j';
k = 'k';
l = 'l';
m = 'm';
n = 'n';
o = 'o';
p = 'p';
q = 'q';
r = 'r';
s = 's';
t = 't';
u = 'u';
v = 'v';
w = 'w';
x = 'x';
y = 'y';
z = 'z';
dolar = 'dolar';
brisket = 'brisket';
tip = 'tip';
navs = [{ href: "#home", title: "Home"}, { href: "#about", title: "About"}, { href: "#contact", title: "Contact"}];
ads = [{ href: "#buy-this", title: "Buy This!"}, { href: "#buy-that", title: "Buy That!"}, { href: "#buy-those", title: "Buy Those!"}];
planets = [
{ name: 'Mercury', diameter: 3032 },
{ name: 'Venus', diameter: 7521 },
{ name: 'Earth', diameter: 7926 },
{ name: 'Mars', diameter: 4222 },
{ name: 'Jupiter', diameter: 88846 },
{ name: 'Saturn', diameter: 74898 },
{ name: 'Uranus', diameter: 31763 },
{ name: 'Neptune', diameter: 30778 }];
}
| {
"content_hash": "c3d6e9f4cc6e18133004f9f9d152b495",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 584,
"avg_line_length": 37.03982300884956,
"alnum_prop": 0.6256122327081591,
"repo_name": "vbauerster/benchmarks",
"id": "7e41176096b744a33db97b2fe64800ea46f57329",
"size": "8371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "benchmarks/micro/templating.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10464"
},
{
"name": "JavaScript",
"bytes": "162034"
}
],
"symlink_target": ""
} |
package plugins
import (
"github.com/shirou/gopsutil/cpu"
"strconv"
)
// GetCPU outputs the system's CPU usage
func GetCPUIdle() string {
percentage, _ := cpu.Percent(0, false)
cpuc := 0.0
for idx, cpua := range percentage {
cpuc = cpuc + cpua
idx = idx + idx
}
return strconv.FormatInt(int64(cpuc), 10)
}
| {
"content_hash": "3aa50379e72725a2a079bced3ed090ac",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 42,
"avg_line_length": 14.727272727272727,
"alnum_prop": 0.6635802469135802,
"repo_name": "serainville/inquisitor",
"id": "87b36a685ae302863916bb46ddaf9312895fe9e4",
"size": "324",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/cpu.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "21220"
},
{
"name": "Makefile",
"bytes": "2529"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Biatorella geophana f. geophana (Nyl.) Rehm
### Remarks
null | {
"content_hash": "3633cad505501c64d28baebdb328f403",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 43,
"avg_line_length": 11.384615384615385,
"alnum_prop": 0.7027027027027027,
"repo_name": "mdoering/backbone",
"id": "70398f9aa5d3bfab7b1656a26f9ce6c66c1c655c",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Lecideaceae/Steinia/Steinia geophana/Biatorella geophana geophana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MINER_H
#define BITCOIN_MINER_H
#include "primitives/block.h"
#include "txmempool.h"
#include <stdint.h>
#include <memory>
#include "boost/multi_index_container.hpp"
#include "boost/multi_index/ordered_index.hpp"
class CBlockIndex;
class CChainParams;
class CReserveKey;
class CScript;
class CWallet;
namespace Consensus { struct Params; };
static const bool DEFAULT_PRINTPRIORITY = false;
struct CBlockTemplate
{
CBlock block;
std::vector<CAmount> vTxFees;
std::vector<int64_t> vTxSigOps;
};
// Container for tracking updates to ancestor feerate as we include (parent)
// transactions in a block
struct CTxMemPoolModifiedEntry {
CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
{
iter = entry;
nSizeWithAncestors = entry->GetSizeWithAncestors();
nModFeesWithAncestors = entry->GetModFeesWithAncestors();
nSigOpCountWithAncestors = entry->GetSigOpCountWithAncestors();
}
CTxMemPool::txiter iter;
uint64_t nSizeWithAncestors;
CAmount nModFeesWithAncestors;
unsigned int nSigOpCountWithAncestors;
};
/** Comparator for CTxMemPool::txiter objects.
* It simply compares the internal memory address of the CTxMemPoolEntry object
* pointed to. This means it has no meaning, and is only useful for using them
* as key in other indexes.
*/
struct CompareCTxMemPoolIter {
bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
{
return &(*a) < &(*b);
}
};
struct modifiedentry_iter {
typedef CTxMemPool::txiter result_type;
result_type operator() (const CTxMemPoolModifiedEntry &entry) const
{
return entry.iter;
}
};
// This matches the calculation in CompareTxMemPoolEntryByAncestorFee,
// except operating on CTxMemPoolModifiedEntry.
// TODO: refactor to avoid duplication of this logic.
struct CompareModifiedEntry {
bool operator()(const CTxMemPoolModifiedEntry &a, const CTxMemPoolModifiedEntry &b)
{
double f1 = (double)a.nModFeesWithAncestors * b.nSizeWithAncestors;
double f2 = (double)b.nModFeesWithAncestors * a.nSizeWithAncestors;
if (f1 == f2) {
return CTxMemPool::CompareIteratorByHash()(a.iter, b.iter);
}
return f1 > f2;
}
};
// A comparator that sorts transactions based on number of ancestors.
// This is sufficient to sort an ancestor package in an order that is valid
// to appear in a block.
struct CompareTxIterByAncestorCount {
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b)
{
if (a->GetCountWithAncestors() != b->GetCountWithAncestors())
return a->GetCountWithAncestors() < b->GetCountWithAncestors();
return CTxMemPool::CompareIteratorByHash()(a, b);
}
};
typedef boost::multi_index_container<
CTxMemPoolModifiedEntry,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
modifiedentry_iter,
CompareCTxMemPoolIter
>,
// sorted by modified ancestor fee rate
boost::multi_index::ordered_non_unique<
// Reuse same tag from CTxMemPool's similar index
boost::multi_index::tag<ancestor_score>,
boost::multi_index::identity<CTxMemPoolModifiedEntry>,
CompareModifiedEntry
>
>
> indexed_modified_transaction_set;
typedef indexed_modified_transaction_set::nth_index<0>::type::iterator modtxiter;
typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator modtxscoreiter;
struct update_for_parent_inclusion
{
update_for_parent_inclusion(CTxMemPool::txiter it) : iter(it) {}
void operator() (CTxMemPoolModifiedEntry &e)
{
e.nModFeesWithAncestors -= iter->GetFee();
e.nSizeWithAncestors -= iter->GetTxSize();
e.nSigOpCountWithAncestors -= iter->GetSigOpCount();
}
CTxMemPool::txiter iter;
};
/** Generate a new block, without valid proof-of-work */
class BlockAssembler
{
private:
// The constructed block template
std::unique_ptr<CBlockTemplate> pblocktemplate;
// A convenience pointer that always refers to the CBlock in pblocktemplate
CBlock* pblock;
// Configuration parameters for the block size
unsigned int nBlockMaxSize, nBlockMinSize;
// Information on the current status of the block
uint64_t nBlockSize;
uint64_t nBlockTx;
unsigned int nBlockSigOps;
CAmount nFees;
CTxMemPool::setEntries inBlock;
// Chain context for the block
int nHeight;
int64_t nLockTimeCutoff;
const CChainParams& chainparams;
// Variables used for addScoreTxs and addPriorityTxs
int lastFewTxs;
bool blockFinished;
public:
BlockAssembler(const CChainParams& chainparams);
/** Construct a new block template with coinbase to scriptPubKeyIn */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
private:
// utility functions
/** Clear the block's state and prepare for assembling a new block */
void resetBlock();
/** Add a tx to the block */
void AddToBlock(CTxMemPool::txiter iter);
// Methods for how to add transactions to a block.
/** Add transactions based on modified feerate */
void addScoreTxs();
/** Add transactions based on tx "priority" */
void addPriorityTxs();
/** Add transactions based on feerate including unconfirmed ancestors */
void addPackageTxs();
// helper function for addScoreTxs and addPriorityTxs
/** Test if tx will still "fit" in the block */
bool TestForBlock(CTxMemPool::txiter iter);
/** Test if tx still has unconfirmed parents not yet in block */
bool isStillDependent(CTxMemPool::txiter iter);
// helper functions for addPackageTxs()
/** Remove confirmed (inBlock) entries from given set */
void onlyUnconfirmed(CTxMemPool::setEntries& testSet);
/** Test if a new package would "fit" in the block */
bool TestPackage(uint64_t packageSize, unsigned int packageSigOps);
/** Test if a set of transactions are all final */
bool TestPackageFinality(const CTxMemPool::setEntries& package);
/** Return true if given transaction from mapTx has already been evaluated,
* or if the transaction's cached data in mapTx is incorrect. */
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx);
/** Sort the package in an order that is valid to appear in a block */
void SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries);
/** Add descendants of given transactions to mapModifiedTx with ancestor
* state updated assuming given transactions are inBlock. */
void UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded, indexed_modified_transaction_set &mapModifiedTx);
};
/** Modify the extranonce in a block */
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
#endif // BITCOIN_MINER_H
| {
"content_hash": "59a8c4678dacee1efbcf881da593b71a",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 135,
"avg_line_length": 35.82125603864734,
"alnum_prop": 0.7159811193526635,
"repo_name": "Alonzo-Coeus/bitcoin",
"id": "a9fea85304aa69a96172709b03a292e4b0ddb81d",
"size": "7415",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/miner.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "678017"
},
{
"name": "C++",
"bytes": "4463748"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Groff",
"bytes": "3792"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2100"
},
{
"name": "M4",
"bytes": "174352"
},
{
"name": "Makefile",
"bytes": "101175"
},
{
"name": "Objective-C",
"bytes": "3660"
},
{
"name": "Objective-C++",
"bytes": "7240"
},
{
"name": "Protocol Buffer",
"bytes": "2308"
},
{
"name": "Python",
"bytes": "773874"
},
{
"name": "QMake",
"bytes": "2020"
},
{
"name": "Shell",
"bytes": "30307"
}
],
"symlink_target": ""
} |
template< typename R , typename T0 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,1> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) ( NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,2> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,3> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 , typename T3 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,4> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 , T3 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,5> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 , T3 , T4 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,6> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,7> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,8> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,9> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 >
typename encode_charr<NDNBOOST_FT_flags,NDNBOOST_FT_cc_id,10> ::type
classifier_impl(NDNBOOST_FT_syntax(NDNBOOST_FT_cc, NDNBOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 NDNBOOST_FT_ell) NDNBOOST_FT_cv);
| {
"content_hash": "437c79addb26e6a4e4cc6218a604749c",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 162,
"avg_line_length": 94.83870967741936,
"alnum_prop": 0.7350340136054422,
"repo_name": "cawka/packaging-ndn-cpp-dev",
"id": "627ec516bdfb42a0cdda3d378d7d66d727a2bb45",
"size": "3878",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "include/ndnboost/function_types/detail/classifier_impl/arity10_1.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "156170"
},
{
"name": "C++",
"bytes": "17434003"
},
{
"name": "Objective-C",
"bytes": "4125"
},
{
"name": "Perl",
"bytes": "2057"
},
{
"name": "Shell",
"bytes": "187"
}
],
"symlink_target": ""
} |
namespace Serenity.Services
{
public class ListRequestHandler<TRow> : ListRequestHandler<TRow, ListRequest, ListResponse<TRow>>,
IListHandler<TRow>, IListHandler<TRow, ListRequest>
where TRow : class, IRow, new()
{
public ListRequestHandler(IRequestContext context)
: base(context)
{
}
}
} | {
"content_hash": "7e6f3b68c943d55b4af725120a875b60",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 102,
"avg_line_length": 30.416666666666668,
"alnum_prop": 0.6246575342465753,
"repo_name": "volkanceylan/Serenity",
"id": "1503a86679bd629f8f946524616d76c8fc48127b",
"size": "367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Serenity.Net.Services/RequestHandlers/List/ListRequestHandlerT.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1592"
},
{
"name": "C#",
"bytes": "3328213"
},
{
"name": "CSS",
"bytes": "198506"
},
{
"name": "HTML",
"bytes": "2818"
},
{
"name": "JavaScript",
"bytes": "638940"
},
{
"name": "Roff",
"bytes": "11586"
},
{
"name": "Shell",
"bytes": "287"
},
{
"name": "Smalltalk",
"bytes": "290"
},
{
"name": "TSQL",
"bytes": "1592"
},
{
"name": "TypeScript",
"bytes": "804757"
},
{
"name": "XSLT",
"bytes": "17702"
}
],
"symlink_target": ""
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <freerdp/gdi/gdi.h>
#include <freerdp/constants.h>
#include <freerdp/codec/color.h>
#include <freerdp/codec/bitmap.h>
#include <freerdp/codec/rfx.h>
#include <freerdp/codec/nsc.h>
#include "wf_interface.h"
#include "wf_graphics.h"
const BYTE wf_rop2_table[] =
{
R2_BLACK, /* 0 */
R2_NOTMERGEPEN, /* DPon */
R2_MASKNOTPEN, /* DPna */
R2_NOTCOPYPEN, /* Pn */
R2_MASKPENNOT, /* PDna */
R2_NOT, /* Dn */
R2_XORPEN, /* DPx */
R2_NOTMASKPEN, /* DPan */
R2_MASKPEN, /* DPa */
R2_NOTXORPEN, /* DPxn */
R2_NOP, /* D */
R2_MERGENOTPEN, /* DPno */
R2_COPYPEN, /* P */
R2_MERGEPENNOT, /* PDno */
R2_MERGEPEN, /* PDo */
R2_WHITE, /* 1 */
};
BOOL wf_set_rop2(HDC hdc, int rop2)
{
if ((rop2 < 0x01) || (rop2 > 0x10))
{
printf("Unsupported ROP2: %d\n", rop2);
return FALSE;
}
SetROP2(hdc, wf_rop2_table[rop2 - 1]);
return TRUE;
}
wfBitmap* wf_glyph_new(wfInfo* wfi, GLYPH_DATA* glyph)
{
wfBitmap* glyph_bmp;
glyph_bmp = wf_image_new(wfi, glyph->cx, glyph->cy, 1, glyph->aj);
return glyph_bmp;
}
void wf_glyph_free(wfBitmap* glyph)
{
wf_image_free(glyph);
}
BYTE* wf_glyph_convert(wfInfo* wfi, int width, int height, BYTE* data)
{
int indexx;
int indexy;
BYTE* src;
BYTE* dst;
BYTE* cdata;
int src_bytes_per_row;
int dst_bytes_per_row;
src_bytes_per_row = (width + 7) / 8;
dst_bytes_per_row = src_bytes_per_row + (src_bytes_per_row % 2);
cdata = (BYTE *) malloc(dst_bytes_per_row * height);
src = data;
for (indexy = 0; indexy < height; indexy++)
{
dst = cdata + indexy * dst_bytes_per_row;
for (indexx = 0; indexx < dst_bytes_per_row; indexx++)
{
if (indexx < src_bytes_per_row)
*dst++ = *src++;
else
*dst++ = 0;
}
}
return cdata;
}
HBRUSH wf_create_brush(wfInfo * wfi, rdpBrush* brush, UINT32 color, int bpp)
{
int i;
HBRUSH br;
LOGBRUSH lbr;
BYTE* cdata;
BYTE ipattern[8];
HBITMAP pattern = NULL;
lbr.lbStyle = brush->style;
if (lbr.lbStyle == BS_DIBPATTERN || lbr.lbStyle == BS_DIBPATTERN8X8 || lbr.lbStyle == BS_DIBPATTERNPT)
lbr.lbColor = DIB_RGB_COLORS;
else
lbr.lbColor = color;
if (lbr.lbStyle == BS_PATTERN || lbr.lbStyle == BS_PATTERN8X8)
{
if (brush->bpp > 1)
{
pattern = wf_create_dib(wfi, 8, 8, bpp, brush->data, NULL);
lbr.lbHatch = (ULONG_PTR) pattern;
}
else
{
for (i = 0; i != 8; i++)
ipattern[7 - i] = brush->data[i];
cdata = wf_glyph_convert(wfi, 8, 8, ipattern);
pattern = CreateBitmap(8, 8, 1, 1, cdata);
lbr.lbHatch = (ULONG_PTR) pattern;
free(cdata);
}
}
else if (lbr.lbStyle == BS_HATCHED)
{
lbr.lbHatch = brush->hatch;
}
else
{
lbr.lbHatch = 0;
}
br = CreateBrushIndirect(&lbr);
SetBrushOrgEx(wfi->drawing->hdc, brush->x, brush->y, NULL);
if (pattern != NULL)
DeleteObject(pattern);
return br;
}
void wf_invalidate_region(wfInfo* wfi, int x, int y, int width, int height)
{
wfi->update_rect.left = x + wfi->offset_x;
wfi->update_rect.top = y + wfi->offset_y;
wfi->update_rect.right = wfi->update_rect.left + width;
wfi->update_rect.bottom = wfi->update_rect.top + height;
InvalidateRect(wfi->hwnd, &(wfi->update_rect), FALSE);
gdi_InvalidateRegion(wfi->hdc, x, y, width, height);
}
void wf_update_offset(wfInfo* wfi)
{
if (wfi->fullscreen)
{
wfi->offset_x = (GetSystemMetrics(SM_CXSCREEN) - wfi->width) / 2;
if (wfi->offset_x < 0)
wfi->offset_x = 0;
wfi->offset_y = (GetSystemMetrics(SM_CYSCREEN) - wfi->height) / 2;
if (wfi->offset_y < 0)
wfi->offset_y = 0;
}
else
{
wfi->offset_x = 0;
wfi->offset_y = 0;
}
}
void wf_resize_window(wfInfo* wfi)
{
if (wfi->fullscreen)
{
SetWindowLongPtr(wfi->hwnd, GWL_STYLE, WS_POPUP);
SetWindowPos(wfi->hwnd, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED);
}
else
{
RECT rc_client, rc_wnd;
SetWindowLongPtr(wfi->hwnd, GWL_STYLE, WS_CAPTION | WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX);
/* Now resize to get full canvas size and room for caption and borders */
SetWindowPos(wfi->hwnd, HWND_TOP, 10, 10, wfi->width, wfi->height, SWP_FRAMECHANGED);
GetClientRect(wfi->hwnd, &rc_client);
GetWindowRect(wfi->hwnd, &rc_wnd);
wfi->diff.x = (rc_wnd.right - rc_wnd.left) - rc_client.right;
wfi->diff.y = (rc_wnd.bottom - rc_wnd.top) - rc_client.bottom;
SetWindowPos(wfi->hwnd, HWND_TOP, -1, -1, wfi->width + wfi->diff.x, wfi->height + wfi->diff.y, SWP_NOMOVE | SWP_FRAMECHANGED);
}
wf_update_offset(wfi);
}
void wf_toggle_fullscreen(wfInfo* wfi)
{
ShowWindow(wfi->hwnd, SW_HIDE);
wfi->fullscreen = !wfi->fullscreen;
wf_resize_window(wfi);
ShowWindow(wfi->hwnd, SW_SHOW);
SetForegroundWindow(wfi->hwnd);
}
void wf_gdi_palette_update(rdpContext* context, PALETTE_UPDATE* palette)
{
}
void wf_set_null_clip_rgn(wfInfo* wfi)
{
SelectClipRgn(wfi->drawing->hdc, NULL);
}
void wf_set_clip_rgn(wfInfo* wfi, int x, int y, int width, int height)
{
HRGN clip;
clip = CreateRectRgn(x, y, x + width, y + height);
SelectClipRgn(wfi->drawing->hdc, clip);
DeleteObject(clip);
}
void wf_gdi_set_bounds(rdpContext* context, rdpBounds* bounds)
{
HRGN hrgn;
wfInfo* wfi = ((wfContext*) context)->wfi;
if (bounds != NULL)
{
hrgn = CreateRectRgn(bounds->left, bounds->top, bounds->right + 1, bounds->bottom + 1);
SelectClipRgn(wfi->drawing->hdc, hrgn);
DeleteObject(hrgn);
}
else
{
SelectClipRgn(wfi->drawing->hdc, NULL);
}
}
void wf_gdi_dstblt(rdpContext* context, DSTBLT_ORDER* dstblt)
{
wfInfo* wfi = ((wfContext*) context)->wfi;
BitBlt(wfi->drawing->hdc, dstblt->nLeftRect, dstblt->nTopRect,
dstblt->nWidth, dstblt->nHeight, NULL, 0, 0, gdi_rop3_code(dstblt->bRop));
wf_invalidate_region(wfi, dstblt->nLeftRect, dstblt->nTopRect,
dstblt->nWidth, dstblt->nHeight);
}
void wf_gdi_patblt(rdpContext* context, PATBLT_ORDER* patblt)
{
HBRUSH brush;
HBRUSH org_brush;
int org_bkmode;
UINT32 fgcolor;
UINT32 bgcolor;
COLORREF org_bkcolor;
COLORREF org_textcolor;
wfInfo* wfi = ((wfContext*) context)->wfi;
fgcolor = freerdp_color_convert_bgr(patblt->foreColor, wfi->srcBpp, wfi->dstBpp, wfi->clrconv);
bgcolor = freerdp_color_convert_bgr(patblt->backColor, wfi->srcBpp, wfi->dstBpp, wfi->clrconv);
brush = wf_create_brush(wfi, &patblt->brush, fgcolor, wfi->srcBpp);
org_bkmode = SetBkMode(wfi->drawing->hdc, OPAQUE);
org_bkcolor = SetBkColor(wfi->drawing->hdc, bgcolor);
org_textcolor = SetTextColor(wfi->drawing->hdc, fgcolor);
org_brush = (HBRUSH)SelectObject(wfi->drawing->hdc, brush);
PatBlt(wfi->drawing->hdc, patblt->nLeftRect, patblt->nTopRect,
patblt->nWidth, patblt->nHeight, gdi_rop3_code(patblt->bRop));
SelectObject(wfi->drawing->hdc, org_brush);
DeleteObject(brush);
SetBkMode(wfi->drawing->hdc, org_bkmode);
SetBkColor(wfi->drawing->hdc, org_bkcolor);
SetTextColor(wfi->drawing->hdc, org_textcolor);
if (wfi->drawing == wfi->primary)
wf_invalidate_region(wfi, patblt->nLeftRect, patblt->nTopRect, patblt->nWidth, patblt->nHeight);
}
void wf_gdi_scrblt(rdpContext* context, SCRBLT_ORDER* scrblt)
{
wfInfo* wfi = ((wfContext*) context)->wfi;
BitBlt(wfi->drawing->hdc, scrblt->nLeftRect, scrblt->nTopRect,
scrblt->nWidth, scrblt->nHeight, wfi->primary->hdc,
scrblt->nXSrc, scrblt->nYSrc, gdi_rop3_code(scrblt->bRop));
wf_invalidate_region(wfi, scrblt->nLeftRect, scrblt->nTopRect,
scrblt->nWidth, scrblt->nHeight);
}
void wf_gdi_opaque_rect(rdpContext* context, OPAQUE_RECT_ORDER* opaque_rect)
{
RECT rect;
HBRUSH brush;
UINT32 brush_color;
wfInfo* wfi = ((wfContext*) context)->wfi;
brush_color = freerdp_color_convert_var_bgr(opaque_rect->color, wfi->srcBpp, wfi->dstBpp, wfi->clrconv);
rect.left = opaque_rect->nLeftRect;
rect.top = opaque_rect->nTopRect;
rect.right = opaque_rect->nLeftRect + opaque_rect->nWidth;
rect.bottom = opaque_rect->nTopRect + opaque_rect->nHeight;
brush = CreateSolidBrush(brush_color);
FillRect(wfi->drawing->hdc, &rect, brush);
DeleteObject(brush);
if (wfi->drawing == wfi->primary)
wf_invalidate_region(wfi, rect.left, rect.top, rect.right - rect.left + 1, rect.bottom - rect.top + 1);
}
void wf_gdi_multi_opaque_rect(rdpContext* context, MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect)
{
int i;
RECT rect;
HBRUSH brush;
UINT32 brush_color;
DELTA_RECT* rectangle;
wfInfo* wfi = ((wfContext*) context)->wfi;
for (i = 1; i < (int) multi_opaque_rect->numRectangles + 1; i++)
{
rectangle = &multi_opaque_rect->rectangles[i];
brush_color = freerdp_color_convert_var_bgr(multi_opaque_rect->color, wfi->srcBpp, wfi->dstBpp, wfi->clrconv);
rect.left = rectangle->left;
rect.top = rectangle->top;
rect.right = rectangle->left + rectangle->width;
rect.bottom = rectangle->top + rectangle->height;
brush = CreateSolidBrush(brush_color);
brush = CreateSolidBrush(brush_color);
FillRect(wfi->drawing->hdc, &rect, brush);
if (wfi->drawing == wfi->primary)
wf_invalidate_region(wfi, rect.left, rect.top, rect.right - rect.left + 1, rect.bottom - rect.top + 1);
DeleteObject(brush);
}
}
void wf_gdi_line_to(rdpContext* context, LINE_TO_ORDER* line_to)
{
HPEN pen;
HPEN org_pen;
int x, y, w, h;
UINT32 pen_color;
wfInfo* wfi = ((wfContext*) context)->wfi;
pen_color = freerdp_color_convert_bgr(line_to->penColor, wfi->srcBpp, wfi->dstBpp, wfi->clrconv);
pen = CreatePen(line_to->penStyle, line_to->penWidth, pen_color);
wf_set_rop2(wfi->drawing->hdc, line_to->bRop2);
org_pen = (HPEN) SelectObject(wfi->drawing->hdc, pen);
MoveToEx(wfi->drawing->hdc, line_to->nXStart, line_to->nYStart, NULL);
LineTo(wfi->drawing->hdc, line_to->nXEnd, line_to->nYEnd);
x = (line_to->nXStart < line_to->nXEnd) ? line_to->nXStart : line_to->nXEnd;
y = (line_to->nYStart < line_to->nYEnd) ? line_to->nYStart : line_to->nYEnd;
w = (line_to->nXStart < line_to->nXEnd) ? (line_to->nXEnd - line_to->nXStart) : (line_to->nXStart - line_to->nXEnd);
h = (line_to->nYStart < line_to->nYEnd) ? (line_to->nYEnd - line_to->nYStart) : (line_to->nYStart - line_to->nYEnd);
if (wfi->drawing == wfi->primary)
wf_invalidate_region(wfi, x, y, w, h);
SelectObject(wfi->drawing->hdc, org_pen);
DeleteObject(pen);
}
void wf_gdi_polyline(rdpContext* context, POLYLINE_ORDER* polyline)
{
int i;
POINT* pts;
int org_rop2;
HPEN hpen;
HPEN org_hpen;
UINT32 pen_color;
wfInfo* wfi = ((wfContext*) context)->wfi;
pen_color = freerdp_color_convert_bgr(polyline->penColor, wfi->srcBpp, wfi->dstBpp, wfi->clrconv);
hpen = CreatePen(0, 1, pen_color);
org_rop2 = wf_set_rop2(wfi->drawing->hdc, polyline->bRop2);
org_hpen = (HPEN) SelectObject(wfi->drawing->hdc, hpen);
if (polyline->numPoints > 0)
{
pts = (POINT*) malloc(sizeof(POINT) * polyline->numPoints);
for (i = 0; i < (int) polyline->numPoints; i++)
{
pts[i].x = polyline->points[i].x;
pts[i].y = polyline->points[i].y;
if (wfi->drawing == wfi->primary)
wf_invalidate_region(wfi, pts[i].x, pts[i].y, pts[i].x + 1, pts[i].y + 1);
}
Polyline(wfi->drawing->hdc, pts, polyline->numPoints);
free(pts);
}
SelectObject(wfi->drawing->hdc, org_hpen);
wf_set_rop2(wfi->drawing->hdc, org_rop2);
DeleteObject(hpen);
}
void wf_gdi_memblt(rdpContext* context, MEMBLT_ORDER* memblt)
{
wfBitmap* bitmap;
wfInfo* wfi = ((wfContext*) context)->wfi;
bitmap = (wfBitmap*) memblt->bitmap;
BitBlt(wfi->drawing->hdc, memblt->nLeftRect, memblt->nTopRect,
memblt->nWidth, memblt->nHeight, bitmap->hdc,
memblt->nXSrc, memblt->nYSrc, gdi_rop3_code(memblt->bRop));
if (wfi->drawing == wfi->primary)
wf_invalidate_region(wfi, memblt->nLeftRect, memblt->nTopRect, memblt->nWidth, memblt->nHeight);
}
void wf_gdi_surface_bits(rdpContext* context, SURFACE_BITS_COMMAND* surface_bits_command)
{
int i, j;
int tx, ty;
char* tile_bitmap;
RFX_MESSAGE* message;
BITMAPINFO bitmap_info;
wfInfo* wfi = ((wfContext*) context)->wfi;
RFX_CONTEXT* rfx_context = (RFX_CONTEXT*) wfi->rfx_context;
NSC_CONTEXT* nsc_context = (NSC_CONTEXT*) wfi->nsc_context;
tile_bitmap = (char*) malloc(32);
ZeroMemory(tile_bitmap, 32);
if (surface_bits_command->codecID == RDP_CODEC_ID_REMOTEFX)
{
message = rfx_process_message(rfx_context, surface_bits_command->bitmapData, surface_bits_command->bitmapDataLength);
/* blit each tile */
for (i = 0; i < message->num_tiles; i++)
{
tx = message->tiles[i]->x + surface_bits_command->destLeft;
ty = message->tiles[i]->y + surface_bits_command->destTop;
freerdp_image_convert(message->tiles[i]->data, wfi->tile->pdata, 64, 64, 32, 32, wfi->clrconv);
for (j = 0; j < message->num_rects; j++)
{
wf_set_clip_rgn(wfi,
surface_bits_command->destLeft + message->rects[j].x,
surface_bits_command->destTop + message->rects[j].y,
message->rects[j].width, message->rects[j].height);
BitBlt(wfi->primary->hdc, tx, ty, 64, 64, wfi->tile->hdc, 0, 0, SRCCOPY);
}
}
wf_set_null_clip_rgn(wfi);
/* invalidate regions */
for (i = 0; i < message->num_rects; i++)
{
tx = surface_bits_command->destLeft + message->rects[i].x;
ty = surface_bits_command->destTop + message->rects[i].y;
wf_invalidate_region(wfi, tx, ty, message->rects[i].width, message->rects[i].height);
}
rfx_message_free(rfx_context, message);
}
else if (surface_bits_command->codecID == RDP_CODEC_ID_NSCODEC)
{
nsc_process_message(nsc_context, surface_bits_command->bpp, surface_bits_command->width, surface_bits_command->height,
surface_bits_command->bitmapData, surface_bits_command->bitmapDataLength);
ZeroMemory(&bitmap_info, sizeof(bitmap_info));
bitmap_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmap_info.bmiHeader.biWidth = surface_bits_command->width;
bitmap_info.bmiHeader.biHeight = surface_bits_command->height;
bitmap_info.bmiHeader.biPlanes = 1;
bitmap_info.bmiHeader.biBitCount = surface_bits_command->bpp;
bitmap_info.bmiHeader.biCompression = BI_RGB;
SetDIBitsToDevice(wfi->primary->hdc, surface_bits_command->destLeft, surface_bits_command->destTop,
surface_bits_command->width, surface_bits_command->height, 0, 0, 0, surface_bits_command->height,
nsc_context->bmpdata, &bitmap_info, DIB_RGB_COLORS);
wf_invalidate_region(wfi, surface_bits_command->destLeft, surface_bits_command->destTop,
surface_bits_command->width, surface_bits_command->height);
}
else if (surface_bits_command->codecID == RDP_CODEC_ID_NONE)
{
ZeroMemory(&bitmap_info, sizeof(bitmap_info));
bitmap_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmap_info.bmiHeader.biWidth = surface_bits_command->width;
bitmap_info.bmiHeader.biHeight = surface_bits_command->height;
bitmap_info.bmiHeader.biPlanes = 1;
bitmap_info.bmiHeader.biBitCount = surface_bits_command->bpp;
bitmap_info.bmiHeader.biCompression = BI_RGB;
SetDIBitsToDevice(wfi->primary->hdc, surface_bits_command->destLeft, surface_bits_command->destTop,
surface_bits_command->width, surface_bits_command->height, 0, 0, 0, surface_bits_command->height,
surface_bits_command->bitmapData, &bitmap_info, DIB_RGB_COLORS);
wf_invalidate_region(wfi, surface_bits_command->destLeft, surface_bits_command->destTop,
surface_bits_command->width, surface_bits_command->height);
}
else
{
printf("Unsupported codecID %d\n", surface_bits_command->codecID);
}
if (tile_bitmap != NULL)
free(tile_bitmap);
}
void wf_gdi_surface_frame_marker(rdpContext* context, SURFACE_FRAME_MARKER* surface_frame_marker)
{
wfInfo* wfi;
rdpSettings* settings;
wfi = ((wfContext*) context)->wfi;
settings = wfi->instance->settings;
if (surface_frame_marker->frameAction == SURFACECMD_FRAMEACTION_END && settings->FrameAcknowledge > 0)
{
IFCALL(wfi->instance->update->SurfaceFrameAcknowledge, context, surface_frame_marker->frameId);
}
}
void wf_gdi_register_update_callbacks(rdpUpdate* update)
{
rdpPrimaryUpdate* primary = update->primary;
update->Palette = wf_gdi_palette_update;
update->SetBounds = wf_gdi_set_bounds;
primary->DstBlt = wf_gdi_dstblt;
primary->PatBlt = wf_gdi_patblt;
primary->ScrBlt = wf_gdi_scrblt;
primary->OpaqueRect = wf_gdi_opaque_rect;
primary->DrawNineGrid = NULL;
primary->MultiDstBlt = NULL;
primary->MultiPatBlt = NULL;
primary->MultiScrBlt = NULL;
primary->MultiOpaqueRect = wf_gdi_multi_opaque_rect;
primary->MultiDrawNineGrid = NULL;
primary->LineTo = wf_gdi_line_to;
primary->Polyline = wf_gdi_polyline;
primary->MemBlt = wf_gdi_memblt;
primary->Mem3Blt = NULL;
primary->SaveBitmap = NULL;
primary->GlyphIndex = NULL;
primary->FastIndex = NULL;
primary->FastGlyph = NULL;
primary->PolygonSC = NULL;
primary->PolygonCB = NULL;
primary->EllipseSC = NULL;
primary->EllipseCB = NULL;
update->SurfaceBits = wf_gdi_surface_bits;
update->SurfaceFrameMarker = wf_gdi_surface_frame_marker;
}
| {
"content_hash": "653ac1249336c7c0392810fda95e2034",
"timestamp": "",
"source": "github",
"line_count": 573,
"max_line_length": 128,
"avg_line_length": 29.37521815008726,
"alnum_prop": 0.6825689163498099,
"repo_name": "woshipike00/FreeRDP",
"id": "a78c281e34e47a94d38a7565bd0ebbac630496cb",
"size": "17601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/Windows/wf_gdi.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5612816"
},
{
"name": "C#",
"bytes": "12447"
},
{
"name": "C++",
"bytes": "730894"
},
{
"name": "Java",
"bytes": "306435"
},
{
"name": "Objective-C",
"bytes": "482486"
},
{
"name": "Perl",
"bytes": "8044"
},
{
"name": "Python",
"bytes": "1430"
},
{
"name": "Shell",
"bytes": "1686"
}
],
"symlink_target": ""
} |
"""
SoftLayer.tests.CLI.modules.config_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
import json
import tempfile
import mock
import SoftLayer
from SoftLayer import auth
from SoftLayer.CLI.config import setup as config
from SoftLayer.CLI import exceptions
from SoftLayer import consts
from SoftLayer import testing
from SoftLayer import transports
class TestHelpShow(testing.TestCase):
def set_up(self):
transport = transports.XmlRpcTransport(
endpoint_url='http://endpoint-url',
)
self.env.client = SoftLayer.BaseClient(
transport=transport,
auth=auth.BasicAuthentication('username', 'api-key'))
def test_show(self):
result = self.run_command(['config', 'show'])
self.assertEqual(result.exit_code, 0)
self.assertEqual(json.loads(result.output),
{'Username': 'username',
'API Key': 'api-key',
'Endpoint URL': 'http://endpoint-url',
'Timeout': 'not set'})
class TestHelpSetup(testing.TestCase):
def set_up(self):
super(TestHelpSetup, self).set_up()
# NOTE(kmcdonald): since the endpoint_url is changed with the client
# in these commands, we need to ensure that a fixtured transport is
# used.
transport = testing.MockableTransport(SoftLayer.FixtureTransport())
self.env.client = SoftLayer.BaseClient(transport=transport)
@mock.patch('SoftLayer.CLI.formatting.confirm')
@mock.patch('SoftLayer.CLI.environment.Environment.getpass')
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_setup(self, input, getpass, confirm_mock):
with tempfile.NamedTemporaryFile() as config_file:
confirm_mock.return_value = True
getpass.return_value = 'A' * 64
input.side_effect = ['user', 'public', 0]
result = self.run_command(['--config=%s' % config_file.name,
'config', 'setup'])
self.assertEqual(result.exit_code, 0)
self.assertTrue('Configuration Updated Successfully'
in result.output)
contents = config_file.read().decode("utf-8")
self.assertTrue('[softlayer]' in contents)
self.assertTrue('username = user' in contents)
self.assertTrue('api_key = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in contents)
self.assertTrue('endpoint_url = %s' % consts.API_PUBLIC_ENDPOINT
in contents)
@mock.patch('SoftLayer.CLI.formatting.confirm')
@mock.patch('SoftLayer.CLI.environment.Environment.getpass')
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_setup_cancel(self, input, getpass, confirm_mock):
with tempfile.NamedTemporaryFile() as config_file:
confirm_mock.return_value = False
getpass.return_value = 'A' * 64
input.side_effect = ['user', 'public', 0]
result = self.run_command(['--config=%s' % config_file.name,
'config', 'setup'])
self.assertEqual(result.exit_code, 2)
self.assertIsInstance(result.exception, exceptions.CLIAbort)
@mock.patch('SoftLayer.CLI.environment.Environment.getpass')
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_get_user_input_private(self, input, getpass):
getpass.return_value = 'A' * 64
input.side_effect = ['user', 'private', 0]
username, secret, endpoint_url, timeout = (
config.get_user_input(self.env))
self.assertEqual(username, 'user')
self.assertEqual(secret, 'A' * 64)
self.assertEqual(endpoint_url, consts.API_PRIVATE_ENDPOINT)
@mock.patch('SoftLayer.CLI.environment.Environment.getpass')
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_get_user_input_custom(self, input, getpass):
getpass.return_value = 'A' * 64
input.side_effect = ['user', 'custom', 'custom-endpoint', 0]
_, _, endpoint_url, _ = config.get_user_input(self.env)
self.assertEqual(endpoint_url, 'custom-endpoint')
@mock.patch('SoftLayer.CLI.environment.Environment.getpass')
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_get_user_input_default(self, input, getpass):
self.env.getpass.return_value = 'A' * 64
self.env.input.side_effect = ['user', 'public', 0]
_, _, endpoint_url, _ = config.get_user_input(self.env)
self.assertEqual(endpoint_url, consts.API_PUBLIC_ENDPOINT)
| {
"content_hash": "294f7950df4602db0cc45f052c704a67",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 76,
"avg_line_length": 39.33606557377049,
"alnum_prop": 0.6217962075432382,
"repo_name": "iftekeriba/softlayer-python",
"id": "db0ed6b8a58668d1dace482d5688d9eda292ec56",
"size": "4799",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "SoftLayer/tests/CLI/modules/config_tests.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "DIGITAL Command Language",
"bytes": "854"
},
{
"name": "Python",
"bytes": "744378"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>label: 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 / extra-dev</a></li>
<li class="active"><a href="">dev / label - 1.0.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
label
<small>
1.0.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-29 02:01:24 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-29 02:01:24 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq dev Formal proof management system
dune 3.0.3 Fast, portable, and opinionated build system
ocaml 4.11.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.2 Official release 4.11.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "pierre-evariste.dagand@lip6.fr"
homepage: "https://github.com/pedagand/coq-label"
dev-repo: "git+https://github.com/pedagand/coq-label.git"
bug-reports: "https://github.com/pedagand/coq-label/issues"
authors: ["Pierre-Évariste Dagand" "Théo Zimmermann" "Pierre-Marie Pédrot"]
license: "MIT"
build: [
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Label"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
synopsis:
"'label' is a Coq plugin for referring to Propositional hypotheses by their type"
flags: light-uninstall
url {
src:
"https://github.com/pedagand/coq-label/releases/download/v1.0.0/coq-label-1.0.0.tar.gz"
checksum: "md5=3ae47300d7985cf2ddb0ba87354d061c"
}
</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-label.1.0.0 coq.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq-label -> coq < 8.8~ -> ocaml < 4.10
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-label.1.0.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": "b7756a60df25554693dd07953d1f7498",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 159,
"avg_line_length": 40.24404761904762,
"alnum_prop": 0.5345363111965685,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "ab74df1d3d64209958d10b802d4fe12623d3b409",
"size": "6789",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.11.2-2.0.7/extra-dev/dev/label/1.0.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.