text
stringlengths 2
1.04M
| meta
dict |
|---|---|
"""test2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
|
{
"content_hash": "4c90c89ecfd1fd2c170518165744f735",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 77,
"avg_line_length": 35.95238095238095,
"alnum_prop": 0.6980132450331126,
"repo_name": "nacker/pythonProject",
"id": "4b179fbc8d2ea3c43837e7c9829388622675786d",
"size": "755",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Django/test2/test2/urls.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "104"
},
{
"name": "CSS",
"bytes": "218"
},
{
"name": "Python",
"bytes": "234188"
},
{
"name": "Shell",
"bytes": "12"
}
],
"symlink_target": ""
}
|
namespace HareDu.Model
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class Policy :
HareDuModel
{
public Policy()
{
Definition = new Dictionary<string, string>();
}
[JsonProperty("pattern")]
public string Pattern { get; set; }
[JsonProperty("definition")]
public Dictionary<string, string> Definition { get; set; }
[JsonProperty("priority")]
public int Priority { get; set; }
}
}
|
{
"content_hash": "41785bf8de731cdfb61435db355510f1",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 66,
"avg_line_length": 22.391304347826086,
"alnum_prop": 0.574757281553398,
"repo_name": "ahives/HareDu",
"id": "031b07a7f03a9ac858c9543aaa55aa2b3dfa132c",
"size": "1139",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/HareDu/Model/Policy.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "283327"
},
{
"name": "Ruby",
"bytes": "12287"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Threading;
namespace Enigma.Threading
{
/// <summary>
/// Manages a queue of work in the background with FIFO
/// </summary>
public class BackgroundQueue : IDisposable
{
private readonly Thread _thread;
private readonly SortedList<DateTime, CompositeBackgroundTask> _scheduledTasks;
private readonly AutoResetEvent _event;
private readonly ManualResetEventSlim _idleEvent;
private readonly object _tasksLock = new object();
private List<IBackgroundTask> _tasks;
private DateTime _nextTaskAt;
private bool _continue;
/// <summary>
/// How long the background queue remains idle before being forced to check the queue
/// </summary>
/// <remarks>
/// <para>This is to ensure that the queue never misses anything.
/// The event should make sure that we actually take care of everything
/// without forcing a control, but call us paranoid.</para>
/// <para>OnSet this to Times.Infinite to have it wait indefinetly</para>
/// </remarks>
public TimeSpan MaxIdleTime { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="BackgroundQueue"/> class.
/// </summary>
public BackgroundQueue()
{
_thread = new Thread(ThreadRun);
_scheduledTasks = new SortedList<DateTime, CompositeBackgroundTask>();
_tasks = new List<IBackgroundTask>();
_event = new AutoResetEvent(false);
_idleEvent = new ManualResetEventSlim(true);
MaxIdleTime = TimeSpan.FromMinutes(5);
_continue = true;
}
private void Stop()
{
_continue = false;
_event.Set();
}
/// <summary>
/// Enqueues the specified invoker.
/// </summary>
/// <param name="invoker">The invoker.</param>
public void Enqueue(InvokeHandler invoker)
{
Enqueue(new BackgroundTask {Invoker = invoker});
}
/// <summary>
/// Enqueues the specified invoker.
/// </summary>
/// <param name="invoker">The invoker.</param>
/// <param name="dueAt">The due at.</param>
public void Enqueue(InvokeHandler invoker, DateTime dueAt)
{
Enqueue(new BackgroundTask { Invoker = invoker }, dueAt);
}
/// <summary>
/// Enqueues the specified task.
/// </summary>
/// <param name="task">The task.</param>
public void Enqueue(IBackgroundTask task)
{
lock (_tasksLock)
_tasks.Add(task);
UpdateBackgroundWorker();
}
/// <summary>
/// Enqueues the specified task.
/// </summary>
/// <param name="task">The task.</param>
/// <param name="dueAt">The due at.</param>
public void Enqueue(IBackgroundTask task, DateTime dueAt)
{
if (dueAt <= DateTime.Now) {
Enqueue(task);
return;
}
CompositeBackgroundTask compositeTask;
lock (_scheduledTasks) {
if (!_scheduledTasks.TryGetValue(dueAt, out compositeTask)) {
compositeTask = new CompositeBackgroundTask();
_scheduledTasks.Add(dueAt, compositeTask);
}
}
compositeTask.Add(task);
UpdateBackgroundWorker(dueAt);
}
/// <summary>
/// Waits until idle.
/// </summary>
public void WaitUntilIdle()
{
_idleEvent.Wait();
}
/// <summary>
/// Waits until idle.
/// </summary>
/// <param name="timeout">The timeout.</param>
public void WaitUntilIdle(TimeSpan timeout)
{
_idleEvent.Wait(timeout);
}
private void UpdateBackgroundWorker()
{
if (_thread.ThreadState == ThreadState.Unstarted)
_thread.Start();
_event.Set();
}
private void UpdateBackgroundWorker(DateTime triggersAt)
{
if (_thread.ThreadState == ThreadState.Unstarted)
_thread.Start();
if (triggersAt < _nextTaskAt) {
_event.Set();
_nextTaskAt = triggersAt;
}
}
/// <summary>
/// The main working method of the thread.
/// </summary>
/// <param name="obj">An unused object argument.</param>
private void ThreadRun(object obj)
{
_idleEvent.Reset();
while (_continue){
if (_tasks.Count > 0) {
foreach (var task in DequeueTasks())
task.Invoke();
}
if (_scheduledTasks.Count == 0) {
_idleEvent.Set();
_event.WaitOne(MaxIdleTime);
_idleEvent.Reset();
continue;
}
var now = DateTime.Now;
var timeToNext = _nextTaskAt.Subtract(now);
if (timeToNext > TimeSpan.Zero) {
_idleEvent.Set();
_event.WaitOne(timeToNext > MaxIdleTime ? MaxIdleTime : timeToNext);
_idleEvent.Reset();
continue;
}
var dueTasks = GetDueTasks(now);
foreach (var task in dueTasks)
task.Invoke();
}
}
private IEnumerable<IBackgroundTask> DequeueTasks()
{
var tasks = _tasks;
lock (_tasksLock)
_tasks = new List<IBackgroundTask>();
return tasks;
}
private IEnumerable<IBackgroundTask> GetDueTasks(DateTime dueAt)
{
var result = new List<IBackgroundTask>();
lock (_scheduledTasks) {
while (true) {
if (_scheduledTasks.Count == 0) return result;
var taskDueAt = _scheduledTasks.Keys[0];
if (taskDueAt > dueAt) return result;
result.Add(_scheduledTasks.Values[0]);
_scheduledTasks.RemoveAt(0);
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <remarks>
/// <para>This will attempt to do a soft stop of the background queue lasting max 1 second.
/// If that fails, a hard stop will ensue.</para>
/// </remarks>
public void Dispose()
{
Stop();
if (_thread.ThreadState != ThreadState.Running) return;
_thread.Join(TimeSpan.FromSeconds(1));
if (_thread.ThreadState != ThreadState.Running) return;
_thread.Abort();
_thread.Join(TimeSpan.FromSeconds(1));
}
}
}
|
{
"content_hash": "df442c33e48caa85912844ca0e2ba3ea",
"timestamp": "",
"source": "github",
"line_count": 221,
"max_line_length": 116,
"avg_line_length": 32.46153846153846,
"alnum_prop": 0.5160301087259548,
"repo_name": "jaygumji/EnigmaDb",
"id": "15b73644ee7e380bb6034c1d27c12974225666e0",
"size": "7176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Enigma/Threading/BackgroundQueue.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "752774"
}
],
"symlink_target": ""
}
|
namespace DeJong.Utilities.Logging
{
using Core;
using System;
public static partial class Log
{
private static bool loggerActive;
private static event Action loggerDispose;
internal static void AddLogger(IDisposable sender)
{
LoggedException.RaiseIf(loggerActive, nameof(ConsoleLogger), "A logger is already active!");
loggerActive = true;
loggerDispose += sender.Dispose;
}
internal static void RemoveLogger()
{
if (!loggerActive) Warning(nameof(Log), "Attempted to remove non excisting logger!");
loggerActive = false;
loggerDispose = null;
}
internal static void Dispose()
{
if (loggerActive) loggerDispose();
logThread?.Dispose();
garbage.Dispose();
msgbuffer.Dispose();
listener.Dispose();
}
}
}
|
{
"content_hash": "2da9f94b15dc648c7d1b7f6b0c9433a7",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 104,
"avg_line_length": 27.823529411764707,
"alnum_prop": 0.5782241014799154,
"repo_name": "Arzana/DeJongUtils",
"id": "03677f37b1190ff8dd3863a900d33ed8e6e204ba",
"size": "948",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Utilities/Utilities/Logging/Log_dispose.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "193624"
}
],
"symlink_target": ""
}
|
SabisuRails::Engine.routes.draw do
get "explorer", to: "explorer#index"
end
|
{
"content_hash": "7c71b7bbff95f2755cb86d9f53ab2cf7",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 38,
"avg_line_length": 26,
"alnum_prop": 0.7435897435897436,
"repo_name": "mallikarjunayaddala/sabisu-rails",
"id": "1f31c2df319cbff48ad4664abfea1803e428092e",
"size": "78",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "config/routes.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3453"
},
{
"name": "CoffeeScript",
"bytes": "1741"
},
{
"name": "HTML",
"bytes": "5448"
},
{
"name": "JavaScript",
"bytes": "564"
},
{
"name": "Ruby",
"bytes": "13544"
}
],
"symlink_target": ""
}
|
require 'spec_helper'
shared_examples_for 'splunk forwarder' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('splunk') }
it { is_expected.to contain_class('splunk::params') }
it { is_expected.to contain_class('splunk::forwarder') }
it { is_expected.to contain_class('splunk::forwarder::install') }
it { is_expected.to contain_class('splunk::forwarder::config') }
it { is_expected.to contain_class('splunk::forwarder::service') }
it { is_expected.to contain_splunk_config('splunk') }
it { is_expected.to contain_package('splunkforwarder').with(ensure: 'installed') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/deploymentclient.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/outputs.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/inputs.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/limits.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/props.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/transforms.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/web.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/limits.conf') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/system/local/server.conf') }
it { is_expected.to contain_splunkforwarder_web('forwarder_splunkd_port').with(value: '127.0.0.1:8089') }
it { is_expected.not_to contain_file('/opt/splunkforwarder/etc/splunk.secret') }
it { is_expected.not_to contain_file('/opt/splunkforwarder/etc/passwd') }
end
describe 'splunk::forwarder' do
context 'supported operating systems' do
on_supported_os.each do |os, facts|
if os.start_with?('windows')
# Splunk Server not used supported on windows
else
context "on #{os}" do
let(:facts) do
facts
end
context 'splunk when including forwarder and enterprise' do
let(:pre_condition) do
'include splunk::enterprise'
end
it { is_expected.to compile.and_raise_error(%r{Do not include splunk::forwarder on the same node as splunk::enterprise}) }
end
context 'when manage_password = true' do
if facts[:kernel] == 'Linux' || facts[:kernel] == 'SunOS'
let(:params) { { 'manage_password' => true } }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/splunk.secret') }
it { is_expected.to contain_file('/opt/splunkforwarder/etc/passwd') }
end
end
context 'when package_provider = yum' do
if facts[:kernel] == 'Linux' || facts[:kernel] == 'SunOS'
let(:params) { { 'package_provider' => 'yum' } }
it { is_expected.to contain_package('splunkforwarder').with(provider: 'yum') }
end
end
context 'with $boot_start = true (defaults)' do
if facts[:kernel] == 'Linux' || facts[:kernel] == 'SunOS'
context 'with $facts[service_provider] == init and $splunk::params::version >= 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'init')
end
let(:pre_condition) do
"class { 'splunk::params': version => '7.2.2' }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'splunk') }
it { is_expected.to contain_exec('stop_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk stop') }
it { is_expected.to contain_exec('enable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk enable boot-start -user root --accept-license --answer-yes --no-prompt') }
it { is_expected.not_to contain_exec('disable_splunkforwarder') }
it { is_expected.not_to contain_exec('license_splunkforwarder') }
it { is_expected.to contain_service('splunk').with(ensure: 'running', enable: true, status: nil, restart: nil, start: nil, stop: nil) }
end
context 'with $facts[service_provider] == init and $splunk::params::version < 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'init')
end
let(:pre_condition) do
"class { 'splunk::params': version => '6.0.0' }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'splunk') }
it { is_expected.to contain_exec('stop_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk stop') }
it { is_expected.to contain_exec('enable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk enable boot-start -user root --accept-license --answer-yes --no-prompt') }
it { is_expected.not_to contain_exec('disable_splunkforwarder') }
it { is_expected.not_to contain_exec('license_splunkforwarder') }
it { is_expected.to contain_service('splunk').with(ensure: 'running', enable: true, status: nil, restart: nil, start: nil, stop: nil) }
end
context 'with $facts[service_provider] == systemd and $splunk::params::version >= 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'systemd')
end
let(:pre_condition) do
"class { 'splunk::params': version => '7.2.2' }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'SplunkForwarder') }
it { is_expected.to contain_exec('stop_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk stop') }
it { is_expected.to contain_exec('enable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk enable boot-start -systemd-managed 1 --accept-license --answer-yes --no-prompt') }
it { is_expected.not_to contain_exec('disable_splunkforwarder') }
it { is_expected.not_to contain_exec('license_splunkforwarder') }
it { is_expected.to contain_service('SplunkForwarder').with(ensure: 'running', enable: true, status: nil, restart: nil, start: nil, stop: nil) }
end
context 'with $facts[service_provider] == systemd and $splunk::params::version >= 7.2.2 and user != root' do
let(:facts) do
facts.merge(service_provider: 'systemd')
end
let(:pre_condition) do
"class { 'splunk::params': version => '7.2.2' }"
end
let(:params) { { splunk_user: 'splunk' } }
it { is_expected.to contain_exec('enable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk enable boot-start -user splunk -systemd-managed 1 --accept-license --answer-yes --no-prompt') }
end
context 'with $facts[service_provider] == systemd and $splunk::params::version < 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'systemd')
end
let(:pre_condition) do
"class { 'splunk::params': version => '6.0.0' }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'splunk') }
it { is_expected.to contain_exec('stop_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk stop') }
it { is_expected.to contain_exec('enable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk enable boot-start -user root --accept-license --answer-yes --no-prompt') }
it { is_expected.not_to contain_exec('disable_splunkforwarder') }
it { is_expected.not_to contain_exec('license_splunkforwarder') }
it { is_expected.to contain_service('splunk').with(ensure: 'running', enable: true, status: nil, restart: nil, start: nil, stop: nil) }
end
end
end
context 'with $boot_start = false' do
if facts[:kernel] == 'Linux' || facts[:kernel] == 'SunOS'
context 'with $facts[service_provider] == init and $splunk::params::version >= 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'init')
end
let(:pre_condition) do
"class { 'splunk::params': version => '7.2.2', boot_start => false }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'splunk') }
it { is_expected.not_to contain_exec('stop_splunkforwarder') }
it { is_expected.not_to contain_exec('enable_splunkforwarder') }
it { is_expected.to contain_exec('disable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk disable boot-start -user root --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_exec('license_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk ftr --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_service('splunk').with(restart: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk restart'", start: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk start'", stop: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk stop'", status: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk status'") }
end
context 'with $facts[service_provider] == init and $splunk::params::version < 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'init')
end
let(:pre_condition) do
"class { 'splunk::params': version => '6.0.0', boot_start => false }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'splunk') }
it { is_expected.not_to contain_exec('stop_splunkforwarder') }
it { is_expected.not_to contain_exec('enable_splunkforwarder') }
it { is_expected.to contain_exec('disable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk disable boot-start -user root --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_exec('license_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk ftr --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_service('splunk').with(restart: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk restart'", start: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk start'", stop: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk stop'", status: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk status'") }
end
context 'with $facts[service_provider] == systemd and $splunk::params::version >= 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'systemd')
end
let(:pre_condition) do
"class { 'splunk::params': version => '7.2.2', boot_start => false }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'SplunkForwarder') }
it { is_expected.not_to contain_exec('stop_splunkforwarder') }
it { is_expected.not_to contain_exec('enable_splunkforwarder') }
it { is_expected.to contain_exec('disable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk disable boot-start -user root --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_exec('license_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk ftr --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_service('SplunkForwarder').with(restart: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk restart'", start: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk start'", stop: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk stop'", status: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk status'") }
end
context 'with $facts[service_provider] == systemd and $splunk::params::version < 7.2.2' do
let(:facts) do
facts.merge(service_provider: 'systemd')
end
let(:pre_condition) do
"class { 'splunk::params': version => '6.0.0', boot_start => false }"
end
it_behaves_like 'splunk forwarder'
it { is_expected.to contain_class('splunk::forwarder::service::nix') }
it { is_expected.to contain_class('splunk::forwarder').with(service_name: 'splunk') }
it { is_expected.not_to contain_exec('stop_splunkforwarder') }
it { is_expected.not_to contain_exec('enable_splunkforwarder') }
it { is_expected.to contain_exec('disable_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk disable boot-start -user root --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_exec('license_splunkforwarder').with(command: '/opt/splunkforwarder/bin/splunk ftr --accept-license --answer-yes --no-prompt') }
it { is_expected.to contain_service('splunk').with(restart: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk restart'", start: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk start'", stop: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk stop'", status: "/usr/sbin/runuser -l root -c '/opt/splunkforwarder/bin/splunk status'") }
end
end
end
context 'when forwarder not already installed' do
let(:facts) do
facts.merge(splunkforwarder_version: nil, service_provider: facts[:kernel] == 'FreeBSD' ? 'freebsd' : 'systemd')
end
let(:pre_condition) do
"class { 'splunk::params': version => '7.2.2' }"
end
let(:accept_tos_command) do
'/opt/splunkforwarder/bin/splunk stop && /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes && /opt/splunkforwarder/bin/splunk stop'
end
let(:service_name) do
facts[:kernel] == 'FreeBSD' ? 'splunk' : 'SplunkForwarder'
end
it_behaves_like 'splunk forwarder'
it do
is_expected.to contain_exec('splunk-forwarder-accept-tos').with(
command: accept_tos_command,
user: 'root',
before: "Service[#{service_name}]",
subscribe: nil,
require: 'Exec[enable_splunkforwarder]',
refreshonly: 'true'
)
end
end
context 'when forwarder already installed' do
let(:facts) do
facts.merge(splunkforwarder_version: '7.3.3', service_provider: facts[:kernel] == 'FreeBSD' ? 'freebsd' : 'systemd')
end
let(:pre_condition) do
"class { 'splunk::params': version => '7.2.2' }"
end
let(:accept_tos_command) do
'/opt/splunkforwarder/bin/splunk stop && /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes && /opt/splunkforwarder/bin/splunk stop'
end
let(:service_name) do
facts[:kernel] == 'FreeBSD' ? 'splunk' : 'SplunkForwarder'
end
it_behaves_like 'splunk forwarder'
it do
is_expected.to contain_exec('splunk-forwarder-accept-tos').with(
command: accept_tos_command,
user: 'root',
before: "Service[#{service_name}]",
subscribe: 'Package[splunkforwarder]',
require: 'Exec[enable_splunkforwarder]',
refreshonly: 'true'
)
end
end
end
end
end
end
end
|
{
"content_hash": "52b4a9e83d3be4d0d650e876cfcc067b",
"timestamp": "",
"source": "github",
"line_count": 289,
"max_line_length": 397,
"avg_line_length": 60.71626297577855,
"alnum_prop": 0.589730438251553,
"repo_name": "dhoppe/puppet-splunk",
"id": "4c24af28acb6f9a2515bad000a3c2f1606c032b2",
"size": "17547",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/classes/forwarder_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "480"
},
{
"name": "Pascal",
"bytes": "183"
},
{
"name": "Puppet",
"bytes": "78596"
},
{
"name": "Ruby",
"bytes": "80788"
}
],
"symlink_target": ""
}
|
package br.com.ppm.test.helper;
import org.mockito.stubbing.Answer;
/**
* The Stubbing Interface
*
* @author pedrotoliveira
*/
public interface Stubbing<ReturnType> {
<ReturnType> Stubbing<ReturnType> when(ReturnType value);
<D> GivenDataAndStubbing<D, ReturnType> then();
Stubbing<ReturnType> thenReturn(ReturnType value);
@SuppressWarnings("unchecked")
Stubbing<ReturnType> thenReturn(ReturnType value, ReturnType... values);
Stubbing<ReturnType> thenThrow(Throwable... throwables);
@SuppressWarnings("unchecked")
Stubbing<ReturnType> thenThrow(Class<? extends Throwable>... throwableClasses);
Stubbing<ReturnType> thenAnswer(Answer<?> answer);
Stubbing<ReturnType> then(Answer<?> answer);
<M> M getMock();
}
|
{
"content_hash": "98803f6b5e5edd82ab312d93c16414b8",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 83,
"avg_line_length": 24.838709677419356,
"alnum_prop": 0.7220779220779221,
"repo_name": "pedrotoliveira/ppm-test-helper",
"id": "c0a355f639ab395e18f50ae04cb071da691462a1",
"size": "770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/br/com/ppm/test/helper/Stubbing.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "119175"
},
{
"name": "Shell",
"bytes": "193"
}
],
"symlink_target": ""
}
|
/*
* @author Gabriel Oexle
* 2015.
*/
package peanutencryption.peanutencryption;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class Initialization extends AppCompatActivity {
public String LOG_str = "peanutencryption";
private String MY_PREF;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initialization);
MY_PREF = getString(R.string.sharedPref);
}
@Override
public void onBackPressed() {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_initialization, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void clickButtonConfirm(View v)
{
TextInputLayout inputLayoutPasswordFirst = (TextInputLayout) findViewById(R.id.textInputLayout_Password_First);
TextInputLayout inputLayoutPasswordSecond = (TextInputLayout) findViewById(R.id.textInputLayout_Password_Second);
String firstPassword = inputLayoutPasswordFirst.getEditText().getText().toString();
String secondPassword = inputLayoutPasswordSecond.getEditText().getText().toString();
if(firstPassword.isEmpty())
{
inputLayoutPasswordFirst.setError(getString(R.string.Init_App_Empty_password));
inputLayoutPasswordSecond.setError(" ");
}
else {
if (firstPassword.contentEquals(secondPassword)) {
Button btn = (Button) findViewById(R.id.ConfirmBtn);
btn.setEnabled(false);
SharedPreferences settings = getSharedPreferences(MY_PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isInitialized", true);
editor.commit();
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("password", firstPassword);
setResult(RESULT_OK, broadcastIntent);
finish();
} else {
Log.e(LOG_str, "Change Psw: new Passwords do not match");
inputLayoutPasswordFirst.getEditText().setText("");
inputLayoutPasswordSecond.getEditText().setText("");
inputLayoutPasswordFirst.setError(getString(R.string.Init_App_Password_do_not_match));
inputLayoutPasswordSecond.setError(" ");
}
}
}
}
|
{
"content_hash": "750e1611866e84441c6eba56200ffbda",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 121,
"avg_line_length": 32.816326530612244,
"alnum_prop": 0.6672885572139303,
"repo_name": "goexle/peanutEncryption",
"id": "0497caaafbbe734607aac1c96ef9db56e97e1df0",
"size": "3216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/peanutencryption/peanutencryption/Initialization.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "44263"
}
],
"symlink_target": ""
}
|
User::User() : health(3) {
}
User::~User() {
}
void User::updateTexture(bool isRight) {
if (isRight) {
sprite.setTexture("sculptor_right.png");
}
else {
sprite.setTexture("sculptor_left.png");
}
}
void User::init() {
TextureManagerSingleton &manager = TextureManagerSingleton::Instance();
sprite.setTexture("sculptor_right.png");
sprite.setSize((float)manager.getHeight()*150/1200, (float)manager.getWidth()*200/675);
sprite.setPosition((float)manager.getHeight()*525/1200, (float)manager.getWidth()*400/600);
}
void User::update(float time) {
//TODO
}
void User::draw(sf::RenderTarget &target) {
sprite.draw(target);
}
void User::setPosition(float x, float y) {
sprite.setPosition(x, y);
}
sf::Vector2f User::getPosition() {
return sprite.getPosition();
}
void User::setSize(float x, float y) {
sprite.setSize(x, y);
}
sf::Vector2f User::getSize() {
return sprite.getSize();
}
void User::setSprite(std::string newSpritePath) {
sprite.setSprite(newSpritePath);
}
int User::getHealth() {
return health;
}
void User::setHealth(int a) {
health = a;
}
void User::incrHealth(int a) {
if (health != 0) {
int b = health + a;
if (b > 3) {
b = 3;
}
health = b;
}
}
void User::decrHealth(int a) {
int b = health - a;
if (b < 0) {
b = 0;
}
health = b;
}
|
{
"content_hash": "facda08aa56131d5228c838c45e97260",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 92,
"avg_line_length": 15.72289156626506,
"alnum_prop": 0.653639846743295,
"repo_name": "undebutant/serial-sculptor",
"id": "cc1c7e87f4afe7e01b2f2eff5967a6e6409e04ce",
"size": "1382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code-serial-sculptor/MaBibliotheque/User.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "77559"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tangent.Intermediate
{
public class TypeDeclaration : ReductionRule<PhrasePart, TangentType>
{
public TypeDeclaration(PhrasePart takes, TangentType returns) : this(new[] { takes }, returns) { }
public TypeDeclaration(Identifier takes, TangentType returns) : this(new PhrasePart(takes), returns) { }
public TypeDeclaration(IEnumerable<PhrasePart> takes, TangentType returns) : base(takes, returns) { }
public TypeDeclaration(IEnumerable<Identifier> takes, TangentType returns) : this(takes.Select(id => new PhrasePart(id)), returns) { }
public bool IsGeneric
{
get
{
return !Takes.All(pp => pp == null || pp.IsIdentifier);
}
}
public override string SeparatorToken
{
get { return ":>"; }
}
}
}
|
{
"content_hash": "7e8fb5d0312f9202840bf3057ea0cc8c",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 142,
"avg_line_length": 33.892857142857146,
"alnum_prop": 0.6322444678609063,
"repo_name": "Telastyn/Tangent",
"id": "3d339a543605b4dabcc9e4eea91a9a4dee54788b",
"size": "951",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tangent.Intermediate/TypeDeclaration.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "850175"
}
],
"symlink_target": ""
}
|
"use strict";
var util = require("util");
module.exports = ontransaction;
function ontransaction(transaction) {
var t = transaction;
if (t.type === "ORDER_FILL") {
util.log(t.time, t.id, t.type, t.instrument, t.accountBalance, t.pl);
}
}
|
{
"content_hash": "9e6a5dcf7af7de9e396e3dd9c9114a7d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 77,
"avg_line_length": 20.153846153846153,
"alnum_prop": 0.6297709923664122,
"repo_name": "albertosantini/argo-trading-plugin-random",
"id": "ca9549a17732850d692a30f6876b18bf96b0e6f9",
"size": "262",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/custom/ontransaction.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16983"
}
],
"symlink_target": ""
}
|
package org.apache.hadoop.mapred.join;
import java.io.DataOutput;
import java.io.DataInput;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
/**
* Writable type storing multiple {@link org.apache.hadoop.io.Writable}s.
*
* This is *not* a general-purpose tuple type. In almost all cases, users are
* encouraged to implement their own serializable types, which can perform
* better validation and provide more efficient encodings than this class is
* capable. TupleWritable relies on the join framework for type safety and
* assumes its instances will rarely be persisted, assumptions not only
* incompatible with, but contrary to the general case.
*
* @see org.apache.hadoop.io.Writable
*/
public class TupleWritable implements Writable, Iterable<Writable> {
private long written;
private Writable[] values;
/**
* Create an empty tuple with no allocated storage for writables.
*/
public TupleWritable() {
}
/**
* Initialize tuple with storage; unknown whether any of them contain
* "written" values.
*/
public TupleWritable(Writable[] vals) {
written = 0L;
values = vals;
}
/**
* Return true if tuple has an element at the position provided.
*/
public boolean has(int i) {
return 0 != ((1L << i) & written);
}
/**
* Get ith Writable from Tuple.
*/
public Writable get(int i) {
return values[i];
}
/**
* The number of children in this Tuple.
*/
public int size() {
return values.length;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object other) {
if (other instanceof TupleWritable) {
TupleWritable that = (TupleWritable) other;
if (this.size() != that.size() || this.written != that.written) {
return false;
}
for (int i = 0; i < values.length; ++i) {
if (!has(i))
continue;
if (!values[i].equals(that.get(i))) {
return false;
}
}
return true;
}
return false;
}
public int hashCode() {
assert false : "hashCode not designed";
return (int) written;
}
/**
* Return an iterator over the elements in this tuple. Note that this
* doesn't flatten the tuple; one may receive tuples from this iterator.
*/
public Iterator<Writable> iterator() {
final TupleWritable t = this;
return new Iterator<Writable>() {
long i = written;
long last = 0L;
public boolean hasNext() {
return 0L != i;
}
public Writable next() {
last = Long.lowestOneBit(i);
if (0 == last)
throw new NoSuchElementException();
i ^= last;
// numberOfTrailingZeros rtn 64 if lsb set
return t.get(Long.numberOfTrailingZeros(last) % 64);
}
public void remove() {
t.written ^= last;
if (t.has(Long.numberOfTrailingZeros(last))) {
throw new IllegalStateException(
"Attempt to remove non-existent val");
}
}
};
}
/**
* Convert Tuple to String as in the following.
* <tt>[<child1>,<child2>,...,<childn>]</tt>
*/
public String toString() {
StringBuffer buf = new StringBuffer("[");
for (int i = 0; i < values.length; ++i) {
buf.append(has(i) ? values[i].toString() : "");
buf.append(",");
}
if (values.length != 0)
buf.setCharAt(buf.length() - 1, ']');
else
buf.append(']');
return buf.toString();
}
// Writable
/**
* Writes each Writable to <code>out</code>. TupleWritable format: {@code
* <count><type1><type2>...<typen><obj1><obj2>...<objn> * }
*/
public void write(DataOutput out) throws IOException {
WritableUtils.writeVInt(out, values.length);
WritableUtils.writeVLong(out, written);
for (int i = 0; i < values.length; ++i) {
Text.writeString(out, values[i].getClass().getName());
}
for (int i = 0; i < values.length; ++i) {
if (has(i)) {
values[i].write(out);
}
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
// No static typeinfo on Tuples
public void readFields(DataInput in) throws IOException {
int card = WritableUtils.readVInt(in);
values = new Writable[card];
written = WritableUtils.readVLong(in);
Class<? extends Writable>[] cls = new Class[card];
try {
for (int i = 0; i < card; ++i) {
cls[i] = Class.forName(Text.readString(in)).asSubclass(
Writable.class);
}
for (int i = 0; i < card; ++i) {
values[i] = cls[i].newInstance();
if (has(i)) {
values[i].readFields(in);
}
}
} catch (ClassNotFoundException e) {
throw (IOException) new IOException("Failed tuple init")
.initCause(e);
} catch (IllegalAccessException e) {
throw (IOException) new IOException("Failed tuple init")
.initCause(e);
} catch (InstantiationException e) {
throw (IOException) new IOException("Failed tuple init")
.initCause(e);
}
}
/**
* Record that the tuple contains an element at the position provided.
*/
void setWritten(int i) {
written |= 1L << i;
}
/**
* Record that the tuple does not contain an element at the position
* provided.
*/
void clearWritten(int i) {
written &= -1 ^ (1L << i);
}
/**
* Clear any record of which writables have been written to, without
* releasing storage.
*/
void clearWritten() {
written = 0L;
}
}
|
{
"content_hash": "1bebf93317b080a1c2006573fa8e070c",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 77,
"avg_line_length": 24.15068493150685,
"alnum_prop": 0.6483267158252978,
"repo_name": "shot/hadoop-source-reading",
"id": "4ac240dd60ccc5088a7781b72c931f947677c82f",
"size": "6095",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mapred/org/apache/hadoop/mapred/join/TupleWritable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Spot.Ebnf
{
/// <summary>
/// Defines a list of rules that should be called by the
/// <see cref="SyntaxValidator"/> when validating a syntax.
/// Any rule that is not defined in this list is not called.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = Justifications.MissingCollectionSuffix)]
public sealed class IncludedRules : IEnumerable<string>
{
private List<string> includedRules;
/// <summary>
/// Initializes a new instance of the <see cref="IncludedRules"/> class.
/// </summary>
/// <param name="rules">The rules that is to be included.</param>
/// <exception cref="ArgumentException">
/// <paramref name="rules"/> is null.
/// </exception>
public IncludedRules(IEnumerable<string> rules)
{
if (rules == null)
throw new ArgumentNullException(nameof(rules));
includedRules = new List<string>(rules);
}
/// <summary>
/// Initializes a new instance of the <see cref="IncludedRules"/> class.
/// </summary>
/// <param name="rules">The rules that is to be included.</param>
/// <exception cref="ArgumentException">
/// <paramref name="rules"/> is null.
/// </exception>
public IncludedRules(params string[] rules)
{
if (rules == null)
throw new ArgumentNullException(nameof(rules));
includedRules = new List<string>(rules);
}
/// <summary>
/// Returns an enumerator that iterates through the included rules.
/// </summary>
/// <returns>An enumerator that iterates through the included rules.</returns>
public IEnumerator<string> GetEnumerator()
{
return includedRules.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the included rules.
/// </summary>
/// <returns>An enumerator that iterates through the included rules.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return includedRules.GetEnumerator();
}
}
}
|
{
"content_hash": "35cf0931de037d7fe0f22f0006d9dea9",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 142,
"avg_line_length": 37.07575757575758,
"alnum_prop": 0.5864323661626482,
"repo_name": "pawwkm/Spot",
"id": "491242821818fc11431ddc4f0da6511242e4345d",
"size": "2449",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "Spot.Ebnf/IncludedRules.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "411846"
},
{
"name": "Smalltalk",
"bytes": "1494"
},
{
"name": "TeX",
"bytes": "14000"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
{
"content_hash": "ed8f77219dceac72233344d8e151e9b9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "9b1dfbbe5820beb9c87d17d7a12138bcc190ffd5",
"size": "218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Exhalimolobos/Exhalimolobos hispidulus/Sisymbrium hispidulum herrerae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
package info.voxtechnica.appraisers.db;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricSet;
import com.datastax.driver.core.Cluster;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import static com.codahale.metrics.MetricRegistry.name;
/**
* Cassandra Client Metrics, available on the admin port (e.g. http://localhost:8081/metrics)
*/
public class CassandraMetricSet implements MetricSet {
private Map<String, Metric> metrics;
public CassandraMetricSet(Cluster cluster) {
final String clusterName = cluster.getClusterName();
Map<String, Metric> driverMetrics = cluster.getMetrics().getRegistry().getMetrics();
ImmutableMap.Builder<String, Metric> builder = ImmutableMap.builder();
for (Map.Entry<String, Metric> metricEntry : driverMetrics.entrySet()) {
builder.put(name(Cluster.class, clusterName, metricEntry.getKey()), metricEntry.getValue());
}
metrics = builder.build();
}
@Override
public Map<String, Metric> getMetrics() {
return metrics;
}
}
|
{
"content_hash": "154f797d3826d13fefba2ec442909a9e",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 104,
"avg_line_length": 34.21875,
"alnum_prop": 0.7187214611872146,
"repo_name": "voxtechnica/appraiser-service",
"id": "3aa88039c2ee88f63f347c7191f956f3bddede80",
"size": "1095",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/info/voxtechnica/appraisers/db/CassandraMetricSet.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "32811"
},
{
"name": "FreeMarker",
"bytes": "6409"
},
{
"name": "HTML",
"bytes": "178"
},
{
"name": "Java",
"bytes": "332028"
},
{
"name": "JavaScript",
"bytes": "259538"
},
{
"name": "Shell",
"bytes": "2348"
}
],
"symlink_target": ""
}
|
package org.openkilda.rulemanager.factory.generator.flow;
import org.openkilda.adapter.FlowSideAdapter;
import org.openkilda.model.FlowEndpoint;
import org.openkilda.model.Switch;
import org.openkilda.model.cookie.CookieBase.CookieType;
import org.openkilda.model.cookie.PortColourCookie;
import org.openkilda.rulemanager.Constants.Priority;
import org.openkilda.rulemanager.Field;
import org.openkilda.rulemanager.FlowSpeakerData;
import org.openkilda.rulemanager.FlowSpeakerData.FlowSpeakerDataBuilder;
import org.openkilda.rulemanager.Instructions;
import org.openkilda.rulemanager.OfMetadata;
import org.openkilda.rulemanager.OfTable;
import org.openkilda.rulemanager.OfVersion;
import org.openkilda.rulemanager.ProtoConstants.EthType;
import org.openkilda.rulemanager.SpeakerData;
import org.openkilda.rulemanager.factory.RuleGenerator;
import org.openkilda.rulemanager.match.FieldMatch;
import org.openkilda.rulemanager.utils.RoutingMetadata;
import com.google.common.collect.Sets;
import lombok.Builder.Default;
import lombok.experimental.SuperBuilder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@SuperBuilder
public class InputArpRuleGenerator implements RuleGenerator {
@Default
private final Set<FlowSideAdapter> overlappingIngressAdapters = new HashSet<>();
private FlowEndpoint ingressEndpoint;
private boolean multiTable;
@Override
public List<SpeakerData> generateCommands(Switch sw) {
List<SpeakerData> result = new ArrayList<>();
if (multiTable && ingressEndpoint.isTrackArpConnectedDevices()
&& overlappingIngressAdapters.stream().noneMatch(FlowSideAdapter::isDetectConnectedDevicesArp)) {
result.add(buildArpInputCustomerFlowCommand(sw, ingressEndpoint));
}
return result;
}
private SpeakerData buildArpInputCustomerFlowCommand(Switch sw, FlowEndpoint endpoint) {
RoutingMetadata metadata = RoutingMetadata.builder().arpFlag(true).build(sw.getFeatures());
FlowSpeakerDataBuilder<?, ?> builder = FlowSpeakerData.builder()
.switchId(endpoint.getSwitchId())
.ofVersion(OfVersion.of(sw.getOfVersion()))
.cookie(new PortColourCookie(CookieType.ARP_INPUT_CUSTOMER_TYPE, endpoint.getPortNumber()))
.table(OfTable.INPUT)
.priority(Priority.ARP_INPUT_CUSTOMER_PRIORITY)
.match(Sets.newHashSet(
FieldMatch.builder().field(Field.IN_PORT).value(endpoint.getPortNumber()).build(),
FieldMatch.builder().field(Field.ETH_TYPE).value(EthType.ARP).build()))
.instructions(Instructions.builder()
.goToTable(OfTable.PRE_INGRESS)
.writeMetadata(new OfMetadata(metadata.getValue(), metadata.getMask()))
.build());
//todo add RESET_COUNTERS flag
return builder.build();
}
}
|
{
"content_hash": "837c04e6c2855ad0f6a409683cc21c9a",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 113,
"avg_line_length": 42.19718309859155,
"alnum_prop": 0.7283044058744993,
"repo_name": "telstra/open-kilda",
"id": "6b12a53a6eb82e67ef4101c052565698f7650dc0",
"size": "3613",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src-java/rule-manager/rule-manager-implementation/src/main/java/org/openkilda/rulemanager/factory/generator/flow/InputArpRuleGenerator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "89798"
},
{
"name": "CMake",
"bytes": "4314"
},
{
"name": "CSS",
"bytes": "233390"
},
{
"name": "Dockerfile",
"bytes": "30541"
},
{
"name": "Groovy",
"bytes": "2234079"
},
{
"name": "HTML",
"bytes": "362166"
},
{
"name": "Java",
"bytes": "14631453"
},
{
"name": "JavaScript",
"bytes": "369015"
},
{
"name": "Jinja",
"bytes": "937"
},
{
"name": "Makefile",
"bytes": "20500"
},
{
"name": "Python",
"bytes": "367364"
},
{
"name": "Shell",
"bytes": "62664"
},
{
"name": "TypeScript",
"bytes": "867537"
}
],
"symlink_target": ""
}
|
package voltdb
import (
"bytes"
"testing"
"time"
)
func TestWriteByte(t *testing.T) {
var b bytes.Buffer
writeByte(&b, 0x10)
r, err := b.ReadByte()
if err != nil {
t.Errorf("writeByte produced error: %v", err)
}
if r != 0x10 {
t.Errorf("writeByte has %v wants %v", r, 0x10)
}
}
func TestRoundTripByte(t *testing.T) {
testVals := [...]int8{-128, -10, 0, 127}
for _, val := range testVals {
var b bytes.Buffer
writeByte(&b, val)
r, _ := readByte(&b)
if val != r {
t.Errorf("Expected %v have %v", val, r)
}
}
}
func TestWriteShort(t *testing.T) {
var b bytes.Buffer
writeShort(&b, 0x4BCD)
b1, err := b.ReadByte()
if err != nil {
t.Errorf("writeShort produced error on first byte: %v", err)
}
b2, err := b.ReadByte()
if err != nil {
t.Errorf("writeShort produced error on second byte: %v", err)
}
if b1 != 0x4B && b2 != 0xCD {
t.Errorf("writeShort has %v,%v wants %v,%v", b1, b2, 0xCD, 0x4B)
}
}
// only verifies non-error, correct number of bytes written
func TestWriteInt(t *testing.T) {
var b bytes.Buffer
testVals := [...]int32{-100, -1, 0, 1, 100}
for _, v := range testVals {
b.Reset()
err := writeInt(&b, v)
if err != nil {
t.Errorf("writeInt produced error %v for %v", err, v)
}
length := b.Len()
if length != 4 {
t.Errorf("writeInt wrote %v bytes expected 4 bytes", length)
}
}
}
func TestRoundTripInt(t *testing.T) {
testVals := [...]int32{0xF00000, -10, 0, 0xEFFFFF}
for _, val := range testVals {
var b bytes.Buffer
writeInt(&b, val)
r, _ := readInt(&b)
if val != r {
t.Errorf("Expected %v have %v", val, r)
}
}
}
// only verifies non-error, correct number of bytes written
func TestWriteFloat(t *testing.T) {
var b bytes.Buffer
testVals := [...]float64{-100.1, -1.01, 0.0, 1.01, 100.1}
for _, v := range testVals {
b.Reset()
err := writeFloat(&b, v)
if err != nil {
t.Errorf("writeFloat produced error %v for %v", err, v)
}
length := b.Len()
if length != 8 {
t.Errorf("writeFloat wrote %v bytes expected 8 bytes", length)
}
}
}
func TestRoundTripFloat(t *testing.T) {
testVals := [...]float64{-100, -1, 0, 1, 100, 60.1798012160534}
for _, val := range testVals {
var b bytes.Buffer
writeFloat(&b, val)
r, _ := readFloat(&b)
if val != r {
t.Errorf("Expected %v have %v", val, r)
}
}
}
// only tests a single pure-ascii string
func TestWriteString(t *testing.T) {
var b bytes.Buffer
expected := [...]byte{0x00, 0x00, 0x00, 0x06, 'a', 'b', 'c', 'd', 'e', 'f'}
err := writeString(&b, "abcdef")
if err != nil {
t.Errorf("writeString produced error %v", err)
}
if b.Len() != 10 {
t.Errorf("writeString wrote %v but expected to write 10", b.Len())
}
for idx, val := range expected {
actual, _ := b.ReadByte()
if val != actual {
t.Errorf("writeString at index %v has %v wants %v", idx, actual, val)
}
}
}
func TestRoundTripString(t *testing.T) {
val := "⋒♈ℱ8 ♈ᗴᔕ♈ ᔕ♈ᖇᓰﬡᘐ"
var b bytes.Buffer
writeString(&b, val)
result, _ := readString(&b)
if val != result {
t.Errorf("expected %v received %v", val, result)
}
}
func TestRoundTripNullTimestamp(t *testing.T) {
var b bytes.Buffer
writeTimestamp(&b, time.Time{})
result, _ := readTimestamp(&b)
if !result.IsZero() {
t.Error("timestamp round trip failed. Want zero-value have non-zero")
}
}
func TestRoundTripNegativeTimestamp(t *testing.T) {
ts := time.Unix(-10000, 0)
var b bytes.Buffer
writeTimestamp(&b, ts)
result, _ := readTimestamp(&b)
if result != ts {
t.Errorf("timestamp round trip failed, expected %s got %s", ts.String(), result.String())
}
}
func TestReflection(t *testing.T) {
var b bytes.Buffer
var expInt8 int8 = 5
marshalParam(&b, expInt8)
rVtByte, _ := readByte(&b) // volttype
if rVtByte != vt_BOOL {
t.Errorf("reflect failed to write volttype byte")
}
result, _ := readByte(&b)
if result != expInt8 {
t.Errorf("int8 reflection failed. Want %d have %d", expInt8, result)
}
b.Reset()
var expString string = "abcde"
marshalParam(&b, expString)
rVtString, _ := readByte(&b) // volttype
if rVtString != vt_STRING {
t.Errorf("reflect failed to write volttype string")
}
rString, _ := readString(&b)
if rString != expString {
t.Errorf("string reflection failed. Want %s have %s", expString, rString)
}
b.Reset()
var expTimestamp time.Time = time.Now().Round(time.Microsecond)
marshalParam(&b, expTimestamp)
rVtTimestamp, _ := readByte(&b) // volttype
if rVtTimestamp != vt_TIMESTAMP {
t.Errorf("reflect failed to write volttype timestamp")
}
rTimestamp, _ := readTimestamp(&b)
if rTimestamp != expTimestamp {
t.Errorf("timestamp reflection failed. Want %v have %v", expTimestamp, rTimestamp)
}
}
|
{
"content_hash": "7dd67d2874834fbbad6389d5e68a30de",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 91,
"avg_line_length": 24.390625,
"alnum_prop": 0.6337817638266069,
"repo_name": "rbetts/voltdbgo",
"id": "a0e0773370f34f98934daff678bd9e3c95659f27",
"size": "4709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "voltdb/fastserializer_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "34155"
}
],
"symlink_target": ""
}
|
/*
* Created by Stefan Sprenger
*/
package com.sprenger.software.movie.app;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.ShareActionProvider;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.sprenger.software.movie.app.configuration.ReviewExpandableAdapter;
import com.sprenger.software.movie.app.configuration.ReviewSpec;
import com.sprenger.software.movie.app.configuration.TrailerGridAdapter;
import com.sprenger.software.movie.app.database.MovieContract;
import com.sprenger.software.movie.app.download.FetchReviewDataTask;
import com.sprenger.software.movie.app.download.FetchTrailerDataTask;
import com.sprenger.software.movie.app.utilities.Utility;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MovieDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int DETAIL_LOADER = 111;
static final String DETAIL_URI = "DETAIL_URI";
private Uri mUri;
private ImageView mMoviePosterView;
private TextView mMovieSynopsisView;
private TextView mMovieTitleView;
private TextView mMovieReleaseDateView;
private RecyclerView movieRecyclerView;
private TextView mMovieRatingView;
private RecyclerView mMovieReviewRecycler;
private ImageButton mMovieFavoriteButton;
private TextView mMovieReviewHeadline;
private TextView mMovieTrailerHeadline;
private ShareActionProvider mShareActionProvider;
private String mFirstTrailerYTID;
public MovieDetailFragment() {
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.movie_detail_fragment_menu, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
if (mFirstTrailerYTID != null) {
mShareActionProvider.setShareIntent(createShareTrailerIntent());
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mUri = arguments.getParcelable(DETAIL_URI);
}
View rootView = inflater.inflate(R.layout.movie_detail_fragment, container, false);
mMoviePosterView = (ImageView) rootView.findViewById(R.id.image_view_detail);
mMovieSynopsisView = (TextView) rootView.findViewById(R.id.synopsis_text_detail);
mMovieTitleView = (TextView) rootView.findViewById(R.id.title_text_detail);
mMovieReleaseDateView = (TextView) rootView.findViewById(R.id.detail_release_date_textview);
mMovieFavoriteButton = (ImageButton) rootView.findViewById(R.id.detail_favorite_button);
movieRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_trailers);
mMovieRatingView = (TextView) rootView.findViewById(R.id.detail_rating_textview);
mMovieReviewRecycler = (RecyclerView) rootView.findViewById(R.id.recyclerview_reviews);
mMovieReviewHeadline = (TextView) rootView.findViewById(R.id.textview_review_headlines);
mMovieTrailerHeadline = (TextView) rootView.findViewById(R.id.textview_trailer_headlines);
//set to invisible if there is no content
setComponentsVisibility(View.INVISIBLE);
return rootView;
}
private void setComponentsVisibility(int visibilityStatus) {
mMoviePosterView.setVisibility(visibilityStatus);
mMovieSynopsisView.setVisibility(visibilityStatus);
mMovieTitleView.setVisibility(visibilityStatus);
mMovieReleaseDateView.setVisibility(visibilityStatus);
mMovieFavoriteButton.setVisibility(visibilityStatus);
movieRecyclerView.setVisibility(visibilityStatus);
mMovieRatingView.setVisibility(visibilityStatus);
mMovieReviewRecycler.setVisibility(visibilityStatus);
mMovieReviewHeadline.setVisibility(visibilityStatus);
mMovieTrailerHeadline.setVisibility(visibilityStatus);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (null != mUri) {
return new CursorLoader(
getActivity(),
mUri,
Utility.MOVIE_COLUMNS,
null,
null,
null
);
}
return null;
}
@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
if (data != null && data.moveToFirst()) {
// content fills the components now
setComponentsVisibility(View.VISIBLE);
final String movieId = data.getString(Utility.COL_MOVIE_ID);
final String movieTitle = data.getString(Utility.COL_MOVIE_TITLE);
final String moviePopularity = data.getString(Utility.COL_MOVIE_POPUlARITY);
final String moviePoster = data.getString(Utility.COL_MOVIE_POSTER_PATH);
final String movieSynopsis = data.getString(Utility.COL_MOVIE_SYNOPSIS);
final String movieReleaseDate = data.getString(Utility.COL_MOVIE_RELEASE_DATE);
final String movieRating = data.getString(Utility.COL_MOVIE_RATING);
final String mMovieDBID = data.getString(Utility.COL_MOVIE_MOVIEDBID);
Picasso
.with(getActivity())
.load(data.getString(Utility.COL_MOVIE_POSTER_PATH))
.into(mMoviePosterView);
mMovieTitleView.setText(movieTitle);
mMovieSynopsisView.setText(movieSynopsis);
mMovieSynopsisView.setMovementMethod(new ScrollingMovementMethod());
mMovieReleaseDateView.setText(String.format(getString(R.string.release_text), movieReleaseDate));
mMovieRatingView.setText(String.format(getString(R.string.rating_text),movieRating));
mMovieFavoriteButton.setSelected(data.getInt(Utility.COL_MOVIE_ISFAVORITE) == 1);
mMovieFavoriteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMovieFavoriteButton.setSelected(!mMovieFavoriteButton.isSelected());
Uri alterMovie = MovieContract.MovieEntry.buildMovieByMovieId(data.getString(Utility.COL_MOVIE_MOVIEDBID));
ContentValues alteredMovieValues = new ContentValues();
alteredMovieValues.put(MovieContract.MovieEntry.COLUMN_TITLE, movieTitle);
alteredMovieValues.put(MovieContract.MovieEntry.COLUMN_SYNOPSIS, movieSynopsis);
alteredMovieValues.put(MovieContract.MovieEntry.COLUMN_POSTER_PATH, moviePoster);
alteredMovieValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, movieReleaseDate);
alteredMovieValues.put(MovieContract.MovieEntry.COLUMN_RATING, movieRating);
alteredMovieValues.put(MovieContract.MovieEntry.COLUMN_POPULARITY, moviePopularity);
alteredMovieValues.put(MovieContract.MovieEntry.COLUMN_IS_FAVORITE, mMovieFavoriteButton.isSelected() ? 1 : 0);
getContext().getContentResolver().update(alterMovie, alteredMovieValues, MovieContract.MovieEntry._ID + "= ?", new String[]{movieId});
if (Utility.getOnlyFavoriteOption(getContext()) && !mMovieFavoriteButton.isSelected()) {
updateLoadedEntry();
}
}
});
if (Utility.isNetworkAvailable(getContext())) {
ArrayList<String> trailerList = new ArrayList<>();
FetchTrailerDataTask fetchTrailerDataTask = new FetchTrailerDataTask(getContext());
try {
trailerList = fetchTrailerDataTask.execute(mMovieDBID).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
ArrayList<String> trailerNameIncremental = new ArrayList<>();
TrailerGridAdapter trailerGridAdapter;
if (trailerList != null) {
for (int i = 0; i < trailerList.size(); i++) {
trailerNameIncremental.add("Trailer " + (i + 1));
}
trailerGridAdapter = new TrailerGridAdapter(getActivity(), trailerNameIncremental, trailerList);
} else {
trailerGridAdapter = new TrailerGridAdapter(getActivity(), trailerNameIncremental, new ArrayList<String>());
}
movieRecyclerView.setAdapter(trailerGridAdapter);
LinearLayoutManager horizontalManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
movieRecyclerView.setLayoutManager(horizontalManager);
movieRecyclerView.setHasFixedSize(true);
ArrayList<ReviewSpec> reviewSpecs = new ArrayList<>();
FetchReviewDataTask fetchReviewDataTask = new FetchReviewDataTask(getContext());
try {
reviewSpecs = fetchReviewDataTask.execute(mMovieDBID).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if(trailerList != null && trailerList.size()>0) {
mFirstTrailerYTID = trailerList.get(0);
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(createShareTrailerIntent());
}
}
ArrayList<ParentObject> parentObjects = new ArrayList<>();
for (ReviewSpec reviewSpec : reviewSpecs) {
ArrayList<Object> childList = new ArrayList<>();
childList.add(reviewSpec.getReview());
reviewSpec.setChildObjectList(childList);
parentObjects.add(reviewSpec);
}
ReviewExpandableAdapter reviewExpandableAdapter = new ReviewExpandableAdapter(getActivity(), parentObjects);
reviewExpandableAdapter.setCustomParentAnimationViewId(R.id.parent_list_item_expand_arrow);
reviewExpandableAdapter.setParentClickableViewAnimationDefaultDuration();
reviewExpandableAdapter.setParentAndIconExpandOnClick(true);
mMovieReviewRecycler.setAdapter(reviewExpandableAdapter);
LinearLayoutManager verticalManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
verticalManager.setAutoMeasureEnabled(true);
mMovieReviewRecycler.setLayoutManager(verticalManager);
} else {
Utility.showToast("To enable movie trailers/reviews check your network connection", getContext());
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
public void updateLoadedEntry() {
if (null != mUri) {
Cursor topEntry;
String selector = null;
String[] selectorValues = null;
if (Utility.getOnlyFavoriteOption(getContext())) {
selector = MovieContract.MovieEntry.COLUMN_IS_FAVORITE + " = ?";
selectorValues = new String[]{"1"};
}
topEntry = getContext().getContentResolver().query(
MovieContract.MovieEntry.CONTENT_URI,
null,
selector,
selectorValues,
Utility.getSortOrderSQL(Utility.getPreferedSortOrder(getContext())));
if (topEntry != null && topEntry.moveToFirst()) {
mUri = MovieContract.MovieEntry.buildMovieByMovieId(topEntry.getString(Utility.COL_MOVIE_MOVIEDBID));
topEntry.close();
}
getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
}
}
private Intent createShareTrailerIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}else{
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
}
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "https://www.youtube.com/watch?v=" + mFirstTrailerYTID);
return shareIntent;
}
}
|
{
"content_hash": "31df69dd65a3cced8891e5741cbba27e",
"timestamp": "",
"source": "github",
"line_count": 323,
"max_line_length": 154,
"avg_line_length": 42.94117647058823,
"alnum_prop": 0.6645998558038932,
"repo_name": "sprengerst/udacity_nanodegree_project_2",
"id": "c999de78e319f672234498dfcc5379d15d544f4b",
"size": "13870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/sprenger/software/movie/app/MovieDetailFragment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "63122"
}
],
"symlink_target": ""
}
|
const PANGO_SCALE = 1024.0
# Serialized glyph sizes for commont fonts.
const glyphsizes = open(fd -> JSON.parse(readstring(fd)),
joinpath(dirname(@__FILE__), "..", "data",
"glyphsize.json"))
# It's better to overestimate text extents than to underestimes, since the later
# leads to overlaping where the former just results in some extra space. So, we
# scale estimated text extends by this number. Width on the other hand tends be
# overestimated since it doesn't take kerning into account.
const text_extents_scale_x = 1.0
const text_extents_scale_y = 1.0
# Normalized Levenshtein distance between two strings.
function levenshtein(a::AbstractString, b::AbstractString)
a = replace(lowercase(a), r"\s+", "")
b = replace(lowercase(b), r"\s+", "")
n = length(a)
m = length(b)
D = zeros(UInt, n + 1, m + 1)
D[:,1] = 0:n
D[1,:] = 0:m
for i in 2:n, j in 2:m
if a[i - 1] == b[j - 1]
D[i, j] = D[i - 1, j - 1]
else
D[i, j] = 1 + min(D[i - 1, j - 1], D[i, j - 1], D[i - 1, j])
end
end
return D[n,m] / max(n, m)
end
# Find the nearst typeface from the glyph size table.
let
matched_font_cache = Dict{AbstractString, AbstractString}()
global match_font
function match_font(families::AbstractString)
if haskey(matched_font_cache, families)
return matched_font_cache[families]
end
smallest_dist = Inf
best_match = "Helvetica"
for family in [lowercase(strip(family, [' ', '"', '\''])) for family in split(families, ',')]
for available_family in keys(glyphsizes)
d = levenshtein(family, available_family)
if d < smallest_dist
smallest_dist = d
best_match = available_family
end
end
end
matched_font_cache[families] = best_match
return best_match
end
end
# Approximate width of a text in millimeters.
#
# Args:
# widths: A glyph width table from glyphsizes.
# text: Any string.
# size: Font size in points.
#
# Returns:
# Approximate text width in millimeters.
#
function text_width(widths::Dict, text::AbstractString, size::Float64)
stripped_text = replace(text, r"<[^>]*>", "")
width = 0
for c in stripped_text
width += get(widths, string(c), widths["w"])
end
width
end
function max_text_extents(font_family::AbstractString, size::Measure,
texts::AbstractString...)
if !isa(size, AbsoluteLength)
error("text_extents requries font size be in absolute units")
end
scale = size / 12pt
font_family = match_font(font_family)
glyphheight = glyphsizes[font_family]["height"]
widths = glyphsizes[font_family]["widths"]
fontsize = size/pt
chunkwidths = Float64[]
textheights = Float64[]
for text in texts
textheight = 0.0
for chunk in split(text, '\n')
chunkheight = glyphheight
if match(r"<su(p|b)>", chunk) != nothing
chunkheight *= 1.5
end
textheight += chunkheight
push!(chunkwidths, text_width(widths, chunk, fontsize))
end
push!(textheights, textheight)
end
width = maximum(chunkwidths)
height = maximum(textheights)
(text_extents_scale_x * scale * width * mm,
text_extents_scale_y * scale * height * mm)
end
function text_extents(font_family::AbstractString, size::Measure, texts::AbstractString...)
scale = size / 12pt
font_family = match_font(font_family)
glyphheight = glyphsizes[font_family]["height"]
glyphwidths = glyphsizes[font_family]["widths"]
fontsize = size/pt
extents = Array((@compat Tuple{Measure, Measure}), length(texts))
for (i, text) in enumerate(texts)
chunkwidths = Float64[]
textheight = 0.0
for chunk in split(text, "\n")
chunkheight = glyphheight
if match(r"<su(p|b)>", text) != nothing
chunkheight *= 1.5
end
textheight += chunkheight
push!(chunkwidths, text_width(glyphwidths, chunk, fontsize))
end
width = maximum(chunkwidths)
extents[i] = (text_extents_scale_x * scale * width * mm,
text_extents_scale_y * scale * textheight * mm)
end
return extents
end
# Amazingly crude fallback to parse pango markup into svg.
function pango_to_svg(text::AbstractString)
pat = r"<(/?)\s*([^>]*)\s*>"
input = convert(Array{UInt8}, text)
output = IOBuffer()
lastpos = 1
baseline_shift = 0.0
open_tag = false
for mat in eachmatch(pat, text)
write(output, input[lastpos:mat.offset-1])
closing_tag = mat.captures[1] == "/"
if open_tag && !closing_tag
write(output, "</tspan>")
end
if mat.captures[2] == "sup"
if mat.captures[1] == "/"
write(output, "</tspan>")
else
# write(output, "<tspan style=\"dominant-baseline:inherit\" baseline-shift=\"super\">")
write(output, "<tspan style=\"dominant-baseline:inherit\" dy=\"-0.6em\" font-size=\"83%\">")
baseline_shift = -0.6 * 0.83
end
elseif mat.captures[2] == "sub"
if mat.captures[1] == "/"
write(output, "</tspan>")
else
# write(output, "<tspan style=\"dominant-baseline:inherit\" baseline-shift=\"sub\">")
write(output, "<tspan style=\"dominant-baseline:inherit\" dy=\"0.6em\" font-size=\"83%\">")
baseline_shift = 0.6 * 0.83
end
elseif mat.captures[2] == "i"
if mat.captures[1] == "/"
write(output, "</tspan>")
else
write(output, "<tspan style=\"dominant-baseline:inherit\" font-style=\"italic\">")
end
elseif mat.captures[2] == "b"
if mat.captures[1] == "/"
write(output, "</tspan>")
else
write(output, "<tspan style=\"dominant-baseline:inherit\" font-weight=\"bold\">")
end
end
if closing_tag && baseline_shift != 0.0
@printf(output, "<tspan dy=\"%fem\">", -baseline_shift)
baseline_shift = 0.0
open_tag = true
end
lastpos = mat.offset + length(mat.match)
end
write(output, input[lastpos:end])
if open_tag
write(output, "</tspan>")
end
takebuf_string(output)
end
|
{
"content_hash": "adeca95e8fb2bf077e3b202f59cc9492",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 108,
"avg_line_length": 31.51658767772512,
"alnum_prop": 0.562406015037594,
"repo_name": "JuliaPackageMirrors/Compose.jl",
"id": "93056a7fe3581609ab8806c1092db2434954773e",
"size": "6781",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/fontfallback.jl",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2832"
},
{
"name": "Julia",
"bytes": "433320"
},
{
"name": "Makefile",
"bytes": "1021"
}
],
"symlink_target": ""
}
|
namespace AngleSharp.Html.InputTypes
{
using AngleSharp.Html.Dom;
using System;
using System.Text.RegularExpressions;
class EmailInputType : BaseInputType
{
#region Fields
static readonly Regex emailPattern = new Regex("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", RegexOptions.Compiled);
#endregion
#region ctor
public EmailInputType(IHtmlInputElement input, String name)
: base(input, name, validate: true)
{
}
#endregion
#region Methods
public override ValidationErrors Check(IValidityState current)
{
var value = Input.Value ?? String.Empty;
var result = GetErrorsFrom(current);
if (IsInvalidPattern(Input.Pattern, value))
{
result ^= ValidationErrors.PatternMismatch;
}
if (IsInvalidEmail(Input.IsMultiple, value) && !String.IsNullOrEmpty(value))
{
result ^= ValidationErrors.TypeMismatch | ValidationErrors.BadInput;
}
return result;
}
static Boolean IsInvalidEmail(Boolean multiple, String value)
{
if (multiple)
{
var mails = value.Split(',');
foreach (var mail in mails)
{
if (!emailPattern.IsMatch(mail.Trim()))
{
return true;
}
}
return false;
}
return !emailPattern.IsMatch(value.Trim());
}
#endregion
}
}
|
{
"content_hash": "8dd956ffb98d223b979a5672c767d0aa",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 215,
"avg_line_length": 26.37878787878788,
"alnum_prop": 0.504882251579552,
"repo_name": "AngleSharp/AngleSharp",
"id": "dcfc250b6e2356079c53efb87778d2bc4fba7578",
"size": "1741",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "src/AngleSharp/Html/InputTypes/EmailInputType.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "7758647"
},
{
"name": "HTML",
"bytes": "1294302"
},
{
"name": "JavaScript",
"bytes": "75888"
},
{
"name": "PowerShell",
"bytes": "2370"
},
{
"name": "Shell",
"bytes": "2670"
},
{
"name": "TypeScript",
"bytes": "237"
}
],
"symlink_target": ""
}
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Comp2502Component } from './comp-2502.component';
describe('Comp2502Component', () => {
let component: Comp2502Component;
let fixture: ComponentFixture<Comp2502Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Comp2502Component ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Comp2502Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
{
"content_hash": "1486714a8157168f82a3ed4c433adf6d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 73,
"avg_line_length": 23.88888888888889,
"alnum_prop": 0.6744186046511628,
"repo_name": "angular/angular-cli-stress-test",
"id": "aba7eed671383fd15831f41f55a71ad5f5e22e83",
"size": "847",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/components/comp-2502/comp-2502.component.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1040888"
},
{
"name": "HTML",
"bytes": "300322"
},
{
"name": "JavaScript",
"bytes": "2404"
},
{
"name": "TypeScript",
"bytes": "8535506"
}
],
"symlink_target": ""
}
|
title: Introduction
product: remmina-plugin-exec
depth: 1
---
# Description
**Remmina Plugin Exec** is a free software protocol plugin to execute external processes (commands or applications) from the Remmina window.
Some examples of external applications could be third party remote access applications not supported by any Remmina protocol, network calculators, network diagram draw applications and many others.

[muflone-install type="index" package="remmina-plugin-exec" name="Remmina Plugin Exec"][/muflone-install]
# Settings
The Remmina Plugin Exec plugin settings are documented in the [Settings page](../settings).
[muflone-license type="index" package="remmina-plugin-exec" name="Remmina Plugin Exec"][/muflone-license]
|
{
"content_hash": "62412a8d92e2489466ffa6e833ad53be",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 197,
"avg_line_length": 43.31578947368421,
"alnum_prop": 0.7934386391251519,
"repo_name": "muflone/grav-muflone",
"id": "7a2191e349abff9a172973942c0db5db852affcc",
"size": "827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "user/pages/11.remmina-plugin-exec/01.index/item.en.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3982"
},
{
"name": "CSS",
"bytes": "468085"
},
{
"name": "HTML",
"bytes": "257967"
},
{
"name": "JavaScript",
"bytes": "221067"
},
{
"name": "Logos",
"bytes": "816"
},
{
"name": "Nginx",
"bytes": "1443"
},
{
"name": "PHP",
"bytes": "1393025"
},
{
"name": "Shell",
"bytes": "643"
},
{
"name": "XSLT",
"bytes": "827"
}
],
"symlink_target": ""
}
|
package crypto
import (
obc "github.com/openblockchain/obc-peer/protos"
"bytes"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"reflect"
"testing"
"crypto/rand"
"github.com/op/go-logging"
"github.com/openblockchain/obc-peer/obc-ca/obcca"
"github.com/openblockchain/obc-peer/openchain/crypto/utils"
"github.com/openblockchain/obc-peer/openchain/util"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type createTxFunc func(t *testing.T) (*obc.Transaction, *obc.Transaction, error)
var (
validator Peer
peer Peer
deployer Client
invoker Client
server *grpc.Server
eca *obcca.ECA
tca *obcca.TCA
tlsca *obcca.TLSCA
deployTxCreators []createTxFunc
executeTxCreators []createTxFunc
queryTxCreators []createTxFunc
ksPwd = []byte("This is a very very very long pw")
)
func TestMain(m *testing.M) {
setup()
// Init PKI
initPKI()
go startPKI()
defer cleanup()
// Init clients
err := initClients()
if err != nil {
fmt.Printf("Failed initializing clients [%s]\n", err)
panic(fmt.Errorf("Failed initializing clients [%s].", err))
}
// Init peer
err = initPeers()
if err != nil {
fmt.Printf("Failed initializing peers [%s]\n", err)
panic(fmt.Errorf("Failed initializing peers [%s].", err))
}
// Init validators
err = initValidators()
if err != nil {
fmt.Printf("Failed initializing validators [%s]\n", err)
panic(fmt.Errorf("Failed initializing validators [%s].", err))
}
viper.Set("pki.validity-period.update", "false")
viper.Set("validator.validity-period.verification", "false")
if err != nil {
fmt.Printf("Failed initializing ledger [%s]\n", err.Error())
panic(fmt.Errorf("Failed initializing ledger [%s].", err.Error()))
}
ret := m.Run()
cleanup()
os.Exit(ret)
}
func TestParallelInitClose(t *testing.T) {
// TODO: complete this
conf := utils.NodeConfiguration{Type: "client", Name: "userthread"}
RegisterClient(conf.Name, nil, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())
done := make(chan bool)
n := 10
for i := 0; i < n; i++ {
go func() {
for i := 0; i < 5; i++ {
client, err := InitClient(conf.Name, nil)
if err != nil {
t.Log("Init failed")
}
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
for i := 0; i < 20; i++ {
uuid := util.GenerateUUID()
client.NewChaincodeExecute(cis, uuid)
}
err = CloseClient(client)
if err != nil {
t.Log("Close failed")
}
}
done <- true
}()
}
for i := 0; i < n; i++ {
log.Info("Waiting")
<-done
log.Info("+1")
}
log.Info("Test Finished!")
//
}
func TestRegistrationSameEnrollIDDifferentRole(t *testing.T) {
conf := utils.NodeConfiguration{Type: "client", Name: "TestRegistrationSameEnrollIDDifferentRole"}
if err := RegisterClient(conf.Name, nil, conf.GetEnrollmentID(), conf.GetEnrollmentPWD()); err != nil {
t.Fatalf("Failed client registration [%s]", err)
}
if err := RegisterValidator(conf.Name, nil, conf.GetEnrollmentID(), conf.GetEnrollmentPWD()); err == nil {
t.Fatalf("Reusing the same enrollment id must be forbidden", err)
}
if err := RegisterPeer(conf.Name, nil, conf.GetEnrollmentID(), conf.GetEnrollmentPWD()); err == nil {
t.Fatalf("Reusing the same enrollment id must be forbidden", err)
}
}
func TestInitialization(t *testing.T) {
// Init fake client
client, err := InitClient("", nil)
if err == nil || client != nil {
t.Fatal("Init should fail")
}
err = CloseClient(client)
if err == nil {
t.Fatal("Close should fail")
}
// Init fake peer
peer, err := InitPeer("", nil)
if err == nil || peer != nil {
t.Fatal("Init should fail")
}
err = ClosePeer(peer)
if err == nil {
t.Fatal("Close should fail")
}
// Init fake validator
validator, err := InitValidator("", nil)
if err == nil || validator != nil {
t.Fatal("Init should fail")
}
err = CloseValidator(validator)
if err == nil {
t.Fatal("Close should fail")
}
}
func TestClientDeployTransaction(t *testing.T) {
for i, createTx := range deployTxCreators {
t.Logf("TestClientDeployTransaction with [%d]\n", i)
_, tx, err := createTx(t)
if err != nil {
t.Fatalf("Failed creating deploy transaction [%s].", err)
}
if tx == nil {
t.Fatalf("Result must be different from nil")
}
// Check transaction. For test purposes only
err = deployer.(*clientImpl).checkTransaction(tx)
if err != nil {
t.Fatalf("Failed checking transaction [%s].", err)
}
}
}
func TestClientExecuteTransaction(t *testing.T) {
for i, createTx := range executeTxCreators {
t.Logf("TestClientExecuteTransaction with [%d]\n", i)
_, tx, err := createTx(t)
if err != nil {
t.Fatalf("Failed creating deploy transaction [%s].", err)
}
if tx == nil {
t.Fatalf("Result must be different from nil")
}
// Check transaction. For test purposes only
err = invoker.(*clientImpl).checkTransaction(tx)
if err != nil {
t.Fatalf("Failed checking transaction [%s].", err)
}
}
}
func TestClientQueryTransaction(t *testing.T) {
for i, createTx := range queryTxCreators {
t.Logf("TestClientQueryTransaction with [%d]\n", i)
_, tx, err := createTx(t)
if err != nil {
t.Fatalf("Failed creating deploy transaction [%s].", err)
}
if tx == nil {
t.Fatalf("Result must be different from nil")
}
// Check transaction. For test purposes only
err = invoker.(*clientImpl).checkTransaction(tx)
if err != nil {
t.Fatalf("Failed checking transaction [%s].", err)
}
}
}
func TestClientMultiExecuteTransaction(t *testing.T) {
for i := 0; i < 24; i++ {
_, tx, err := createConfidentialExecuteTransaction(t)
if err != nil {
t.Fatalf("Failed creating execute transaction [%s].", err)
}
if tx == nil {
t.Fatalf("Result must be different from nil")
}
// Check transaction. For test purposes only
err = invoker.(*clientImpl).checkTransaction(tx)
if err != nil {
t.Fatalf("Failed checking transaction [%s].", err)
}
}
}
func TestClientGetTCertHandlerNext(t *testing.T) {
handler, err := deployer.GetTCertificateHandlerNext()
if err != nil {
t.Fatalf("Failed getting handler: [%s]", err)
}
if handler == nil {
t.Fatalf("Handler should be different from nil")
}
certDER := handler.GetCertificate()
if certDER == nil {
t.Fatalf("Cert should be different from nil")
}
if len(certDER) == 0 {
t.Fatalf("Cert should have length > 0")
}
}
func TestClientGetTCertHandlerFromDER(t *testing.T) {
handler, err := deployer.GetTCertificateHandlerNext()
if err != nil {
t.Fatalf("Failed getting handler: [%s]", err)
}
handler2, err := deployer.GetTCertificateHandlerFromDER(handler.GetCertificate())
if err != nil {
t.Fatalf("Failed getting tcert: [%s]", err)
}
if handler == nil {
t.Fatalf("Handler should be different from nil")
}
tCertDER := handler2.GetCertificate()
if tCertDER == nil {
t.Fatalf("TCert should be different from nil")
}
if len(tCertDER) == 0 {
t.Fatalf("TCert should have length > 0")
}
if !reflect.DeepEqual(handler.GetCertificate(), tCertDER) {
t.Fatalf("TCerts must be the same")
}
}
func TestClientTCertHandlerSign(t *testing.T) {
handlerDeployer, err := deployer.GetTCertificateHandlerNext()
if err != nil {
t.Fatalf("Failed getting handler: [%s]", err)
}
msg := []byte("Hello World!!!")
signature, err := handlerDeployer.Sign(msg)
if err != nil {
t.Fatalf("Failed getting tcert: [%s]", err)
}
if signature == nil || len(signature) == 0 {
t.Fatalf("Failed getting non-nil signature")
}
err = handlerDeployer.Verify(signature, msg)
if err != nil {
t.Fatalf("Failed verifying signature: [%s]", err)
}
// Check that invoker (another party) can verify the signature
handlerInvoker, err := invoker.GetTCertificateHandlerFromDER(handlerDeployer.GetCertificate())
if err != nil {
t.Fatalf("Failed getting tcert: [%s]", err)
}
err = handlerInvoker.Verify(signature, msg)
if err != nil {
t.Fatalf("Failed verifying signature: [%s]", err)
}
// Check that invoker cannot sign using a tcert obtained by the deployer
signature, err = handlerInvoker.Sign(msg)
if err == nil {
t.Fatalf("Bob should not be able to use Alice's tcert to sign")
}
if signature != nil {
t.Fatalf("Signature should be nil")
}
}
func TestClientGetEnrollmentCertHandler(t *testing.T) {
handler, err := deployer.GetEnrollmentCertificateHandler()
if err != nil {
t.Fatalf("Failed getting handler: [%s]", err)
}
if handler == nil {
t.Fatalf("Handler should be different from nil")
}
certDER := handler.GetCertificate()
if certDER == nil {
t.Fatalf("Cert should be different from nil")
}
if len(certDER) == 0 {
t.Fatalf("Cert should have length > 0")
}
}
func TestClientGetEnrollmentCertHandlerSign(t *testing.T) {
handlerDeployer, err := deployer.GetEnrollmentCertificateHandler()
if err != nil {
t.Fatalf("Failed getting handler: [%s]", err)
}
msg := []byte("Hello World!!!")
signature, err := handlerDeployer.Sign(msg)
if err != nil {
t.Fatalf("Failed getting tcert: [%s]", err)
}
if signature == nil || len(signature) == 0 {
t.Fatalf("Failed getting non-nil signature")
}
err = handlerDeployer.Verify(signature, msg)
if err != nil {
t.Fatalf("Failed verifying signature: [%s]", err)
}
// Check that invoker (another party) can verify the signature
handlerInvoker, err := invoker.GetEnrollmentCertificateHandler()
if err != nil {
t.Fatalf("Failed getting tcert: [%s]", err)
}
err = handlerInvoker.Verify(signature, msg)
if err == nil {
t.Fatalf("Failed verifying signature: [%s]", err)
}
}
func TestPeerID(t *testing.T) {
// Verify that any id modification doesn't change
id := peer.GetID()
if id == nil {
t.Fatalf("Id is nil.")
}
if len(id) == 0 {
t.Fatalf("Id length is zero.")
}
id[0] = id[0] + 1
id2 := peer.GetID()
if id2[0] == id[0] {
t.Fatalf("Invariant not respected.")
}
}
func TestPeerDeployTransaction(t *testing.T) {
for i, createTx := range deployTxCreators {
t.Logf("TestPeerDeployTransaction with [%d]\n", i)
_, tx, err := createTx(t)
if err != nil {
t.Fatalf("TransactionPreValidation: failed creating transaction [%s].", err)
}
res, err := peer.TransactionPreValidation(tx)
if err != nil {
t.Fatalf("Error must be nil [%s].", err)
}
if res == nil {
t.Fatalf("Result must be diffrent from nil")
}
res, err = peer.TransactionPreExecution(tx)
if err != utils.ErrNotImplemented {
t.Fatalf("Error must be ErrNotImplemented [%s].", err)
}
if res != nil {
t.Fatalf("Result must nil")
}
}
}
func TestPeerExecuteTransaction(t *testing.T) {
for i, createTx := range executeTxCreators {
t.Logf("TestPeerExecuteTransaction with [%d]\n", i)
_, tx, err := createTx(t)
if err != nil {
t.Fatalf("TransactionPreValidation: failed creating transaction [%s].", err)
}
res, err := peer.TransactionPreValidation(tx)
if err != nil {
t.Fatalf("Error must be nil [%s].", err)
}
if res == nil {
t.Fatalf("Result must be diffrent from nil")
}
res, err = peer.TransactionPreExecution(tx)
if err != utils.ErrNotImplemented {
t.Fatalf("Error must be ErrNotImplemented [%s].", err)
}
if res != nil {
t.Fatalf("Result must nil")
}
}
}
func TestPeerQueryTransaction(t *testing.T) {
for i, createTx := range queryTxCreators {
t.Logf("TestPeerQueryTransaction with [%d]\n", i)
_, tx, err := createTx(t)
if err != nil {
t.Fatalf("Failed creating query transaction [%s].", err)
}
res, err := peer.TransactionPreValidation(tx)
if err != nil {
t.Fatalf("Error must be nil [%s].", err)
}
if res == nil {
t.Fatalf("Result must be diffrent from nil")
}
res, err = peer.TransactionPreExecution(tx)
if err != utils.ErrNotImplemented {
t.Fatalf("Error must be ErrNotImplemented [%s].", err)
}
if res != nil {
t.Fatalf("Result must nil")
}
}
}
func TestPeerStateEncryptor(t *testing.T) {
_, deployTx, err := createConfidentialDeployTransaction(t)
if err != nil {
t.Fatalf("Failed creating deploy transaction [%s].", err)
}
_, invokeTxOne, err := createConfidentialExecuteTransaction(t)
if err != nil {
t.Fatalf("Failed creating invoke transaction [%s].", err)
}
res, err := peer.GetStateEncryptor(deployTx, invokeTxOne)
if err != utils.ErrNotImplemented {
t.Fatalf("Error must be ErrNotImplemented [%s].", err)
}
if res != nil {
t.Fatalf("Result must be nil")
}
}
func TestPeerSignVerify(t *testing.T) {
msg := []byte("Hello World!!!")
signature, err := peer.Sign(msg)
if err != utils.ErrNotImplemented {
t.Fatalf("Error must be ErrNotImplemented [%s].", err)
}
if signature != nil {
t.Fatalf("Result must be nil")
}
err = peer.Verify(validator.GetID(), signature, msg)
if err != utils.ErrNotImplemented {
t.Fatalf("Error must be ErrNotImplemented [%s].", err)
}
}
func TestValidatorID(t *testing.T) {
// Verify that any id modification doesn't change
id := validator.GetID()
if id == nil {
t.Fatalf("Id is nil.")
}
if len(id) == 0 {
t.Fatalf("Id length is zero.")
}
id[0] = id[0] + 1
id2 := validator.GetID()
if id2[0] == id[0] {
t.Fatalf("Invariant not respected.")
}
}
func TestValidatorDeployTransaction(t *testing.T) {
for i, createTx := range deployTxCreators {
t.Logf("TestValidatorDeployTransaction with [%d]\n", i)
otx, tx, err := createTx(t)
if err != nil {
t.Fatalf("Failed creating deploy transaction [%s].", err)
}
res, err := validator.TransactionPreValidation(tx)
if err != nil {
t.Fatalf("Error must be nil [%s].", err)
}
if res == nil {
t.Fatalf("Result must be diffrent from nil")
}
res, err = validator.TransactionPreExecution(tx)
if err != nil {
t.Fatalf("Error must be nil [%s].", err)
}
if res == nil {
t.Fatalf("Result must be diffrent from nil")
}
if tx.ConfidentialityLevel == obc.ConfidentialityLevel_CONFIDENTIAL {
if reflect.DeepEqual(res, tx) {
t.Fatalf("Src and Dest Transaction should be different after PreExecution")
}
if err := isEqual(otx, res); err != nil {
t.Fatalf("Decrypted transaction differs from the original: [%s]", err)
}
}
}
}
func TestValidatorExecuteTransaction(t *testing.T) {
for i, createTx := range executeTxCreators {
t.Logf("TestValidatorExecuteTransaction with [%d]\n", i)
otx, tx, err := createTx(t)
if err != nil {
t.Fatalf("Failed creating execute transaction [%s].", err)
}
res, err := validator.TransactionPreValidation(tx)
if err != nil {
t.Fatalf("Error must be nil [%s].", err)
}
if res == nil {
t.Fatalf("Result must be diffrent from nil")
}
res, err = validator.TransactionPreExecution(tx)
if err != nil {
t.Fatalf("Error must be nil [%s].", err)
}
if res == nil {
t.Fatalf("Result must be diffrent from nil")
}
if tx.ConfidentialityLevel == obc.ConfidentialityLevel_CONFIDENTIAL {
if reflect.DeepEqual(res, tx) {
t.Fatalf("Src and Dest Transaction should be different after PreExecution")
}
if err := isEqual(otx, res); err != nil {
t.Fatalf("Decrypted transaction differs from the original: [%s]", err)
}
}
}
}
func TestValidatorQueryTransaction(t *testing.T) {
for i, createTx := range queryTxCreators {
t.Logf("TestValidatorConfidentialQueryTransaction with [%d]\n", i)
_, deployTx, err := deployTxCreators[i](t)
if err != nil {
t.Fatalf("Failed creating deploy transaction [%s].", err)
}
_, invokeTxOne, err := executeTxCreators[i](t)
if err != nil {
t.Fatalf("Failed creating invoke transaction [%s].", err)
}
_, invokeTxTwo, err := executeTxCreators[i](t)
if err != nil {
t.Fatalf("Failed creating invoke transaction [%s].", err)
}
otx, queryTx, err := createTx(t)
if err != nil {
t.Fatalf("Failed creating query transaction [%s].", err)
}
if queryTx.ConfidentialityLevel == obc.ConfidentialityLevel_CONFIDENTIAL {
// Transactions must be PreExecuted by the validators before getting the StateEncryptor
if _, err := validator.TransactionPreValidation(deployTx); err != nil {
t.Fatalf("Failed pre-validating deploty transaction [%s].", err)
}
if deployTx, err = validator.TransactionPreExecution(deployTx); err != nil {
t.Fatalf("Failed pre-executing deploty transaction [%s].", err)
}
if _, err := validator.TransactionPreValidation(invokeTxOne); err != nil {
t.Fatalf("Failed pre-validating exec1 transaction [%s].", err)
}
if invokeTxOne, err = validator.TransactionPreExecution(invokeTxOne); err != nil {
t.Fatalf("Failed pre-executing exec1 transaction [%s].", err)
}
if _, err := validator.TransactionPreValidation(invokeTxTwo); err != nil {
t.Fatalf("Failed pre-validating exec2 transaction [%s].", err)
}
if invokeTxTwo, err = validator.TransactionPreExecution(invokeTxTwo); err != nil {
t.Fatalf("Failed pre-executing exec2 transaction [%s].", err)
}
if _, err := validator.TransactionPreValidation(queryTx); err != nil {
t.Fatalf("Failed pre-validating query transaction [%s].", err)
}
if queryTx, err = validator.TransactionPreExecution(queryTx); err != nil {
t.Fatalf("Failed pre-executing query transaction [%s].", err)
}
if err := isEqual(otx, queryTx); err != nil {
t.Fatalf("Decrypted transaction differs from the original: [%s]", err)
}
// First invokeTx
seOne, err := validator.GetStateEncryptor(deployTx, invokeTxOne)
if err != nil {
t.Fatalf("Failed creating state encryptor [%s].", err)
}
pt := []byte("Hello World")
aCt, err := seOne.Encrypt(pt)
if err != nil {
t.Fatalf("Failed encrypting state [%s].", err)
}
aPt, err := seOne.Decrypt(aCt)
if err != nil {
t.Fatalf("Failed decrypting state [%s].", err)
}
if !bytes.Equal(pt, aPt) {
t.Fatalf("Failed decrypting state [%s != %s]: %s", string(pt), string(aPt), err)
}
// Second invokeTx
seTwo, err := validator.GetStateEncryptor(deployTx, invokeTxTwo)
if err != nil {
t.Fatalf("Failed creating state encryptor [%s].", err)
}
aPt2, err := seTwo.Decrypt(aCt)
if err != nil {
t.Fatalf("Failed decrypting state [%s].", err)
}
if !bytes.Equal(pt, aPt2) {
t.Fatalf("Failed decrypting state [%s != %s]: %s", string(pt), string(aPt), err)
}
// queryTx
seThree, err := validator.GetStateEncryptor(deployTx, queryTx)
ctQ, err := seThree.Encrypt(aPt2)
if err != nil {
t.Fatalf("Failed encrypting query result [%s].", err)
}
aPt3, err := invoker.DecryptQueryResult(queryTx, ctQ)
if err != nil {
t.Fatalf("Failed decrypting query result [%s].", err)
}
if !bytes.Equal(aPt2, aPt3) {
t.Fatalf("Failed decrypting query result [%s != %s]: %s", string(aPt2), string(aPt3), err)
}
}
}
}
func TestValidatorStateEncryptor(t *testing.T) {
_, deployTx, err := createConfidentialDeployTransaction(t)
if err != nil {
t.Fatalf("Failed creating deploy transaction [%s]", err)
}
_, invokeTxOne, err := createConfidentialExecuteTransaction(t)
if err != nil {
t.Fatalf("Failed creating invoke transaction [%s]", err)
}
_, invokeTxTwo, err := createConfidentialExecuteTransaction(t)
if err != nil {
t.Fatalf("Failed creating invoke transaction [%s]", err)
}
// Transactions must be PreExecuted by the validators before getting the StateEncryptor
if _, err := validator.TransactionPreValidation(deployTx); err != nil {
t.Fatalf("Failed pre-validating deploty transaction [%s].", err)
}
if deployTx, err = validator.TransactionPreExecution(deployTx); err != nil {
t.Fatalf("Failed pre-validating deploty transaction [%s].", err)
}
if _, err := validator.TransactionPreValidation(invokeTxOne); err != nil {
t.Fatalf("Failed pre-validating exec1 transaction [%s].", err)
}
if invokeTxOne, err = validator.TransactionPreExecution(invokeTxOne); err != nil {
t.Fatalf("Failed pre-validating exec1 transaction [%s].", err)
}
if _, err := validator.TransactionPreValidation(invokeTxTwo); err != nil {
t.Fatalf("Failed pre-validating exec2 transaction [%s].", err)
}
if invokeTxTwo, err = validator.TransactionPreExecution(invokeTxTwo); err != nil {
t.Fatalf("Failed pre-validating exec2 transaction [%s].", err)
}
seOne, err := validator.GetStateEncryptor(deployTx, invokeTxOne)
if err != nil {
t.Fatalf("Failed creating state encryptor [%s].", err)
}
pt := []byte("Hello World")
aCt, err := seOne.Encrypt(pt)
if err != nil {
t.Fatalf("Failed encrypting state [%s].", err)
}
aPt, err := seOne.Decrypt(aCt)
if err != nil {
t.Fatalf("Failed decrypting state [%s].", err)
}
if !bytes.Equal(pt, aPt) {
t.Fatalf("Failed decrypting state [%s != %s]: %s", string(pt), string(aPt), err)
}
seTwo, err := validator.GetStateEncryptor(deployTx, invokeTxTwo)
if err != nil {
t.Fatalf("Failed creating state encryptor [%s].", err)
}
aPt2, err := seTwo.Decrypt(aCt)
if err != nil {
t.Fatalf("Failed decrypting state [%s].", err)
}
if !bytes.Equal(pt, aPt2) {
t.Fatalf("Failed decrypting state [%s != %s]: %s", string(pt), string(aPt), err)
}
}
func TestValidatorSignVerify(t *testing.T) {
msg := []byte("Hello World!!!")
signature, err := validator.Sign(msg)
if err != nil {
t.Fatalf("TestSign: failed generating signature [%s].", err)
}
err = validator.Verify(validator.GetID(), signature, msg)
if err != nil {
t.Fatalf("TestSign: failed validating signature [%s].", err)
}
}
func TestValidatorVerify(t *testing.T) {
msg := []byte("Hello World!!!")
signature, err := validator.Sign(msg)
if err != nil {
t.Fatalf("Failed generating signature [%s].", err)
}
err = validator.Verify(nil, signature, msg)
if err == nil {
t.Fatalf("Verify should fail when given an empty id.", err)
}
err = validator.Verify(msg, signature, msg)
if err == nil {
t.Fatalf("Verify should fail when given an invalid id.", err)
}
err = validator.Verify(validator.GetID(), nil, msg)
if err == nil {
t.Fatalf("Verify should fail when given an invalid signature.", err)
}
err = validator.Verify(validator.GetID(), msg, msg)
if err == nil {
t.Fatalf("Verify should fail when given an invalid signature.", err)
}
err = validator.Verify(validator.GetID(), signature, nil)
if err == nil {
t.Fatalf("Verify should fail when given an invalid messahe.", err)
}
}
func BenchmarkTransactionCreation(b *testing.B) {
b.StopTimer()
b.ResetTimer()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
invoker.GetTCertificateHandlerNext()
for i := 0; i < b.N; i++ {
uuid := util.GenerateUUID()
b.StartTimer()
invoker.NewChaincodeExecute(cis, uuid)
b.StopTimer()
}
}
func BenchmarkTransactionValidation(b *testing.B) {
b.StopTimer()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, tx, _ := createConfidentialTCertHExecuteTransaction(nil)
b.StartTimer()
validator.TransactionPreValidation(tx)
validator.TransactionPreExecution(tx)
b.StopTimer()
}
}
func BenchmarkSign(b *testing.B) {
b.StopTimer()
b.ResetTimer()
//b.Logf("#iterations %d\n", b.N)
signKey, _ := utils.NewECDSAKey()
hash := make([]byte, 48)
for i := 0; i < b.N; i++ {
rand.Read(hash)
b.StartTimer()
utils.ECDSASign(signKey, hash)
b.StopTimer()
}
}
func BenchmarkVerify(b *testing.B) {
b.StopTimer()
b.ResetTimer()
//b.Logf("#iterations %d\n", b.N)
signKey, _ := utils.NewECDSAKey()
verKey := signKey.PublicKey
hash := make([]byte, 48)
for i := 0; i < b.N; i++ {
rand.Read(hash)
sigma, _ := utils.ECDSASign(signKey, hash)
b.StartTimer()
utils.ECDSAVerify(&verKey, hash, sigma)
b.StopTimer()
}
}
func setup() {
// Conf
viper.SetConfigName("crypto_test") // name of config file (without extension)
viper.AddConfigPath(".") // path to look for the config file in
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file [%s] \n", err))
}
// Set Default properties
viper.Set("peer.fileSystemPath", filepath.Join(os.TempDir(), "obc-crypto-tests", "peers"))
viper.Set("server.rootpath", filepath.Join(os.TempDir(), "obc-crypto-tests", "ca"))
viper.Set("peer.pki.tls.rootcert.file", filepath.Join(os.TempDir(),
"obc-crypto-tests", "ca", "tlsca.cert"))
// Logging
var formatter = logging.MustStringFormatter(
`%{color}%{time:15:04:05.000} [%{module}] %{shortfunc} [%{shortfile}] -> %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)
logging.SetFormatter(formatter)
// TX creators
deployTxCreators = []createTxFunc{
createPublicDeployTransaction,
createConfidentialDeployTransaction,
createConfidentialTCertHDeployTransaction,
createConfidentialECertHDeployTransaction,
}
executeTxCreators = []createTxFunc{
createPublicExecuteTransaction,
createConfidentialExecuteTransaction,
createConfidentialTCertHExecuteTransaction,
createConfidentialECertHExecuteTransaction,
}
queryTxCreators = []createTxFunc{
createPublicQueryTransaction,
createConfidentialQueryTransaction,
createConfidentialTCertHQueryTransaction,
createConfidentialECertHQueryTransaction,
}
// Init crypto layer
Init()
// Clenaup folders
removeFolders()
}
func initPKI() {
obcca.LogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr, os.Stdout)
eca = obcca.NewECA()
tca = obcca.NewTCA(eca)
tlsca = obcca.NewTLSCA(eca)
}
func startPKI() {
var opts []grpc.ServerOption
if viper.GetBool("peer.pki.tls.enabled") {
// TLS configuration
creds, err := credentials.NewServerTLSFromFile(
filepath.Join(viper.GetString("server.rootpath"), "tlsca.cert"),
filepath.Join(viper.GetString("server.rootpath"), "tlsca.priv"),
)
if err != nil {
panic("Failed creating credentials for OBC-CA: " + err.Error())
}
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
fmt.Printf("open socket...\n")
sockp, err := net.Listen("tcp", viper.GetString("server.port"))
if err != nil {
panic("Cannot open port: " + err.Error())
}
fmt.Printf("open socket...done\n")
server = grpc.NewServer(opts...)
eca.Start(server)
tca.Start(server)
tlsca.Start(server)
fmt.Printf("start serving...\n")
server.Serve(sockp)
}
func initClients() error {
// Deployer
deployerConf := utils.NodeConfiguration{Type: "client", Name: "user1"}
if err := RegisterClient(deployerConf.Name, ksPwd, deployerConf.GetEnrollmentID(), deployerConf.GetEnrollmentPWD()); err != nil {
return err
}
var err error
deployer, err = InitClient(deployerConf.Name, ksPwd)
if err != nil {
return err
}
// Invoker
invokerConf := utils.NodeConfiguration{Type: "client", Name: "user2"}
if err := RegisterClient(invokerConf.Name, ksPwd, invokerConf.GetEnrollmentID(), invokerConf.GetEnrollmentPWD()); err != nil {
return err
}
invoker, err = InitClient(invokerConf.Name, ksPwd)
if err != nil {
return err
}
return nil
}
func initPeers() error {
// Register
conf := utils.NodeConfiguration{Type: "peer", Name: "peer"}
err := RegisterPeer(conf.Name, ksPwd, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())
if err != nil {
return err
}
// Verify that a second call to Register fails
err = RegisterPeer(conf.Name, ksPwd, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())
if err != nil {
return err
}
// Init
peer, err = InitPeer(conf.Name, ksPwd)
if err != nil {
return err
}
err = RegisterPeer(conf.Name, ksPwd, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())
if err != nil {
return err
}
return err
}
func initValidators() error {
// Register
conf := utils.NodeConfiguration{Type: "validator", Name: "validator"}
err := RegisterValidator(conf.Name, ksPwd, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())
if err != nil {
return err
}
// Verify that a second call to Register fails
err = RegisterValidator(conf.Name, ksPwd, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())
if err != nil {
return err
}
// Init
validator, err = InitValidator(conf.Name, ksPwd)
if err != nil {
return err
}
err = RegisterValidator(conf.Name, ksPwd, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())
if err != nil {
return err
}
return err
}
func createConfidentialDeployTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cds := &obc.ChaincodeDeploymentSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
EffectiveDate: nil,
CodePackage: nil,
}
otx, err := obc.NewChaincodeDeployTransaction(cds, uuid)
if err != nil {
return nil, nil, err
}
tx, err := deployer.NewChaincodeDeployTransaction(cds, uuid)
return otx, tx, err
}
func createConfidentialExecuteTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_EXECUTE)
if err != nil {
return nil, nil, err
}
tx, err := invoker.NewChaincodeExecute(cis, uuid)
return otx, tx, err
}
func createConfidentialQueryTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_QUERY)
if err != nil {
return nil, nil, err
}
tx, err := invoker.NewChaincodeQuery(cis, uuid)
return otx, tx, err
}
func createConfidentialTCertHDeployTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cds := &obc.ChaincodeDeploymentSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
EffectiveDate: nil,
CodePackage: nil,
}
otx, err := obc.NewChaincodeDeployTransaction(cds, uuid)
if err != nil {
return nil, nil, err
}
handler, err := deployer.GetTCertificateHandlerNext()
if err != nil {
return nil, nil, err
}
txHandler, err := handler.GetTransactionHandler()
if err != nil {
return nil, nil, err
}
tx, err := txHandler.NewChaincodeDeployTransaction(cds, uuid)
// Check binding consistency
binding, _ := txHandler.GetBinding()
if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
t.Fatal("Binding is malformed!")
}
// Check confidentiality level
if tx.ConfidentialityLevel != cds.ChaincodeSpec.ConfidentialityLevel {
t.Fatal("Failed setting confidentiality level")
}
// Check metadata
if !reflect.DeepEqual(cds.ChaincodeSpec.Metadata, tx.Metadata) {
t.Fatal("Failed copying metadata")
}
return otx, tx, err
}
func createConfidentialTCertHExecuteTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_EXECUTE)
if err != nil {
return nil, nil, err
}
handler, err := invoker.GetTCertificateHandlerNext()
if err != nil {
return nil, nil, err
}
txHandler, err := handler.GetTransactionHandler()
if err != nil {
return nil, nil, err
}
tx, err := txHandler.NewChaincodeExecute(cis, uuid)
// Check binding consistency
binding, _ := txHandler.GetBinding()
if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
t.Fatal("Binding is malformed!")
}
// Check confidentiality level
if tx.ConfidentialityLevel != cis.ChaincodeSpec.ConfidentialityLevel {
t.Fatal("Failed setting confidentiality level")
}
// Check metadata
if !reflect.DeepEqual(cis.ChaincodeSpec.Metadata, tx.Metadata) {
t.Fatal("Failed copying metadata")
}
return otx, tx, err
}
func createConfidentialTCertHQueryTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_QUERY)
if err != nil {
return nil, nil, err
}
handler, err := invoker.GetTCertificateHandlerNext()
if err != nil {
return nil, nil, err
}
txHandler, err := handler.GetTransactionHandler()
if err != nil {
return nil, nil, err
}
tx, err := txHandler.NewChaincodeQuery(cis, uuid)
// Check binding consistency
binding, _ := txHandler.GetBinding()
if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
t.Fatal("Binding is malformed!")
}
// Check confidentiality level
if tx.ConfidentialityLevel != cis.ChaincodeSpec.ConfidentialityLevel {
t.Fatal("Failed setting confidentiality level")
}
// Check metadata
if !reflect.DeepEqual(cis.ChaincodeSpec.Metadata, tx.Metadata) {
t.Fatal("Failed copying metadata")
}
return otx, tx, err
}
func createConfidentialECertHDeployTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cds := &obc.ChaincodeDeploymentSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
EffectiveDate: nil,
CodePackage: nil,
}
otx, err := obc.NewChaincodeDeployTransaction(cds, uuid)
if err != nil {
return nil, nil, err
}
handler, err := deployer.GetEnrollmentCertificateHandler()
if err != nil {
return nil, nil, err
}
txHandler, err := handler.GetTransactionHandler()
if err != nil {
return nil, nil, err
}
tx, err := txHandler.NewChaincodeDeployTransaction(cds, uuid)
// Check binding consistency
binding, _ := txHandler.GetBinding()
if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
t.Fatal("Binding is malformed!")
}
// Check confidentiality level
if tx.ConfidentialityLevel != cds.ChaincodeSpec.ConfidentialityLevel {
t.Fatal("Failed setting confidentiality level")
}
// Check metadata
if !reflect.DeepEqual(cds.ChaincodeSpec.Metadata, tx.Metadata) {
t.Fatal("Failed copying metadata")
}
return otx, tx, err
}
func createConfidentialECertHExecuteTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_EXECUTE)
if err != nil {
return nil, nil, err
}
handler, err := invoker.GetEnrollmentCertificateHandler()
if err != nil {
return nil, nil, err
}
txHandler, err := handler.GetTransactionHandler()
if err != nil {
return nil, nil, err
}
tx, err := txHandler.NewChaincodeExecute(cis, uuid)
// Check binding consistency
binding, _ := txHandler.GetBinding()
if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
t.Fatal("Binding is malformed!")
}
// Check confidentiality level
if tx.ConfidentialityLevel != cis.ChaincodeSpec.ConfidentialityLevel {
t.Fatal("Failed setting confidentiality level")
}
// Check metadata
if !reflect.DeepEqual(cis.ChaincodeSpec.Metadata, tx.Metadata) {
t.Fatal("Failed copying metadata")
}
return otx, tx, err
}
func createConfidentialECertHQueryTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_QUERY)
if err != nil {
return nil, nil, err
}
handler, err := invoker.GetEnrollmentCertificateHandler()
if err != nil {
return nil, nil, err
}
txHandler, err := handler.GetTransactionHandler()
if err != nil {
return nil, nil, err
}
tx, err := txHandler.NewChaincodeQuery(cis, uuid)
// Check binding consistency
binding, _ := txHandler.GetBinding()
if !reflect.DeepEqual(binding, utils.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
t.Fatal("Binding is malformed!")
}
// Check confidentiality level
if tx.ConfidentialityLevel != cis.ChaincodeSpec.ConfidentialityLevel {
t.Fatal("Failed setting confidentiality level")
}
// Check metadata
if !reflect.DeepEqual(cis.ChaincodeSpec.Metadata, tx.Metadata) {
t.Fatal("Failed copying metadata")
}
return otx, tx, err
}
func createPublicDeployTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cds := &obc.ChaincodeDeploymentSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_PUBLIC,
},
EffectiveDate: nil,
CodePackage: nil,
}
otx, err := obc.NewChaincodeDeployTransaction(cds, uuid)
if err != nil {
return nil, nil, err
}
tx, err := deployer.NewChaincodeDeployTransaction(cds, uuid)
return otx, tx, err
}
func createPublicExecuteTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_PUBLIC,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_EXECUTE)
if err != nil {
return nil, nil, err
}
tx, err := invoker.NewChaincodeExecute(cis, uuid)
return otx, tx, err
}
func createPublicQueryTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
uuid := util.GenerateUUID()
cis := &obc.ChaincodeInvocationSpec{
ChaincodeSpec: &obc.ChaincodeSpec{
Type: obc.ChaincodeSpec_GOLANG,
ChaincodeID: &obc.ChaincodeID{Path: "Contract001"},
CtorMsg: nil,
ConfidentialityLevel: obc.ConfidentialityLevel_PUBLIC,
},
}
otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_QUERY)
if err != nil {
return nil, nil, err
}
tx, err := invoker.NewChaincodeQuery(cis, uuid)
return otx, tx, err
}
func isEqual(src, dst *obc.Transaction) error {
if !reflect.DeepEqual(src.Payload, dst.Payload) {
return fmt.Errorf("Different Payload [%s]!=[%s].", utils.EncodeBase64(src.Payload), utils.EncodeBase64(dst.Payload))
}
if !reflect.DeepEqual(src.ChaincodeID, dst.ChaincodeID) {
return fmt.Errorf("Different ChaincodeID [%s]!=[%s].", utils.EncodeBase64(src.ChaincodeID), utils.EncodeBase64(dst.ChaincodeID))
}
if !reflect.DeepEqual(src.Metadata, dst.Metadata) {
return fmt.Errorf("Different Metadata [%s]!=[%s].", utils.EncodeBase64(src.Metadata), utils.EncodeBase64(dst.Metadata))
}
return nil
}
func cleanup() {
fmt.Println("Cleanup...")
CloseAllClients()
CloseAllPeers()
CloseAllValidators()
stopPKI()
removeFolders()
fmt.Println("Cleanup...done!")
}
func stopPKI() {
eca.Close()
tca.Close()
tlsca.Close()
server.Stop()
}
func removeFolders() {
if err := os.RemoveAll(filepath.Join(os.TempDir(), "obc-crypto-tests")); err != nil {
fmt.Printf("Failed removing [%s] [%s]\n", "obc-crypto-tests", err)
}
}
|
{
"content_hash": "1fd9737763369f203a0ec7a73d303f9d",
"timestamp": "",
"source": "github",
"line_count": 1524,
"max_line_length": 130,
"avg_line_length": 27.06758530183727,
"alnum_prop": 0.6767593512884537,
"repo_name": "ghaskins/obc-peer",
"id": "6d1c3c2eadf7544a3493dd860da53e83c11de95b",
"size": "42011",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "openchain/crypto/crypto_test.go",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Cucumber",
"bytes": "18711"
},
{
"name": "Go",
"bytes": "1395885"
},
{
"name": "Protocol Buffer",
"bytes": "31595"
},
{
"name": "Python",
"bytes": "27330"
},
{
"name": "Shell",
"bytes": "5302"
},
{
"name": "TypeScript",
"bytes": "33203"
}
],
"symlink_target": ""
}
|
/**
*
*/
package org.ovirt.engine.core.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Arrays;
import org.apache.commons.lang.NotImplementedException;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmStatistics;
import org.ovirt.engine.core.compat.Guid;
import org.springframework.dao.DataIntegrityViolationException;
/**
*
*/
public class VmStatisticsDAOTest extends BaseDAOTestCase {
private static final Guid EXISTING_VM_ID = new Guid("77296e00-0cad-4e5a-9299-008a7b6f4355");
private VmStaticDAO vmStaticDao;
private VmStatisticsDAO dao;
private VmStatic newVmStatic;
private VmStatistics newVmStatistics;
@Override
public void setUp() throws Exception {
super.setUp();
vmStaticDao = dbFacade.getVmStaticDao();
dao = dbFacade.getVmStatisticsDao();
newVmStatic = vmStaticDao.get(new Guid("77296e00-0cad-4e5a-9299-008a7b6f5001"));
newVmStatistics = new VmStatistics();
}
@Test
public void testGet() {
VmStatistics result = dao.get(EXISTING_VM_ID);
assertNotNull(result);
assertEquals(EXISTING_VM_ID, result.getId());
}
@Test
public void testGetNonExistingId() {
VmStatistics result = dao.get(Guid.newGuid());
assertNull(result);
}
@Test
public void testSave() {
newVmStatistics.setId(newVmStatic.getId());
newVmStatistics.setMigrationProgressPercent(0);
dao.save(newVmStatistics);
VmStatistics stats = dao.get(newVmStatic.getId());
assertNotNull(stats);
assertEquals(newVmStatistics, stats);
}
@Test(expected = DataIntegrityViolationException.class)
public void testSaveStaticDoesNotExist() {
Guid newGuid = Guid.newGuid();
newVmStatistics.setId(newGuid);
dao.save(newVmStatistics);
VmStatistics stats = dao.get(newGuid);
assertNull(stats);
}
@Test
public void testUpdateStatistics() {
VmStatistics before = dao.get(EXISTING_VM_ID);
before.setusage_mem_percent(17);
before.setDisksUsage("java.util.map { [ ] }");
dao.update(before);
VmStatistics after = dao.get(EXISTING_VM_ID);
assertEquals(before, after);
}
@Test
public void testRemoveStatistics() {
VmStatistics before = dao.get(EXISTING_VM_ID);
// make sure we're using a real example
assertNotNull(before);
dao.remove(EXISTING_VM_ID);
VmStatistics after = dao.get(EXISTING_VM_ID);
assertNull(after);
}
@Test(expected = NotImplementedException.class)
public void testGetAll() {
dao.getAll();
}
@Test
public void testUpdateAll() throws Exception {
VmStatistics existingVm = dao.get(EXISTING_VM_ID);
VmStatistics existingVm2 = dao.get(new Guid("77296e00-0cad-4e5a-9299-008a7b6f4356"));
existingVm.setcpu_sys(50.0);
existingVm2.setcpu_user(50.0);
dao.updateAll(Arrays.asList(new VmStatistics[] { existingVm, existingVm2 }));
assertEquals(existingVm, dao.get(existingVm.getId()));
assertEquals(existingVm2, dao.get(existingVm2.getId()));
}
}
|
{
"content_hash": "8fefaa806396cbf457a8ca8dbd739b72",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 96,
"avg_line_length": 29.36521739130435,
"alnum_prop": 0.6763399466982529,
"repo_name": "halober/ovirt-engine",
"id": "1ae518737408676638280a055ee961f143409e9a",
"size": "3377",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/VmStatisticsDAOTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "251848"
},
{
"name": "Java",
"bytes": "26541598"
},
{
"name": "JavaScript",
"bytes": "890"
},
{
"name": "Python",
"bytes": "698283"
},
{
"name": "Shell",
"bytes": "105362"
},
{
"name": "XSLT",
"bytes": "54683"
}
],
"symlink_target": ""
}
|
using System;
using System.Drawing;
using System.Windows;
using MetroRadiance.Interop;
namespace SylphyHorn.Interop
{
public static class IconHelper
{
public static Icon GetIconFromResource(Uri uri)
{
var streamResourceInfo = System.Windows.Application.GetResourceStream(uri);
if (streamResourceInfo == null) throw new ArgumentException("Resource not found.", nameof(uri));
using (var stream = streamResourceInfo.Stream)
{
var icon = new Icon(stream);
return ScaleIconToDpi(icon);
}
}
public static Icon ToIcon(this Bitmap bitmap)
{
var iconHandle = bitmap.GetHicon();
var icon = Icon.FromHandle(iconHandle);
return icon;
}
private static Icon ScaleIconToDpi(Icon targetIcon)
{
var dpi = GetMonitorDpi();
return new Icon(targetIcon, new System.Drawing.Size((int)(16 * dpi.ScaleX), (int)(16 * dpi.ScaleY)));
}
public static System.Windows.Size GetIconSize()
{
var dpi = GetMonitorDpi();
return new System.Windows.Size(SystemParameters.SmallIconWidth * dpi.ScaleX, SystemParameters.SmallIconHeight * dpi.ScaleY);
}
private static Dpi GetMonitorDpi()
{
return PerMonitorDpi.GetDpi(IntPtr.Zero);
}
}
}
|
{
"content_hash": "80f8d2404ec1e36b6cff216794cb5bb7",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 127,
"avg_line_length": 23.82,
"alnum_prop": 0.7187237615449202,
"repo_name": "Grabacr07/SylphyHorn",
"id": "a50d74c47763a48e119a6095c520f5dcc2834bbe",
"size": "1193",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "source/SylphyHorn/Interop/IconHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "119282"
},
{
"name": "PowerShell",
"bytes": "5665"
}
],
"symlink_target": ""
}
|
<abstract xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<para>
MidoNet is a network virtualization software for
Infrastructure-as-a-Service (IaaS) clouds.
</para>
<para>
It decouples your IaaS cloud from your network hardware, creating an
intelligent software abstraction layer between your end hosts and your
physical network.
</para>
<para>
This guide walks through the minimum installation and configuration
steps neccessary to use MidoNet with OpenStack.
</para>
<para>
<!-- For SNAPSHOT versions, a DRAFT warning gets inserted here automatically. -->
{draftWarningEN}
<!-- Link to Mailing Lists and Chat. -->
<note>
<para>
Please consult the
<link xlink:href="https://github.com/midonet/midonet/wiki/Communication">MidoNet Mailing Lists or Chat</link>
if you need assistance.
</para>
</note>
</para>
</abstract>
|
{
"content_hash": "036531151cf512899b52a0b48dcf8650",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 125,
"avg_line_length": 37.642857142857146,
"alnum_prop": 0.6195445920303605,
"repo_name": "midonet/midonet-docs",
"id": "cf040e8ed173b17ebba9a97b3e301bc29d30f213",
"size": "1054",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/quick-start-guide/src/docinfo_abstract_en.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54603199"
},
{
"name": "HTML",
"bytes": "394216894"
},
{
"name": "Java",
"bytes": "333758"
},
{
"name": "JavaScript",
"bytes": "44659041"
},
{
"name": "Shell",
"bytes": "5616"
},
{
"name": "XProc",
"bytes": "89414"
},
{
"name": "XSLT",
"bytes": "1225973"
}
],
"symlink_target": ""
}
|
START_ATF_NAMESPACE
typedef _BIDI_DATA *LPBIDI_DATA;
END_ATF_NAMESPACE
|
{
"content_hash": "64ae3782fb2cabe93b392063dbdbedef",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 36,
"avg_line_length": 25,
"alnum_prop": 0.76,
"repo_name": "goodwinxp/Yorozuya",
"id": "e0667acae0948b758ce0be5bb20f37194c53ca1f",
"size": "253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/ATF/LPBIDI_DATA.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "207291"
},
{
"name": "C++",
"bytes": "21670817"
}
],
"symlink_target": ""
}
|
module dijit._editor.plugins{
export class EnterKeyHandling extends dijit._editor._Plugin {
blockNodeForEnter : String;
_checkListLater : bool;
bogusHtmlContent : String;
blockNodes : RegExp;
_pressedEnterInBlock : any;
onKeyPressed (e:any) : any;
handleEnterKey (e:any) : any;
_adjustNodeAndOffset (node:HTMLElement,offset:number) : any;
removeTrailingBr (container:any) : any;
}
}
|
{
"content_hash": "f956ed9f9ed9b698bf20a7788528f0be",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 61,
"avg_line_length": 29.46153846153846,
"alnum_prop": 0.7728459530026109,
"repo_name": "stopyoukid/DojoToTypescriptConverter",
"id": "b7ceced0d46ce680c270da09b4399af952ccfaa3",
"size": "472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "out/separate/dijit._editor.plugins.EnterKeyHandling.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "29092"
}
],
"symlink_target": ""
}
|
package flight
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion7
// FlightServiceClient is the client API for FlightService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type FlightServiceClient interface {
//
// Handshake between client and server. Depending on the server, the
// handshake may be required to determine the token that should be used for
// future operations. Both request and response are streams to allow multiple
// round-trips depending on auth mechanism.
Handshake(ctx context.Context, opts ...grpc.CallOption) (FlightService_HandshakeClient, error)
//
// Get a list of available streams given a particular criteria. Most flight
// services will expose one or more streams that are readily available for
// retrieval. This api allows listing the streams available for
// consumption. A user can also provide a criteria. The criteria can limit
// the subset of streams that can be listed via this interface. Each flight
// service allows its own definition of how to consume criteria.
ListFlights(ctx context.Context, in *Criteria, opts ...grpc.CallOption) (FlightService_ListFlightsClient, error)
//
// For a given FlightDescriptor, get information about how the flight can be
// consumed. This is a useful interface if the consumer of the interface
// already can identify the specific flight to consume. This interface can
// also allow a consumer to generate a flight stream through a specified
// descriptor. For example, a flight descriptor might be something that
// includes a SQL statement or a Pickled Python operation that will be
// executed. In those cases, the descriptor will not be previously available
// within the list of available streams provided by ListFlights but will be
// available for consumption for the duration defined by the specific flight
// service.
GetFlightInfo(ctx context.Context, in *FlightDescriptor, opts ...grpc.CallOption) (*FlightInfo, error)
//
// For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
// This is used when a consumer needs the Schema of flight stream. Similar to
// GetFlightInfo this interface may generate a new flight that was not previously
// available in ListFlights.
GetSchema(ctx context.Context, in *FlightDescriptor, opts ...grpc.CallOption) (*SchemaResult, error)
//
// Retrieve a single stream associated with a particular descriptor
// associated with the referenced ticket. A Flight can be composed of one or
// more streams where each stream can be retrieved using a separate opaque
// ticket that the flight service uses for managing a collection of streams.
DoGet(ctx context.Context, in *Ticket, opts ...grpc.CallOption) (FlightService_DoGetClient, error)
//
// Push a stream to the flight service associated with a particular
// flight stream. This allows a client of a flight service to upload a stream
// of data. Depending on the particular flight service, a client consumer
// could be allowed to upload a single stream per descriptor or an unlimited
// number. In the latter, the service might implement a 'seal' action that
// can be applied to a descriptor once all streams are uploaded.
DoPut(ctx context.Context, opts ...grpc.CallOption) (FlightService_DoPutClient, error)
//
// Open a bidirectional data channel for a given descriptor. This
// allows clients to send and receive arbitrary Arrow data and
// application-specific metadata in a single logical stream. In
// contrast to DoGet/DoPut, this is more suited for clients
// offloading computation (rather than storage) to a Flight service.
DoExchange(ctx context.Context, opts ...grpc.CallOption) (FlightService_DoExchangeClient, error)
//
// Flight services can support an arbitrary number of simple actions in
// addition to the possible ListFlights, GetFlightInfo, DoGet, DoPut
// operations that are potentially available. DoAction allows a flight client
// to do a specific action against a flight service. An action includes
// opaque request and response objects that are specific to the type action
// being undertaken.
DoAction(ctx context.Context, in *Action, opts ...grpc.CallOption) (FlightService_DoActionClient, error)
//
// A flight service exposes all of the available action types that it has
// along with descriptions. This allows different flight consumers to
// understand the capabilities of the flight service.
ListActions(ctx context.Context, in *Empty, opts ...grpc.CallOption) (FlightService_ListActionsClient, error)
}
type flightServiceClient struct {
cc grpc.ClientConnInterface
}
func NewFlightServiceClient(cc grpc.ClientConnInterface) FlightServiceClient {
return &flightServiceClient{cc}
}
var flightServiceHandshakeStreamDesc = &grpc.StreamDesc{
StreamName: "Handshake",
ServerStreams: true,
ClientStreams: true,
}
func (c *flightServiceClient) Handshake(ctx context.Context, opts ...grpc.CallOption) (FlightService_HandshakeClient, error) {
stream, err := c.cc.NewStream(ctx, flightServiceHandshakeStreamDesc, "/arrow.flight.protocol.FlightService/Handshake", opts...)
if err != nil {
return nil, err
}
x := &flightServiceHandshakeClient{stream}
return x, nil
}
type FlightService_HandshakeClient interface {
Send(*HandshakeRequest) error
Recv() (*HandshakeResponse, error)
grpc.ClientStream
}
type flightServiceHandshakeClient struct {
grpc.ClientStream
}
func (x *flightServiceHandshakeClient) Send(m *HandshakeRequest) error {
return x.ClientStream.SendMsg(m)
}
func (x *flightServiceHandshakeClient) Recv() (*HandshakeResponse, error) {
m := new(HandshakeResponse)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var flightServiceListFlightsStreamDesc = &grpc.StreamDesc{
StreamName: "ListFlights",
ServerStreams: true,
}
func (c *flightServiceClient) ListFlights(ctx context.Context, in *Criteria, opts ...grpc.CallOption) (FlightService_ListFlightsClient, error) {
stream, err := c.cc.NewStream(ctx, flightServiceListFlightsStreamDesc, "/arrow.flight.protocol.FlightService/ListFlights", opts...)
if err != nil {
return nil, err
}
x := &flightServiceListFlightsClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlightService_ListFlightsClient interface {
Recv() (*FlightInfo, error)
grpc.ClientStream
}
type flightServiceListFlightsClient struct {
grpc.ClientStream
}
func (x *flightServiceListFlightsClient) Recv() (*FlightInfo, error) {
m := new(FlightInfo)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var flightServiceGetFlightInfoStreamDesc = &grpc.StreamDesc{
StreamName: "GetFlightInfo",
}
func (c *flightServiceClient) GetFlightInfo(ctx context.Context, in *FlightDescriptor, opts ...grpc.CallOption) (*FlightInfo, error) {
out := new(FlightInfo)
err := c.cc.Invoke(ctx, "/arrow.flight.protocol.FlightService/GetFlightInfo", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
var flightServiceGetSchemaStreamDesc = &grpc.StreamDesc{
StreamName: "GetSchema",
}
func (c *flightServiceClient) GetSchema(ctx context.Context, in *FlightDescriptor, opts ...grpc.CallOption) (*SchemaResult, error) {
out := new(SchemaResult)
err := c.cc.Invoke(ctx, "/arrow.flight.protocol.FlightService/GetSchema", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
var flightServiceDoGetStreamDesc = &grpc.StreamDesc{
StreamName: "DoGet",
ServerStreams: true,
}
func (c *flightServiceClient) DoGet(ctx context.Context, in *Ticket, opts ...grpc.CallOption) (FlightService_DoGetClient, error) {
stream, err := c.cc.NewStream(ctx, flightServiceDoGetStreamDesc, "/arrow.flight.protocol.FlightService/DoGet", opts...)
if err != nil {
return nil, err
}
x := &flightServiceDoGetClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlightService_DoGetClient interface {
Recv() (*FlightData, error)
grpc.ClientStream
}
type flightServiceDoGetClient struct {
grpc.ClientStream
}
func (x *flightServiceDoGetClient) Recv() (*FlightData, error) {
m := new(FlightData)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var flightServiceDoPutStreamDesc = &grpc.StreamDesc{
StreamName: "DoPut",
ServerStreams: true,
ClientStreams: true,
}
func (c *flightServiceClient) DoPut(ctx context.Context, opts ...grpc.CallOption) (FlightService_DoPutClient, error) {
stream, err := c.cc.NewStream(ctx, flightServiceDoPutStreamDesc, "/arrow.flight.protocol.FlightService/DoPut", opts...)
if err != nil {
return nil, err
}
x := &flightServiceDoPutClient{stream}
return x, nil
}
type FlightService_DoPutClient interface {
Send(*FlightData) error
Recv() (*PutResult, error)
grpc.ClientStream
}
type flightServiceDoPutClient struct {
grpc.ClientStream
}
func (x *flightServiceDoPutClient) Send(m *FlightData) error {
return x.ClientStream.SendMsg(m)
}
func (x *flightServiceDoPutClient) Recv() (*PutResult, error) {
m := new(PutResult)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var flightServiceDoExchangeStreamDesc = &grpc.StreamDesc{
StreamName: "DoExchange",
ServerStreams: true,
ClientStreams: true,
}
func (c *flightServiceClient) DoExchange(ctx context.Context, opts ...grpc.CallOption) (FlightService_DoExchangeClient, error) {
stream, err := c.cc.NewStream(ctx, flightServiceDoExchangeStreamDesc, "/arrow.flight.protocol.FlightService/DoExchange", opts...)
if err != nil {
return nil, err
}
x := &flightServiceDoExchangeClient{stream}
return x, nil
}
type FlightService_DoExchangeClient interface {
Send(*FlightData) error
Recv() (*FlightData, error)
grpc.ClientStream
}
type flightServiceDoExchangeClient struct {
grpc.ClientStream
}
func (x *flightServiceDoExchangeClient) Send(m *FlightData) error {
return x.ClientStream.SendMsg(m)
}
func (x *flightServiceDoExchangeClient) Recv() (*FlightData, error) {
m := new(FlightData)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var flightServiceDoActionStreamDesc = &grpc.StreamDesc{
StreamName: "DoAction",
ServerStreams: true,
}
func (c *flightServiceClient) DoAction(ctx context.Context, in *Action, opts ...grpc.CallOption) (FlightService_DoActionClient, error) {
stream, err := c.cc.NewStream(ctx, flightServiceDoActionStreamDesc, "/arrow.flight.protocol.FlightService/DoAction", opts...)
if err != nil {
return nil, err
}
x := &flightServiceDoActionClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlightService_DoActionClient interface {
Recv() (*Result, error)
grpc.ClientStream
}
type flightServiceDoActionClient struct {
grpc.ClientStream
}
func (x *flightServiceDoActionClient) Recv() (*Result, error) {
m := new(Result)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var flightServiceListActionsStreamDesc = &grpc.StreamDesc{
StreamName: "ListActions",
ServerStreams: true,
}
func (c *flightServiceClient) ListActions(ctx context.Context, in *Empty, opts ...grpc.CallOption) (FlightService_ListActionsClient, error) {
stream, err := c.cc.NewStream(ctx, flightServiceListActionsStreamDesc, "/arrow.flight.protocol.FlightService/ListActions", opts...)
if err != nil {
return nil, err
}
x := &flightServiceListActionsClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlightService_ListActionsClient interface {
Recv() (*ActionType, error)
grpc.ClientStream
}
type flightServiceListActionsClient struct {
grpc.ClientStream
}
func (x *flightServiceListActionsClient) Recv() (*ActionType, error) {
m := new(ActionType)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// FlightServiceService is the service API for FlightService service.
// Fields should be assigned to their respective handler implementations only before
// RegisterFlightServiceService is called. Any unassigned fields will result in the
// handler for that method returning an Unimplemented error.
type FlightServiceService struct {
//
// Handshake between client and server. Depending on the server, the
// handshake may be required to determine the token that should be used for
// future operations. Both request and response are streams to allow multiple
// round-trips depending on auth mechanism.
Handshake func(FlightService_HandshakeServer) error
//
// Get a list of available streams given a particular criteria. Most flight
// services will expose one or more streams that are readily available for
// retrieval. This api allows listing the streams available for
// consumption. A user can also provide a criteria. The criteria can limit
// the subset of streams that can be listed via this interface. Each flight
// service allows its own definition of how to consume criteria.
ListFlights func(*Criteria, FlightService_ListFlightsServer) error
//
// For a given FlightDescriptor, get information about how the flight can be
// consumed. This is a useful interface if the consumer of the interface
// already can identify the specific flight to consume. This interface can
// also allow a consumer to generate a flight stream through a specified
// descriptor. For example, a flight descriptor might be something that
// includes a SQL statement or a Pickled Python operation that will be
// executed. In those cases, the descriptor will not be previously available
// within the list of available streams provided by ListFlights but will be
// available for consumption for the duration defined by the specific flight
// service.
GetFlightInfo func(context.Context, *FlightDescriptor) (*FlightInfo, error)
//
// For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
// This is used when a consumer needs the Schema of flight stream. Similar to
// GetFlightInfo this interface may generate a new flight that was not previously
// available in ListFlights.
GetSchema func(context.Context, *FlightDescriptor) (*SchemaResult, error)
//
// Retrieve a single stream associated with a particular descriptor
// associated with the referenced ticket. A Flight can be composed of one or
// more streams where each stream can be retrieved using a separate opaque
// ticket that the flight service uses for managing a collection of streams.
DoGet func(*Ticket, FlightService_DoGetServer) error
//
// Push a stream to the flight service associated with a particular
// flight stream. This allows a client of a flight service to upload a stream
// of data. Depending on the particular flight service, a client consumer
// could be allowed to upload a single stream per descriptor or an unlimited
// number. In the latter, the service might implement a 'seal' action that
// can be applied to a descriptor once all streams are uploaded.
DoPut func(FlightService_DoPutServer) error
//
// Open a bidirectional data channel for a given descriptor. This
// allows clients to send and receive arbitrary Arrow data and
// application-specific metadata in a single logical stream. In
// contrast to DoGet/DoPut, this is more suited for clients
// offloading computation (rather than storage) to a Flight service.
DoExchange func(FlightService_DoExchangeServer) error
//
// Flight services can support an arbitrary number of simple actions in
// addition to the possible ListFlights, GetFlightInfo, DoGet, DoPut
// operations that are potentially available. DoAction allows a flight client
// to do a specific action against a flight service. An action includes
// opaque request and response objects that are specific to the type action
// being undertaken.
DoAction func(*Action, FlightService_DoActionServer) error
//
// A flight service exposes all of the available action types that it has
// along with descriptions. This allows different flight consumers to
// understand the capabilities of the flight service.
ListActions func(*Empty, FlightService_ListActionsServer) error
}
func (s *FlightServiceService) handshake(_ interface{}, stream grpc.ServerStream) error {
return s.Handshake(&flightServiceHandshakeServer{stream})
}
func (s *FlightServiceService) listFlights(_ interface{}, stream grpc.ServerStream) error {
m := new(Criteria)
if err := stream.RecvMsg(m); err != nil {
return err
}
return s.ListFlights(m, &flightServiceListFlightsServer{stream})
}
func (s *FlightServiceService) getFlightInfo(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FlightDescriptor)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetFlightInfo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/arrow.flight.protocol.FlightService/GetFlightInfo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetFlightInfo(ctx, req.(*FlightDescriptor))
}
return interceptor(ctx, in, info, handler)
}
func (s *FlightServiceService) getSchema(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FlightDescriptor)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetSchema(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/arrow.flight.protocol.FlightService/GetSchema",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetSchema(ctx, req.(*FlightDescriptor))
}
return interceptor(ctx, in, info, handler)
}
func (s *FlightServiceService) doGet(_ interface{}, stream grpc.ServerStream) error {
m := new(Ticket)
if err := stream.RecvMsg(m); err != nil {
return err
}
return s.DoGet(m, &flightServiceDoGetServer{stream})
}
func (s *FlightServiceService) doPut(_ interface{}, stream grpc.ServerStream) error {
return s.DoPut(&flightServiceDoPutServer{stream})
}
func (s *FlightServiceService) doExchange(_ interface{}, stream grpc.ServerStream) error {
return s.DoExchange(&flightServiceDoExchangeServer{stream})
}
func (s *FlightServiceService) doAction(_ interface{}, stream grpc.ServerStream) error {
m := new(Action)
if err := stream.RecvMsg(m); err != nil {
return err
}
return s.DoAction(m, &flightServiceDoActionServer{stream})
}
func (s *FlightServiceService) listActions(_ interface{}, stream grpc.ServerStream) error {
m := new(Empty)
if err := stream.RecvMsg(m); err != nil {
return err
}
return s.ListActions(m, &flightServiceListActionsServer{stream})
}
type FlightService_HandshakeServer interface {
Send(*HandshakeResponse) error
Recv() (*HandshakeRequest, error)
grpc.ServerStream
}
type flightServiceHandshakeServer struct {
grpc.ServerStream
}
func (x *flightServiceHandshakeServer) Send(m *HandshakeResponse) error {
return x.ServerStream.SendMsg(m)
}
func (x *flightServiceHandshakeServer) Recv() (*HandshakeRequest, error) {
m := new(HandshakeRequest)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
type FlightService_ListFlightsServer interface {
Send(*FlightInfo) error
grpc.ServerStream
}
type flightServiceListFlightsServer struct {
grpc.ServerStream
}
func (x *flightServiceListFlightsServer) Send(m *FlightInfo) error {
return x.ServerStream.SendMsg(m)
}
type FlightService_DoGetServer interface {
Send(*FlightData) error
grpc.ServerStream
}
type flightServiceDoGetServer struct {
grpc.ServerStream
}
func (x *flightServiceDoGetServer) Send(m *FlightData) error {
return x.ServerStream.SendMsg(m)
}
type FlightService_DoPutServer interface {
Send(*PutResult) error
Recv() (*FlightData, error)
grpc.ServerStream
}
type flightServiceDoPutServer struct {
grpc.ServerStream
}
func (x *flightServiceDoPutServer) Send(m *PutResult) error {
return x.ServerStream.SendMsg(m)
}
func (x *flightServiceDoPutServer) Recv() (*FlightData, error) {
m := new(FlightData)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
type FlightService_DoExchangeServer interface {
Send(*FlightData) error
Recv() (*FlightData, error)
grpc.ServerStream
}
type flightServiceDoExchangeServer struct {
grpc.ServerStream
}
func (x *flightServiceDoExchangeServer) Send(m *FlightData) error {
return x.ServerStream.SendMsg(m)
}
func (x *flightServiceDoExchangeServer) Recv() (*FlightData, error) {
m := new(FlightData)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
type FlightService_DoActionServer interface {
Send(*Result) error
grpc.ServerStream
}
type flightServiceDoActionServer struct {
grpc.ServerStream
}
func (x *flightServiceDoActionServer) Send(m *Result) error {
return x.ServerStream.SendMsg(m)
}
type FlightService_ListActionsServer interface {
Send(*ActionType) error
grpc.ServerStream
}
type flightServiceListActionsServer struct {
grpc.ServerStream
}
func (x *flightServiceListActionsServer) Send(m *ActionType) error {
return x.ServerStream.SendMsg(m)
}
// RegisterFlightServiceService registers a service implementation with a gRPC server.
func RegisterFlightServiceService(s grpc.ServiceRegistrar, srv *FlightServiceService) {
srvCopy := *srv
if srvCopy.Handshake == nil {
srvCopy.Handshake = func(FlightService_HandshakeServer) error {
return status.Errorf(codes.Unimplemented, "method Handshake not implemented")
}
}
if srvCopy.ListFlights == nil {
srvCopy.ListFlights = func(*Criteria, FlightService_ListFlightsServer) error {
return status.Errorf(codes.Unimplemented, "method ListFlights not implemented")
}
}
if srvCopy.GetFlightInfo == nil {
srvCopy.GetFlightInfo = func(context.Context, *FlightDescriptor) (*FlightInfo, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFlightInfo not implemented")
}
}
if srvCopy.GetSchema == nil {
srvCopy.GetSchema = func(context.Context, *FlightDescriptor) (*SchemaResult, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetSchema not implemented")
}
}
if srvCopy.DoGet == nil {
srvCopy.DoGet = func(*Ticket, FlightService_DoGetServer) error {
return status.Errorf(codes.Unimplemented, "method DoGet not implemented")
}
}
if srvCopy.DoPut == nil {
srvCopy.DoPut = func(FlightService_DoPutServer) error {
return status.Errorf(codes.Unimplemented, "method DoPut not implemented")
}
}
if srvCopy.DoExchange == nil {
srvCopy.DoExchange = func(FlightService_DoExchangeServer) error {
return status.Errorf(codes.Unimplemented, "method DoExchange not implemented")
}
}
if srvCopy.DoAction == nil {
srvCopy.DoAction = func(*Action, FlightService_DoActionServer) error {
return status.Errorf(codes.Unimplemented, "method DoAction not implemented")
}
}
if srvCopy.ListActions == nil {
srvCopy.ListActions = func(*Empty, FlightService_ListActionsServer) error {
return status.Errorf(codes.Unimplemented, "method ListActions not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "arrow.flight.protocol.FlightService",
Methods: []grpc.MethodDesc{
{
MethodName: "GetFlightInfo",
Handler: srvCopy.getFlightInfo,
},
{
MethodName: "GetSchema",
Handler: srvCopy.getSchema,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "Handshake",
Handler: srvCopy.handshake,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "ListFlights",
Handler: srvCopy.listFlights,
ServerStreams: true,
},
{
StreamName: "DoGet",
Handler: srvCopy.doGet,
ServerStreams: true,
},
{
StreamName: "DoPut",
Handler: srvCopy.doPut,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "DoExchange",
Handler: srvCopy.doExchange,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "DoAction",
Handler: srvCopy.doAction,
ServerStreams: true,
},
{
StreamName: "ListActions",
Handler: srvCopy.listActions,
ServerStreams: true,
},
},
Metadata: "Flight.proto",
}
s.RegisterService(&sd, nil)
}
// NewFlightServiceService creates a new FlightServiceService containing the
// implemented methods of the FlightService service in s. Any unimplemented
// methods will result in the gRPC server returning an UNIMPLEMENTED status to the client.
// This includes situations where the method handler is misspelled or has the wrong
// signature. For this reason, this function should be used with great care and
// is not recommended to be used by most users.
func NewFlightServiceService(s interface{}) *FlightServiceService {
ns := &FlightServiceService{}
if h, ok := s.(interface {
Handshake(FlightService_HandshakeServer) error
}); ok {
ns.Handshake = h.Handshake
}
if h, ok := s.(interface {
ListFlights(*Criteria, FlightService_ListFlightsServer) error
}); ok {
ns.ListFlights = h.ListFlights
}
if h, ok := s.(interface {
GetFlightInfo(context.Context, *FlightDescriptor) (*FlightInfo, error)
}); ok {
ns.GetFlightInfo = h.GetFlightInfo
}
if h, ok := s.(interface {
GetSchema(context.Context, *FlightDescriptor) (*SchemaResult, error)
}); ok {
ns.GetSchema = h.GetSchema
}
if h, ok := s.(interface {
DoGet(*Ticket, FlightService_DoGetServer) error
}); ok {
ns.DoGet = h.DoGet
}
if h, ok := s.(interface {
DoPut(FlightService_DoPutServer) error
}); ok {
ns.DoPut = h.DoPut
}
if h, ok := s.(interface {
DoExchange(FlightService_DoExchangeServer) error
}); ok {
ns.DoExchange = h.DoExchange
}
if h, ok := s.(interface {
DoAction(*Action, FlightService_DoActionServer) error
}); ok {
ns.DoAction = h.DoAction
}
if h, ok := s.(interface {
ListActions(*Empty, FlightService_ListActionsServer) error
}); ok {
ns.ListActions = h.ListActions
}
return ns
}
// UnstableFlightServiceService is the service API for FlightService service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended.
type UnstableFlightServiceService interface {
//
// Handshake between client and server. Depending on the server, the
// handshake may be required to determine the token that should be used for
// future operations. Both request and response are streams to allow multiple
// round-trips depending on auth mechanism.
Handshake(FlightService_HandshakeServer) error
//
// Get a list of available streams given a particular criteria. Most flight
// services will expose one or more streams that are readily available for
// retrieval. This api allows listing the streams available for
// consumption. A user can also provide a criteria. The criteria can limit
// the subset of streams that can be listed via this interface. Each flight
// service allows its own definition of how to consume criteria.
ListFlights(*Criteria, FlightService_ListFlightsServer) error
//
// For a given FlightDescriptor, get information about how the flight can be
// consumed. This is a useful interface if the consumer of the interface
// already can identify the specific flight to consume. This interface can
// also allow a consumer to generate a flight stream through a specified
// descriptor. For example, a flight descriptor might be something that
// includes a SQL statement or a Pickled Python operation that will be
// executed. In those cases, the descriptor will not be previously available
// within the list of available streams provided by ListFlights but will be
// available for consumption for the duration defined by the specific flight
// service.
GetFlightInfo(context.Context, *FlightDescriptor) (*FlightInfo, error)
//
// For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
// This is used when a consumer needs the Schema of flight stream. Similar to
// GetFlightInfo this interface may generate a new flight that was not previously
// available in ListFlights.
GetSchema(context.Context, *FlightDescriptor) (*SchemaResult, error)
//
// Retrieve a single stream associated with a particular descriptor
// associated with the referenced ticket. A Flight can be composed of one or
// more streams where each stream can be retrieved using a separate opaque
// ticket that the flight service uses for managing a collection of streams.
DoGet(*Ticket, FlightService_DoGetServer) error
//
// Push a stream to the flight service associated with a particular
// flight stream. This allows a client of a flight service to upload a stream
// of data. Depending on the particular flight service, a client consumer
// could be allowed to upload a single stream per descriptor or an unlimited
// number. In the latter, the service might implement a 'seal' action that
// can be applied to a descriptor once all streams are uploaded.
DoPut(FlightService_DoPutServer) error
//
// Open a bidirectional data channel for a given descriptor. This
// allows clients to send and receive arbitrary Arrow data and
// application-specific metadata in a single logical stream. In
// contrast to DoGet/DoPut, this is more suited for clients
// offloading computation (rather than storage) to a Flight service.
DoExchange(FlightService_DoExchangeServer) error
//
// Flight services can support an arbitrary number of simple actions in
// addition to the possible ListFlights, GetFlightInfo, DoGet, DoPut
// operations that are potentially available. DoAction allows a flight client
// to do a specific action against a flight service. An action includes
// opaque request and response objects that are specific to the type action
// being undertaken.
DoAction(*Action, FlightService_DoActionServer) error
//
// A flight service exposes all of the available action types that it has
// along with descriptions. This allows different flight consumers to
// understand the capabilities of the flight service.
ListActions(*Empty, FlightService_ListActionsServer) error
}
|
{
"content_hash": "559cb7b64795892c15d136e3c2963225",
"timestamp": "",
"source": "github",
"line_count": 875,
"max_line_length": 173,
"avg_line_length": 35.44228571428572,
"alnum_prop": 0.7488391590352121,
"repo_name": "xhochy/arrow",
"id": "c2b98d5613e24a63b8dbe7d4358f983b31886b21",
"size": "31067",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "go/arrow/flight/Flight_grpc.pb.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "73655"
},
{
"name": "Awk",
"bytes": "3709"
},
{
"name": "Batchfile",
"bytes": "24676"
},
{
"name": "C",
"bytes": "881567"
},
{
"name": "C#",
"bytes": "699719"
},
{
"name": "C++",
"bytes": "14541996"
},
{
"name": "CMake",
"bytes": "560347"
},
{
"name": "Dockerfile",
"bytes": "100165"
},
{
"name": "Emacs Lisp",
"bytes": "1916"
},
{
"name": "FreeMarker",
"bytes": "2244"
},
{
"name": "Go",
"bytes": "848212"
},
{
"name": "HTML",
"bytes": "6152"
},
{
"name": "Java",
"bytes": "4713332"
},
{
"name": "JavaScript",
"bytes": "102300"
},
{
"name": "Julia",
"bytes": "235105"
},
{
"name": "Lua",
"bytes": "8771"
},
{
"name": "M4",
"bytes": "11095"
},
{
"name": "MATLAB",
"bytes": "36600"
},
{
"name": "Makefile",
"bytes": "57687"
},
{
"name": "Meson",
"bytes": "48356"
},
{
"name": "Objective-C",
"bytes": "17680"
},
{
"name": "Objective-C++",
"bytes": "12128"
},
{
"name": "PLpgSQL",
"bytes": "56995"
},
{
"name": "Perl",
"bytes": "3799"
},
{
"name": "Python",
"bytes": "3135304"
},
{
"name": "R",
"bytes": "533584"
},
{
"name": "Ruby",
"bytes": "1084485"
},
{
"name": "Rust",
"bytes": "3969176"
},
{
"name": "Shell",
"bytes": "380070"
},
{
"name": "Thrift",
"bytes": "142033"
},
{
"name": "TypeScript",
"bytes": "1157087"
}
],
"symlink_target": ""
}
|
package org.makersoft.model;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
/**
* entity for test.
*/
public class Dept implements Serializable {
private static final long serialVersionUID = -1665006573884858700L;
private Long id;
private String name;
private List<User> users = Collections.emptyList();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Dept [id=" + id + ", name=" + name + ", users=[");
for(User user : users){
sb.append(user);
sb.append(",");
}
sb.append("]]");
return sb.toString();
}
}
|
{
"content_hash": "b2abd2bf618bc2398fe2a9bc19aad99e",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 68,
"avg_line_length": 17.120689655172413,
"alnum_prop": 0.6193353474320241,
"repo_name": "makersoft/makereap",
"id": "137e4c6dc99b6184cd8b03db47d33b6dfe133f8f",
"size": "1186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/extension/src/test/java/org/makersoft/model/Dept.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "543760"
},
{
"name": "JavaScript",
"bytes": "15634"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../card-stack/card-stack.css">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script src="http://localhost:8080/bundle.js"></script>
<script src="./card-state.js"></script>
</head>
<body>
<div id="viewport">
<ul class="stack">
<li class="clubs">♣</li>
</ul>
</div>
<div id="source">
<p><button onclick="card.throwOut(parseInt(document.getElementById('throw-out-x').value, 10), parseInt(document.getElementById('throw-out-y').value, 10))">throwOut</button> (x: <input id="throw-out-x" type="text" value="600">, y: <input id="throw-out-y" type="text" value="-100">) Throws a card out of the stack in the direction away from the original offset.</p>
<p><button onclick="card.throwIn(parseInt(document.getElementById('throw-in-x').value, 10), parseInt(document.getElementById('throw-in-y').value, 10))">throwIn</button> (x: <input id="throw-in-x" type="text" value="600">, y: <input id="throw-in-y" type="text" value="-100">) Throws a card into the stack from an arbitrary position.</p>
<p>Open the <a href="https://developer.chrome.com/devtools/docs/console">Console</a> to view the associated events.</p>
<p>Demonstration of <a href="https://github.com/gajus/swing">https://github.com/gajus/swing</a> implementation.</p>
</div>
</body>
</html>
|
{
"content_hash": "c4631ce71141fbc36983ea5a14ba9a2e",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 371,
"avg_line_length": 54.92307692307692,
"alnum_prop": 0.6491596638655462,
"repo_name": "mattblang/swing",
"id": "96c91f3279176702a16f42898713c45d53a687e7",
"size": "1430",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/card-state/index.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "24906"
}
],
"symlink_target": ""
}
|
package rest
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
"github.com/julienschmidt/httprouter"
"github.com/intelsdi-x/snap/core"
"github.com/intelsdi-x/snap/core/cdata"
"github.com/intelsdi-x/snap/core/serror"
"github.com/intelsdi-x/snap/mgmt/rest/rbody"
"github.com/intelsdi-x/snap/mgmt/tribe/agreement"
cschedule "github.com/intelsdi-x/snap/pkg/schedule"
"github.com/intelsdi-x/snap/scheduler/wmap"
)
const (
APIVersion = 1
)
// default configuration values
const (
defaultEnable bool = true
defaultPort int = 8181
defaultAddress string = ""
defaultHTTPS bool = false
defaultRestCertificate string = ""
defaultRestKey string = ""
defaultAuth bool = false
defaultAuthPassword string = ""
)
var (
ErrBadCert = errors.New("Invalid certificate given")
restLogger = log.WithField("_module", "_mgmt-rest")
protocolPrefix = "http"
)
// holds the configuration passed in through the SNAP config file
// Note: if this struct is modified, then the switch statement in the
// UnmarshalJSON method in this same file needs to be modified to
// match the field mapping that is defined here
type Config struct {
Enable bool `json:"enable"yaml:"enable"`
Port int `json:"port"yaml:"port"`
Address string `json:"addr"yaml:"addr"`
HTTPS bool `json:"https"yaml:"https"`
RestCertificate string `json:"rest_certificate"yaml:"rest_certificate"`
RestKey string `json:"rest_key"yaml:"rest_key"`
RestAuth bool `json:"rest_auth"yaml:"rest_auth"`
RestAuthPassword string `json:"rest_auth_password"yaml:"rest_auth_password"`
}
const (
CONFIG_CONSTRAINTS = `
"restapi" : {
"type": ["object", "null"],
"properties" : {
"enable": {
"type": "boolean"
},
"https" : {
"type": "boolean"
},
"rest_auth": {
"type": "boolean"
},
"rest_auth_password": {
"type": "string"
},
"rest_certificate": {
"type": "string"
},
"rest_key" : {
"type": "string"
},
"port" : {
"type": "integer",
"minimum": 1,
"maximum": 65535
},
"addr" : {
"type": "string"
}
},
"additionalProperties": false
}
`
)
type managesMetrics interface {
MetricCatalog() ([]core.CatalogedMetric, error)
FetchMetrics(core.Namespace, int) ([]core.CatalogedMetric, error)
GetMetricVersions(core.Namespace) ([]core.CatalogedMetric, error)
GetMetric(core.Namespace, int) (core.CatalogedMetric, error)
Load(*core.RequestedPlugin) (core.CatalogedPlugin, serror.SnapError)
Unload(core.Plugin) (core.CatalogedPlugin, serror.SnapError)
PluginCatalog() core.PluginCatalog
AvailablePlugins() []core.AvailablePlugin
GetAutodiscoverPaths() []string
}
type managesTasks interface {
CreateTask(cschedule.Schedule, *wmap.WorkflowMap, bool, ...core.TaskOption) (core.Task, core.TaskErrors)
GetTasks() map[string]core.Task
GetTask(string) (core.Task, error)
StartTask(string) []serror.SnapError
StopTask(string) []serror.SnapError
RemoveTask(string) error
WatchTask(string, core.TaskWatcherHandler) (core.TaskWatcherCloser, error)
EnableTask(string) (core.Task, error)
}
type managesTribe interface {
GetAgreement(name string) (*agreement.Agreement, serror.SnapError)
GetAgreements() map[string]*agreement.Agreement
AddAgreement(name string) serror.SnapError
RemoveAgreement(name string) serror.SnapError
JoinAgreement(agreementName, memberName string) serror.SnapError
LeaveAgreement(agreementName, memberName string) serror.SnapError
GetMembers() []string
GetMember(name string) *agreement.Member
}
type managesConfig interface {
GetPluginConfigDataNode(core.PluginType, string, int) cdata.ConfigDataNode
GetPluginConfigDataNodeAll() cdata.ConfigDataNode
MergePluginConfigDataNode(pluginType core.PluginType, name string, ver int, cdn *cdata.ConfigDataNode) cdata.ConfigDataNode
MergePluginConfigDataNodeAll(cdn *cdata.ConfigDataNode) cdata.ConfigDataNode
DeletePluginConfigDataNodeField(pluginType core.PluginType, name string, ver int, fields ...string) cdata.ConfigDataNode
DeletePluginConfigDataNodeFieldAll(fields ...string) cdata.ConfigDataNode
}
type Server struct {
mm managesMetrics
mt managesTasks
tr managesTribe
mc managesConfig
n *negroni.Negroni
r *httprouter.Router
tls *tls
auth bool
authpwd string
addrString string
addr net.Addr
wg sync.WaitGroup
killChan chan struct{}
err chan error
}
// New creates a REST API server with a given config
func New(cfg *Config) (*Server, error) {
// pull a few parameters from the configuration passed in by snapd
https := cfg.HTTPS
cpath := cfg.RestCertificate
kpath := cfg.RestKey
s := &Server{
err: make(chan error),
killChan: make(chan struct{}),
}
if https {
var err error
s.tls, err = newtls(cpath, kpath)
if err != nil {
return nil, err
}
protocolPrefix = "https"
}
restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", https))
s.n = negroni.New(
NewLogger(),
negroni.NewRecovery(),
negroni.HandlerFunc(s.authMiddleware),
)
s.r = httprouter.New()
// Use negroni to handle routes
s.n.UseHandler(s.r)
return s, nil
}
// GetDefaultConfig gets the default snapd configuration
func GetDefaultConfig() *Config {
return &Config{
Enable: defaultEnable,
Port: defaultPort,
Address: defaultAddress,
HTTPS: defaultHTTPS,
RestCertificate: defaultRestCertificate,
RestKey: defaultRestKey,
RestAuth: defaultAuth,
RestAuthPassword: defaultAuthPassword,
}
}
// UnmarshalJSON unmarshals valid json into a Config. An example Config can be found
// at github.com/intelsdi-x/snap/blob/master/examples/configs/snap-config-sample.json
func (c *Config) UnmarshalJSON(data []byte) error {
// construct a map of strings to json.RawMessages (to defer the parsing of individual
// fields from the unmarshalled interface until later) and unmarshal the input
// byte array into that map
t := make(map[string]json.RawMessage)
if err := json.Unmarshal(data, &t); err != nil {
return err
}
// loop through the individual map elements, parse each in turn, and set
// the appropriate field in this configuration
for k, v := range t {
switch k {
case "enable":
if err := json.Unmarshal(v, &(c.Enable)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::enable')", err)
}
case "port":
if err := json.Unmarshal(v, &(c.Port)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::port')", err)
}
case "addr":
if err := json.Unmarshal(v, &(c.Address)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::addr')", err)
}
case "https":
if err := json.Unmarshal(v, &(c.HTTPS)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::https')", err)
}
case "rest_certificate":
if err := json.Unmarshal(v, &(c.RestCertificate)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::rest_certificate')", err)
}
case "rest_key":
if err := json.Unmarshal(v, &(c.RestKey)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::rest_key')", err)
}
case "rest_auth":
if err := json.Unmarshal(v, &(c.RestAuth)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::rest_auth')", err)
}
case "rest_auth_password":
if err := json.Unmarshal(v, &(c.RestAuthPassword)); err != nil {
return fmt.Errorf("%v (while parsing 'restapi::rest_auth_password')", err)
}
default:
return fmt.Errorf("Unrecognized key '%v' in global config file while parsing 'restapi'", k)
}
}
return nil
}
// SetAPIAuth sets API authentication to enabled or disabled
func (s *Server) SetAPIAuth(auth bool) {
s.auth = auth
}
// SetAPIAuthPwd sets the API authentication password from snapd
func (s *Server) SetAPIAuthPwd(pwd string) {
s.authpwd = pwd
}
// Auth Middleware for REST API
func (s *Server) authMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
defer r.Body.Close()
if s.auth {
_, password, ok := r.BasicAuth()
// If we have valid password or going to tribe/agreements endpoint
// go to next. tribe/agreements endpoint used for populating
// snapctl help page when tribe mode is turned on.
if ok && password == s.authpwd {
next(rw, r)
} else {
http.Error(rw, "Not Authorized", 401)
}
} else {
next(rw, r)
}
}
func (s *Server) Name() string {
return "REST"
}
func (s *Server) SetAddress(addrString string, dfltPort int) {
restLogger.Info(fmt.Sprintf("Setting address to: [%v] Default port: %v", addrString, dfltPort))
// In the future, we could extend this to support multiple comma separated IP[:port] values
if strings.Index(addrString, ",") != -1 {
restLogger.Fatal("Invalid address")
}
// If no port is specified, use default port
if strings.Index(addrString, ":") != -1 {
s.addrString = addrString
} else {
s.addrString = fmt.Sprintf("%s:%d", addrString, dfltPort)
}
restLogger.Info(fmt.Sprintf("Address used for binding: [%v]", s.addrString))
}
func (s *Server) Start() error {
s.addRoutes()
s.run(s.addrString)
restLogger.WithFields(log.Fields{
"_block": "start",
}).Info("REST started")
return nil
}
func (s *Server) Stop() {
close(s.killChan)
s.wg.Wait()
}
func (s *Server) Err() <-chan error {
return s.err
}
func (s *Server) Port() int {
return s.addr.(*net.TCPAddr).Port
}
func (s *Server) run(addrString string) {
restLogger.Info("Starting REST API on ", addrString)
if s.tls != nil {
go s.serveTLS(addrString)
} else {
ln, err := net.Listen("tcp", addrString)
if err != nil {
s.err <- err
}
s.addr = ln.Addr()
go s.serve(ln)
}
}
func (s *Server) serveTLS(addrString string) {
err := http.ListenAndServeTLS(addrString, s.tls.cert, s.tls.key, s.n)
if err != nil {
restLogger.Error(err)
s.err <- err
}
}
func (s *Server) serve(ln net.Listener) {
err := http.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)}, s.n)
if err != nil {
restLogger.Error(err)
s.err <- err
}
}
// Monkey patch ListenAndServe and TCP alive code from https://golang.org/src/net/http/server.go
// The built in ListenAndServe and ListenAndServeTLS include TCP keepalive
// At this point the Go team is not wanting to provide separate listen and serve methods
// that also provide an exported TCP keepalive per: https://github.com/golang/go/issues/12731
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
func (s *Server) BindMetricManager(m managesMetrics) {
s.mm = m
}
func (s *Server) BindTaskManager(t managesTasks) {
s.mt = t
}
func (s *Server) BindTribeManager(t managesTribe) {
s.tr = t
}
func (s *Server) BindConfigManager(c managesConfig) {
s.mc = c
}
func (s *Server) addRoutes() {
// plugin routes
s.r.GET("/v1/plugins", s.getPlugins)
s.r.GET("/v1/plugins/:type", s.getPlugins)
s.r.GET("/v1/plugins/:type/:name", s.getPlugins)
s.r.GET("/v1/plugins/:type/:name/:version", s.getPlugin)
s.r.POST("/v1/plugins", s.loadPlugin)
s.r.DELETE("/v1/plugins/:type/:name/:version", s.unloadPlugin)
s.r.GET("/v1/plugins/:type/:name/:version/config", s.getPluginConfigItem)
s.r.PUT("/v1/plugins/:type/:name/:version/config", s.setPluginConfigItem)
s.r.DELETE("/v1/plugins/:type/:name/:version/config", s.deletePluginConfigItem)
// metric routes
s.r.GET("/v1/metrics", s.getMetrics)
s.r.GET("/v1/metrics/*namespace", s.getMetricsFromTree)
// task routes
s.r.GET("/v1/tasks", s.getTasks)
s.r.GET("/v1/tasks/:id", s.getTask)
s.r.GET("/v1/tasks/:id/watch", s.watchTask)
s.r.POST("/v1/tasks", s.addTask)
s.r.PUT("/v1/tasks/:id/start", s.startTask)
s.r.PUT("/v1/tasks/:id/stop", s.stopTask)
s.r.DELETE("/v1/tasks/:id", s.removeTask)
s.r.PUT("/v1/tasks/:id/enable", s.enableTask)
// tribe routes
if s.tr != nil {
s.r.GET("/v1/tribe/agreements", s.getAgreements)
s.r.POST("/v1/tribe/agreements", s.addAgreement)
s.r.GET("/v1/tribe/agreements/:name", s.getAgreement)
s.r.DELETE("/v1/tribe/agreements/:name", s.deleteAgreement)
s.r.PUT("/v1/tribe/agreements/:name/join", s.joinAgreement)
s.r.DELETE("/v1/tribe/agreements/:name/leave", s.leaveAgreement)
s.r.GET("/v1/tribe/members", s.getMembers)
s.r.GET("/v1/tribe/member/:name", s.getMember)
}
}
func respond(code int, b rbody.Body, w http.ResponseWriter) {
resp := &rbody.APIResponse{
Meta: &rbody.APIResponseMeta{
Code: code,
Message: b.ResponseBodyMessage(),
Type: b.ResponseBodyType(),
Version: APIVersion,
},
Body: b,
}
if !w.(negroni.ResponseWriter).Written() {
w.WriteHeader(code)
}
j, err := json.MarshalIndent(resp, "", " ")
if err != nil {
panic(err)
}
fmt.Fprint(w, string(j))
}
func marshalBody(in interface{}, body io.ReadCloser) (int, error) {
b, err := ioutil.ReadAll(body)
if err != nil {
return 500, err
}
err = json.Unmarshal(b, in)
if err != nil {
return 400, err
}
return 0, nil
}
func parseNamespace(ns string) []string {
if strings.Index(ns, "/") == 0 {
ns = ns[1:]
}
if ns[len(ns)-1] == '/' {
ns = ns[:len(ns)-1]
}
return strings.Split(ns, "/")
}
|
{
"content_hash": "d5a228bbf0ccbbe6e471b67e59d2fcb9",
"timestamp": "",
"source": "github",
"line_count": 476,
"max_line_length": 124,
"avg_line_length": 28.52310924369748,
"alnum_prop": 0.674302128599838,
"repo_name": "mkleina/snap",
"id": "dc155f5767292338c9bf1ea61642d078b1456720",
"size": "14189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mgmt/rest/server.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "1314869"
},
{
"name": "Makefile",
"bytes": "1472"
},
{
"name": "Protocol Buffer",
"bytes": "4900"
},
{
"name": "Shell",
"bytes": "12151"
}
],
"symlink_target": ""
}
|
/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx_hal.h"
/** @addtogroup STM32L1xx_HAL_Driver
* @{
*/
#ifdef HAL_IWDG_MODULE_ENABLED
/** @addtogroup IWDG
* @brief IWDG HAL module driver.
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup IWDG_Private_Defines IWDG Private Defines
* @{
*/
/* MBED */
#define HAL_IWDG_DEFAULT_TIMEOUT 96u
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup IWDG_Exported_Functions
* @{
*/
/** @addtogroup IWDG_Exported_Functions_Group1
* @brief Initialization and Start functions.
*
@verbatim
===============================================================================
##### Initialization and Start functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize the IWDG according to the specified parameters in the
IWDG_InitTypeDef of associated handle.
(+) Once initialization is performed in HAL_IWDG_Init function, Watchdog
is reloaded in order to exit function with correct time base.
@endverbatim
* @{
*/
/**
* @brief Initialize the IWDG according to the specified parameters in the
* IWDG_InitTypeDef and start watchdog. Before exiting function,
* watchdog is refreshed in order to have correct time base.
* @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
* the configuration information for the specified IWDG module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
{
uint32_t tickstart;
/* Check the IWDG handle allocation */
if(hiwdg == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance));
assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler));
assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload));
/* Enable IWDG. LSI is turned on automaticaly */
__HAL_IWDG_START(hiwdg);
/* Enable write access to IWDG_PR, IWDG_RLR registers by writing
0x5555 in KR */
IWDG_ENABLE_WRITE_ACCESS(hiwdg);
/* Write to IWDG registers the Prescaler & Reload values to work with */
hiwdg->Instance->PR = hiwdg->Init.Prescaler;
hiwdg->Instance->RLR = hiwdg->Init.Reload;
/* Check pending flag, if previous update not done, return timeout */
tickstart = HAL_GetTick();
/* Wait for register to be updated */
while(hiwdg->Instance->SR != RESET)
{
if((HAL_GetTick() - tickstart ) > HAL_IWDG_DEFAULT_TIMEOUT)
{
return HAL_TIMEOUT;
}
}
/* Reload IWDG counter with value defined in the reload register */
__HAL_IWDG_RELOAD_COUNTER(hiwdg);
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/** @addtogroup IWDG_Exported_Functions_Group2
* @brief IO operation functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Refresh the IWDG.
@endverbatim
* @{
*/
/**
* @brief Refresh the IWDG.
* @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
* the configuration information for the specified IWDG module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg)
{
/* Reload IWDG counter with value defined in the reload register */
__HAL_IWDG_RELOAD_COUNTER(hiwdg);
/* Return function status */
return HAL_OK;
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_IWDG_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
{
"content_hash": "5d0c3ce37a4783a7f56413edf21263de",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 80,
"avg_line_length": 27.0188679245283,
"alnum_prop": 0.5325884543761639,
"repo_name": "andcor02/mbed-os",
"id": "c057cff97c6325299dff6d22a64ac129dc4a638c",
"size": "9682",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "targets/TARGET_STM/TARGET_STM32L1/device/stm32l1xx_hal_iwdg.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "6601399"
},
{
"name": "Batchfile",
"bytes": "22"
},
{
"name": "C",
"bytes": "295194591"
},
{
"name": "C++",
"bytes": "9038670"
},
{
"name": "CMake",
"bytes": "5285"
},
{
"name": "HTML",
"bytes": "2063156"
},
{
"name": "Makefile",
"bytes": "103497"
},
{
"name": "Objective-C",
"bytes": "460244"
},
{
"name": "Perl",
"bytes": "2589"
},
{
"name": "Python",
"bytes": "38809"
},
{
"name": "Shell",
"bytes": "16862"
},
{
"name": "XSLT",
"bytes": "5596"
}
],
"symlink_target": ""
}
|
from lib.query import Query
class VoteModel(Query):
def __init__(self, db):
self.db = db
self.table_name = "vote"
super(VoteModel, self).__init__()
def add_new_vote(self, vote_info):
return self.data(vote_info).add()
def get_vote_by_topic_id_and_trigger_user_id(self, topic_id, trigger_user_id):
where = "involved_topic_id = %s AND trigger_user_id = %s" % (topic_id, trigger_user_id)
return self.where(where).find()
|
{
"content_hash": "682a4d4d7ee715319493ae8d4062e228",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 95,
"avg_line_length": 32,
"alnum_prop": 0.6104166666666667,
"repo_name": "bukun/ogcc",
"id": "65ee40526c55312d42f43d4ca604f1ac638eb610",
"size": "616",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "model/vote.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "426606"
},
{
"name": "HTML",
"bytes": "96462"
},
{
"name": "JavaScript",
"bytes": "443220"
},
{
"name": "Python",
"bytes": "127487"
},
{
"name": "Ruby",
"bytes": "853"
},
{
"name": "Shell",
"bytes": "283"
}
],
"symlink_target": ""
}
|
package org.wso2.siddhi.test.standard.table;
import junit.framework.Assert;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;
public class UpdateFromTableTestCase {
static final Logger log = Logger.getLogger(UpdateFromTableTestCase.class);
private int count;
private boolean eventArrived;
@Before
public void init() {
count = 0;
eventArrived = false;
}
@Test
public void testQuery1() throws InterruptedException {
log.info("UpdateFromTableTestCase test1");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) ");
siddhiManager.defineStream("define stream cseUpdateEventStream (symbol string, price float, volume long) ");
siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) ");
String queryReference = siddhiManager.addQuery("from cseEventStream " +
"insert into cseEventTable;");
siddhiManager.addQuery("from cseUpdateEventStream " +
"update cseEventTable;");
InputHandler cseEventStream = siddhiManager.getInputHandler("cseEventStream");
cseEventStream.send(new Object[]{"WSO2", 55.6f, 100l});
cseEventStream.send(new Object[]{"IBM", 75.6f, 100l});
cseEventStream.send(new Object[]{"WSO2", 57.6f, 100l});
InputHandler cseUpdateEventStream = siddhiManager.getInputHandler("cseUpdateEventStream");
cseUpdateEventStream.send(new Object[]{"IBM", 75.6f, 100l});
Thread.sleep(500);
siddhiManager.shutdown();
}
@Test
public void testQuery2() throws InterruptedException {
log.info("UpdateFromTableTestCase test2");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) ");
siddhiManager.defineStream("define stream cseUpdateEventStream (symbol string, price float, volume long) ");
siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) ");
String queryReference = siddhiManager.addQuery("from cseEventStream " +
"insert into cseEventTable;");
siddhiManager.addQuery("from cseUpdateEventStream " +
"update cseEventTable" +
" on cseEventTable.symbol=='IBM';");
InputHandler cseEventStream = siddhiManager.getInputHandler("cseEventStream");
cseEventStream.send(new Object[]{"WSO2", 55.6f, 100l});
cseEventStream.send(new Object[]{"IBM", 75.6f, 100l});
cseEventStream.send(new Object[]{"WSO2", 57.6f, 100l});
InputHandler cseUpdateEventStream = siddhiManager.getInputHandler("cseUpdateEventStream");
cseUpdateEventStream.send(new Object[]{"GOOG", 10f, 100l});
Thread.sleep(500);
siddhiManager.shutdown();
}
@Test
public void testQuery3() throws InterruptedException {
log.info("UpdateFromTableTestCase test1");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) ");
siddhiManager.defineStream("define stream cseUpdateEventStream (symbol string, price float, volume long) ");
siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) ");
String queryReference = siddhiManager.addQuery("from cseEventStream " +
"insert into cseEventTable;");
siddhiManager.addQuery("from cseUpdateEventStream " +
"update cseEventTable" +
" on cseEventTable.symbol==symbol;");
InputHandler cseEventStream = siddhiManager.getInputHandler("cseEventStream");
cseEventStream.send(new Object[]{"WSO2", 55.6f, 100l});
cseEventStream.send(new Object[]{"IBM", 75.6f, 100l});
cseEventStream.send(new Object[]{"WSO2", 57.6f, 100l});
InputHandler cseUpdateEventStream = siddhiManager.getInputHandler("cseUpdateEventStream");
cseUpdateEventStream.send(new Object[]{"WSO2", 10f, 200l});
Thread.sleep(500);
siddhiManager.shutdown();
}
@Test
public void testQuery4() throws InterruptedException {
log.info("InsertIntoTableTestCase test4");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) ");
siddhiManager.defineStream("define stream cseCheckEventStream (symbol string, volume long) ");
siddhiManager.defineStream("define stream cseUpdateEventStream (symbol string, price float, volume long) ");
siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) ");
siddhiManager.addQuery("from cseEventStream " +
"insert into cseEventTable;");
siddhiManager.addQuery("from cseUpdateEventStream " +
"update cseEventTable" +
" on cseEventTable.symbol==symbol;");
String queryReference = siddhiManager.addQuery("from cseCheckEventStream[(symbol==cseEventTable.symbol and volume==cseEventTable.volume ) in cseEventTable] " +
"insert into outStream;");
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
count++;
eventArrived = true;
}
});
InputHandler cseEventStream = siddhiManager.getInputHandler("cseEventStream");
InputHandler cseEventCheckStream = siddhiManager.getInputHandler("cseCheckEventStream");
InputHandler cseUpdateEventStream = siddhiManager.getInputHandler("cseUpdateEventStream");
cseEventStream.send(new Object[]{"WSO2", 55.6f, 100l});
cseEventStream.send(new Object[]{"IBM", 55.6f, 100l});
cseEventCheckStream.send(new Object[]{"IBM",100l});
cseEventCheckStream.send(new Object[]{"WSO2",100l});
cseUpdateEventStream.send(new Object[]{"IBM", 77.6f, 200l});
cseEventCheckStream.send(new Object[]{"IBM",100l});
cseEventCheckStream.send(new Object[]{"WSO2",100l});
Thread.sleep(500);
Assert.assertEquals(3, count);
Assert.assertEquals("Event arrived", true, eventArrived);
siddhiManager.shutdown();
}
@Test
public void testQuery5() throws InterruptedException {
log.info("InsertIntoTableTestCase test5");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) ");
siddhiManager.defineStream("define stream cseCheckEventStream (symbol string, volume long) ");
siddhiManager.defineStream("define stream cseUpdateEventStream (comp string, vol long) ");
siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) ");
siddhiManager.addQuery("from cseEventStream " +
"insert into cseEventTable;");
siddhiManager.addQuery("from cseUpdateEventStream " +
"select comp as symbol, vol as volume " +
"update cseEventTable" +
" on cseEventTable.symbol==symbol;");
String queryReference = siddhiManager.addQuery("from cseCheckEventStream[(symbol==cseEventTable.symbol and volume==cseEventTable.volume ) in cseEventTable] " +
"insert into outStream;");
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
count++;
eventArrived = true;
}
});
InputHandler cseEventStream = siddhiManager.getInputHandler("cseEventStream");
InputHandler cseEventCheckStream = siddhiManager.getInputHandler("cseCheckEventStream");
InputHandler cseUpdateEventStream = siddhiManager.getInputHandler("cseUpdateEventStream");
cseEventStream.send(new Object[]{"WSO2", 55.6f, 100l});
cseEventStream.send(new Object[]{"IBM", 155.6f, 100l});
cseEventCheckStream.send(new Object[]{"IBM",100l});
cseEventCheckStream.send(new Object[]{"WSO2",100l});
cseUpdateEventStream.send(new Object[]{"IBM", 200l});
cseEventCheckStream.send(new Object[]{"IBM",100l});
cseEventCheckStream.send(new Object[]{"WSO2",100l});
Thread.sleep(500);
Assert.assertEquals(3, count);
Assert.assertEquals("Event arrived", true, eventArrived);
siddhiManager.shutdown();
}
@Test
public void testQuery6() throws InterruptedException {
log.info("InsertIntoTableTestCase test6");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) ");
siddhiManager.defineStream("define stream cseCheckEventStream (symbol string, volume long, price float) ");
siddhiManager.defineStream("define stream cseUpdateEventStream (comp string, vol long) ");
siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) ");
siddhiManager.addQuery("from cseEventStream " +
"insert into cseEventTable;");
siddhiManager.addQuery("from cseUpdateEventStream " +
"select comp as symbol, vol as volume " +
"update cseEventTable" +
" on cseEventTable.symbol==symbol;");
String queryReference = siddhiManager.addQuery("from cseCheckEventStream[(symbol==cseEventTable.symbol and volume==cseEventTable.volume and price==cseEventTable.price ) in cseEventTable] " +
"insert into outStream;");
siddhiManager.addCallback(queryReference, new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
count++;
eventArrived = true;
}
});
InputHandler cseEventStream = siddhiManager.getInputHandler("cseEventStream");
InputHandler cseEventCheckStream = siddhiManager.getInputHandler("cseCheckEventStream");
InputHandler cseUpdateEventStream = siddhiManager.getInputHandler("cseUpdateEventStream");
cseEventStream.send(new Object[]{"WSO2", 55.6f, 100l});
cseEventStream.send(new Object[]{"IBM", 155.6f, 100l});
cseEventCheckStream.send(new Object[]{"IBM",100l,155.6f});
cseEventCheckStream.send(new Object[]{"WSO2",100l,155.6f});
cseUpdateEventStream.send(new Object[]{"IBM", 200l});
cseEventCheckStream.send(new Object[]{"IBM",200l,155.6f});
cseEventCheckStream.send(new Object[]{"WSO2",100l,155.6f});
Thread.sleep(500);
Assert.assertEquals(2, count);
Assert.assertEquals("Event arrived", true, eventArrived);
siddhiManager.shutdown();
}
}
|
{
"content_hash": "d4e61723116f8f87a56eeb5c5ad05b19",
"timestamp": "",
"source": "github",
"line_count": 254,
"max_line_length": 198,
"avg_line_length": 48.09448818897638,
"alnum_prop": 0.6491486574983628,
"repo_name": "gayanlggd/siddhi",
"id": "c2e6ec03757852e4064f1d7fe5387430c50b9043",
"size": "12883",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "modules/siddhi-core/src/test/java/org/wso2/siddhi/test/standard/table/UpdateFromTableTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "8961"
},
{
"name": "CSS",
"bytes": "2652"
},
{
"name": "GAP",
"bytes": "42178"
},
{
"name": "Java",
"bytes": "2529721"
}
],
"symlink_target": ""
}
|
namespace Golem.Proxy.HAR
{
public class Log
{
public Entry[] Entries { get; set; }
public string Version { get; set; }
public Browser Browser { get; set; }
public Creator Creator { get; set; }
public Page[] Pages { get; set; }
public string Comment { get; set; }
}
}
|
{
"content_hash": "352d735f5c26906c3782cfc575899eae",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 44,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.5579268292682927,
"repo_name": "ProtoTest/ProtoTest.Golem",
"id": "bf3c0482723ef99623797d6e2d476e773e4bc7ae",
"size": "330",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ProtoTest.Golem/Proxy/HAR/Log.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "445069"
},
{
"name": "CSS",
"bytes": "13489"
},
{
"name": "HTML",
"bytes": "30291"
},
{
"name": "PowerShell",
"bytes": "1582"
}
],
"symlink_target": ""
}
|
//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This provides Objective-C code generation targeting the GNU runtime. The
// class in this file generates structures used by the GNU Objective-C runtime
// library. These structures are defined in objc/objc.h and objc/objc-api.h in
// the GNU runtime distribution.
//
//===----------------------------------------------------------------------===//
#include "CGObjCRuntime.h"
#include "CGCleanup.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtObjC.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Compiler.h"
#include <cstdarg>
using namespace clang;
using namespace CodeGen;
namespace {
/// Class that lazily initialises the runtime function. Avoids inserting the
/// types and the function declaration into a module if they're not used, and
/// avoids constructing the type more than once if it's used more than once.
class LazyRuntimeFunction {
CodeGenModule *CGM;
std::vector<llvm::Type*> ArgTys;
const char *FunctionName;
llvm::Constant *Function;
public:
/// Constructor leaves this class uninitialized, because it is intended to
/// be used as a field in another class and not all of the types that are
/// used as arguments will necessarily be available at construction time.
LazyRuntimeFunction()
: CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
/// Initialises the lazy function with the name, return type, and the types
/// of the arguments.
LLVM_END_WITH_NULL
void init(CodeGenModule *Mod, const char *name,
llvm::Type *RetTy, ...) {
CGM =Mod;
FunctionName = name;
Function = nullptr;
ArgTys.clear();
va_list Args;
va_start(Args, RetTy);
while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Push the return type on at the end so we can pop it off easily
ArgTys.push_back(RetTy);
}
/// Overloaded cast operator, allows the class to be implicitly cast to an
/// LLVM constant.
operator llvm::Constant*() {
if (!Function) {
if (!FunctionName) return nullptr;
// We put the return type on the end of the vector, so pop it back off
llvm::Type *RetTy = ArgTys.back();
ArgTys.pop_back();
llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
Function =
cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
// We won't need to use the types again, so we may as well clean up the
// vector now
ArgTys.resize(0);
}
return Function;
}
operator llvm::Function*() {
return cast<llvm::Function>((llvm::Constant*)*this);
}
};
/// GNU Objective-C runtime code generation. This class implements the parts of
/// Objective-C support that are specific to the GNU family of runtimes (GCC,
/// GNUstep and ObjFW).
class CGObjCGNU : public CGObjCRuntime {
protected:
/// The LLVM module into which output is inserted
llvm::Module &TheModule;
/// strut objc_super. Used for sending messages to super. This structure
/// contains the receiver (object) and the expected class.
llvm::StructType *ObjCSuperTy;
/// struct objc_super*. The type of the argument to the superclass message
/// lookup functions.
llvm::PointerType *PtrToObjCSuperTy;
/// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
/// SEL is included in a header somewhere, in which case it will be whatever
/// type is declared in that header, most likely {i8*, i8*}.
llvm::PointerType *SelectorTy;
/// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
/// places where it's used
llvm::IntegerType *Int8Ty;
/// Pointer to i8 - LLVM type of char*, for all of the places where the
/// runtime needs to deal with C strings.
llvm::PointerType *PtrToInt8Ty;
/// Instance Method Pointer type. This is a pointer to a function that takes,
/// at a minimum, an object and a selector, and is the generic type for
/// Objective-C methods. Due to differences between variadic / non-variadic
/// calling conventions, it must always be cast to the correct type before
/// actually being used.
llvm::PointerType *IMPTy;
/// Type of an untyped Objective-C object. Clang treats id as a built-in type
/// when compiling Objective-C code, so this may be an opaque pointer (i8*),
/// but if the runtime header declaring it is included then it may be a
/// pointer to a structure.
llvm::PointerType *IdTy;
/// Pointer to a pointer to an Objective-C object. Used in the new ABI
/// message lookup function and some GC-related functions.
llvm::PointerType *PtrToIdTy;
/// The clang type of id. Used when using the clang CGCall infrastructure to
/// call Objective-C methods.
CanQualType ASTIdTy;
/// LLVM type for C int type.
llvm::IntegerType *IntTy;
/// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
/// used in the code to document the difference between i8* meaning a pointer
/// to a C string and i8* meaning a pointer to some opaque type.
llvm::PointerType *PtrTy;
/// LLVM type for C long type. The runtime uses this in a lot of places where
/// it should be using intptr_t, but we can't fix this without breaking
/// compatibility with GCC...
llvm::IntegerType *LongTy;
/// LLVM type for C size_t. Used in various runtime data structures.
llvm::IntegerType *SizeTy;
/// LLVM type for C intptr_t.
llvm::IntegerType *IntPtrTy;
/// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
llvm::IntegerType *PtrDiffTy;
/// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
/// variables.
llvm::PointerType *PtrToIntTy;
/// LLVM type for Objective-C BOOL type.
llvm::Type *BoolTy;
/// 32-bit integer type, to save us needing to look it up every time it's used.
llvm::IntegerType *Int32Ty;
/// 64-bit integer type, to save us needing to look it up every time it's used.
llvm::IntegerType *Int64Ty;
/// Metadata kind used to tie method lookups to message sends. The GNUstep
/// runtime provides some LLVM passes that can use this to do things like
/// automatic IMP caching and speculative inlining.
unsigned msgSendMDKind;
/// Helper function that generates a constant string and returns a pointer to
/// the start of the string. The result of this function can be used anywhere
/// where the C code specifies const char*.
llvm::Constant *MakeConstantString(const std::string &Str,
const std::string &Name="") {
llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
}
/// Emits a linkonce_odr string, whose name is the prefix followed by the
/// string value. This allows the linker to combine the strings between
/// different modules. Used for EH typeinfo names, selector strings, and a
/// few other things.
llvm::Constant *ExportUniqueString(const std::string &Str,
const std::string prefix) {
std::string name = prefix + Str;
llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
if (!ConstStr) {
llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
}
return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
}
/// Generates a global structure, initialized by the elements in the vector.
/// The element types must match the types of the structure elements in the
/// first argument.
llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
ArrayRef<llvm::Constant *> V,
StringRef Name="",
llvm::GlobalValue::LinkageTypes linkage
=llvm::GlobalValue::InternalLinkage) {
llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
return new llvm::GlobalVariable(TheModule, Ty, false,
linkage, C, Name);
}
/// Generates a global array. The vector must contain the same number of
/// elements that the array type declares, of the type specified as the array
/// element type.
llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
ArrayRef<llvm::Constant *> V,
StringRef Name="",
llvm::GlobalValue::LinkageTypes linkage
=llvm::GlobalValue::InternalLinkage) {
llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
return new llvm::GlobalVariable(TheModule, Ty, false,
linkage, C, Name);
}
/// Generates a global array, inferring the array type from the specified
/// element type and the size of the initialiser.
llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
ArrayRef<llvm::Constant *> V,
StringRef Name="",
llvm::GlobalValue::LinkageTypes linkage
=llvm::GlobalValue::InternalLinkage) {
llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
return MakeGlobal(ArrayTy, V, Name, linkage);
}
/// Returns a property name and encoding string.
llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
const Decl *Container) {
const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
if ((R.getKind() == ObjCRuntime::GNUstep) &&
(R.getVersion() >= VersionTuple(1, 6))) {
std::string NameAndAttributes;
std::string TypeStr;
CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
NameAndAttributes += '\0';
NameAndAttributes += TypeStr.length() + 3;
NameAndAttributes += TypeStr;
NameAndAttributes += '\0';
NameAndAttributes += PD->getNameAsString();
return llvm::ConstantExpr::getGetElementPtr(
CGM.GetAddrOfConstantCString(NameAndAttributes), Zeros);
}
return MakeConstantString(PD->getNameAsString());
}
/// Push the property attributes into two structure fields.
void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
ObjCPropertyDecl *property, bool isSynthesized=true, bool
isDynamic=true) {
int attrs = property->getPropertyAttributes();
// For read-only properties, clear the copy and retain flags
if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
}
// The first flags field has the same attribute values as clang uses internally
Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
attrs >>= 8;
attrs <<= 2;
// For protocol properties, synthesized and dynamic have no meaning, so we
// reuse these flags to indicate that this is a protocol property (both set
// has no meaning, as a property can't be both synthesized and dynamic)
attrs |= isSynthesized ? (1<<0) : 0;
attrs |= isDynamic ? (1<<1) : 0;
// The second field is the next four fields left shifted by two, with the
// low bit set to indicate whether the field is synthesized or dynamic.
Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
// Two padding fields
Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
}
/// Ensures that the value has the required type, by inserting a bitcast if
/// required. This function lets us avoid inserting bitcasts that are
/// redundant.
llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
if (V->getType() == Ty) return V;
return B.CreateBitCast(V, Ty);
}
// Some zeros used for GEPs in lots of places.
llvm::Constant *Zeros[2];
/// Null pointer value. Mainly used as a terminator in various arrays.
llvm::Constant *NULLPtr;
/// LLVM context.
llvm::LLVMContext &VMContext;
private:
/// Placeholder for the class. Lots of things refer to the class before we've
/// actually emitted it. We use this alias as a placeholder, and then replace
/// it with a pointer to the class structure before finally emitting the
/// module.
llvm::GlobalAlias *ClassPtrAlias;
/// Placeholder for the metaclass. Lots of things refer to the class before
/// we've / actually emitted it. We use this alias as a placeholder, and then
/// replace / it with a pointer to the metaclass structure before finally
/// emitting the / module.
llvm::GlobalAlias *MetaClassPtrAlias;
/// All of the classes that have been generated for this compilation units.
std::vector<llvm::Constant*> Classes;
/// All of the categories that have been generated for this compilation units.
std::vector<llvm::Constant*> Categories;
/// All of the Objective-C constant strings that have been generated for this
/// compilation units.
std::vector<llvm::Constant*> ConstantStrings;
/// Map from string values to Objective-C constant strings in the output.
/// Used to prevent emitting Objective-C strings more than once. This should
/// not be required at all - CodeGenModule should manage this list.
llvm::StringMap<llvm::Constant*> ObjCStrings;
/// All of the protocols that have been declared.
llvm::StringMap<llvm::Constant*> ExistingProtocols;
/// For each variant of a selector, we store the type encoding and a
/// placeholder value. For an untyped selector, the type will be the empty
/// string. Selector references are all done via the module's selector table,
/// so we create an alias as a placeholder and then replace it with the real
/// value later.
typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
/// Type of the selector map. This is roughly equivalent to the structure
/// used in the GNUstep runtime, which maintains a list of all of the valid
/// types for a selector in a table.
typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
SelectorMap;
/// A map from selectors to selector types. This allows us to emit all
/// selectors of the same name and type together.
SelectorMap SelectorTable;
/// Selectors related to memory management. When compiling in GC mode, we
/// omit these.
Selector RetainSel, ReleaseSel, AutoreleaseSel;
/// Runtime functions used for memory management in GC mode. Note that clang
/// supports code generation for calling these functions, but neither GNU
/// runtime actually supports this API properly yet.
LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
WeakAssignFn, GlobalAssignFn;
typedef std::pair<std::string, std::string> ClassAliasPair;
/// All classes that have aliases set for them.
std::vector<ClassAliasPair> ClassAliases;
protected:
/// Function used for throwing Objective-C exceptions.
LazyRuntimeFunction ExceptionThrowFn;
/// Function used for rethrowing exceptions, used at the end of \@finally or
/// \@synchronize blocks.
LazyRuntimeFunction ExceptionReThrowFn;
/// Function called when entering a catch function. This is required for
/// differentiating Objective-C exceptions and foreign exceptions.
LazyRuntimeFunction EnterCatchFn;
/// Function called when exiting from a catch block. Used to do exception
/// cleanup.
LazyRuntimeFunction ExitCatchFn;
/// Function called when entering an \@synchronize block. Acquires the lock.
LazyRuntimeFunction SyncEnterFn;
/// Function called when exiting an \@synchronize block. Releases the lock.
LazyRuntimeFunction SyncExitFn;
private:
/// Function called if fast enumeration detects that the collection is
/// modified during the update.
LazyRuntimeFunction EnumerationMutationFn;
/// Function for implementing synthesized property getters that return an
/// object.
LazyRuntimeFunction GetPropertyFn;
/// Function for implementing synthesized property setters that return an
/// object.
LazyRuntimeFunction SetPropertyFn;
/// Function used for non-object declared property getters.
LazyRuntimeFunction GetStructPropertyFn;
/// Function used for non-object declared property setters.
LazyRuntimeFunction SetStructPropertyFn;
/// The version of the runtime that this class targets. Must match the
/// version in the runtime.
int RuntimeVersion;
/// The version of the protocol class. Used to differentiate between ObjC1
/// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
/// components and can not contain declared properties. We always emit
/// Objective-C 2 property structures, but we have to pretend that they're
/// Objective-C 1 property structures when targeting the GCC runtime or it
/// will abort.
const int ProtocolVersion;
private:
/// Generates an instance variable list structure. This is a structure
/// containing a size and an array of structures containing instance variable
/// metadata. This is used purely for introspection in the fragile ABI. In
/// the non-fragile ABI, it's used for instance variable fixup.
llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
ArrayRef<llvm::Constant *> IvarTypes,
ArrayRef<llvm::Constant *> IvarOffsets);
/// Generates a method list structure. This is a structure containing a size
/// and an array of structures containing method metadata.
///
/// This structure is used by both classes and categories, and contains a next
/// pointer allowing them to be chained together in a linked list.
llvm::Constant *GenerateMethodList(StringRef ClassName,
StringRef CategoryName,
ArrayRef<Selector> MethodSels,
ArrayRef<llvm::Constant *> MethodTypes,
bool isClassMethodList);
/// Emits an empty protocol. This is used for \@protocol() where no protocol
/// is found. The runtime will (hopefully) fix up the pointer to refer to the
/// real protocol.
llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
/// Generates a list of property metadata structures. This follows the same
/// pattern as method and instance variable metadata lists.
llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
SmallVectorImpl<Selector> &InstanceMethodSels,
SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
/// Generates a list of referenced protocols. Classes, categories, and
/// protocols all use this structure.
llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
/// To ensure that all protocols are seen by the runtime, we add a category on
/// a class defined in the runtime, declaring no methods, but adopting the
/// protocols. This is a horribly ugly hack, but it allows us to collect all
/// of the protocols without changing the ABI.
void GenerateProtocolHolderCategory();
/// Generates a class structure.
llvm::Constant *GenerateClassStructure(
llvm::Constant *MetaClass,
llvm::Constant *SuperClass,
unsigned info,
const char *Name,
llvm::Constant *Version,
llvm::Constant *InstanceSize,
llvm::Constant *IVars,
llvm::Constant *Methods,
llvm::Constant *Protocols,
llvm::Constant *IvarOffsets,
llvm::Constant *Properties,
llvm::Constant *StrongIvarBitmap,
llvm::Constant *WeakIvarBitmap,
bool isMeta=false);
/// Generates a method list. This is used by protocols to define the required
/// and optional methods.
llvm::Constant *GenerateProtocolMethodList(
ArrayRef<llvm::Constant *> MethodNames,
ArrayRef<llvm::Constant *> MethodTypes);
/// Returns a selector with the specified type encoding. An empty string is
/// used to return an untyped selector (with the types field set to NULL).
llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
const std::string &TypeEncoding, bool lval);
/// Returns the variable used to store the offset of an instance variable.
llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
const ObjCIvarDecl *Ivar);
/// Emits a reference to a class. This allows the linker to object if there
/// is no class of the matching name.
protected:
void EmitClassRef(const std::string &className);
/// Emits a pointer to the named class
virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
const std::string &Name, bool isWeak);
/// Looks up the method for sending a message to the specified object. This
/// mechanism differs between the GCC and GNU runtimes, so this method must be
/// overridden in subclasses.
virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
llvm::Value *&Receiver,
llvm::Value *cmd,
llvm::MDNode *node,
MessageSendInfo &MSI) = 0;
/// Looks up the method for sending a message to a superclass. This
/// mechanism differs between the GCC and GNU runtimes, so this method must
/// be overridden in subclasses.
virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
llvm::Value *ObjCSuper,
llvm::Value *cmd,
MessageSendInfo &MSI) = 0;
/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
/// bits set to their values, LSB first, while larger ones are stored in a
/// structure of this / form:
///
/// struct { int32_t length; int32_t values[length]; };
///
/// The values in the array are stored in host-endian format, with the least
/// significant bit being assumed to come first in the bitfield. Therefore,
/// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
/// while a bitfield / with the 63rd bit set will be 1<<64.
llvm::Constant *MakeBitField(ArrayRef<bool> bits);
public:
CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
unsigned protocolClassVersion);
llvm::Constant *GenerateConstantString(const StringLiteral *) override;
RValue
GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
QualType ResultType, Selector Sel,
llvm::Value *Receiver, const CallArgList &CallArgs,
const ObjCInterfaceDecl *Class,
const ObjCMethodDecl *Method) override;
RValue
GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
QualType ResultType, Selector Sel,
const ObjCInterfaceDecl *Class,
bool isCategoryImpl, llvm::Value *Receiver,
bool IsClassMessage, const CallArgList &CallArgs,
const ObjCMethodDecl *Method) override;
llvm::Value *GetClass(CodeGenFunction &CGF,
const ObjCInterfaceDecl *OID) override;
llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
bool lval = false) override;
llvm::Value *GetSelector(CodeGenFunction &CGF,
const ObjCMethodDecl *Method) override;
llvm::Constant *GetEHType(QualType T) override;
llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
const ObjCContainerDecl *CD) override;
void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
const ObjCProtocolDecl *PD) override;
void GenerateProtocol(const ObjCProtocolDecl *PD) override;
llvm::Function *ModuleInitFunction() override;
llvm::Constant *GetPropertyGetFunction() override;
llvm::Constant *GetPropertySetFunction() override;
llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
bool copy) override;
llvm::Constant *GetSetStructFunction() override;
llvm::Constant *GetGetStructFunction() override;
llvm::Constant *GetCppAtomicObjectGetFunction() override;
llvm::Constant *GetCppAtomicObjectSetFunction() override;
llvm::Constant *EnumerationMutationFunction() override;
void EmitTryStmt(CodeGenFunction &CGF,
const ObjCAtTryStmt &S) override;
void EmitSynchronizedStmt(CodeGenFunction &CGF,
const ObjCAtSynchronizedStmt &S) override;
void EmitThrowStmt(CodeGenFunction &CGF,
const ObjCAtThrowStmt &S,
bool ClearInsertionPoint=true) override;
llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
llvm::Value *AddrWeakObj) override;
void EmitObjCWeakAssign(CodeGenFunction &CGF,
llvm::Value *src, llvm::Value *dst) override;
void EmitObjCGlobalAssign(CodeGenFunction &CGF,
llvm::Value *src, llvm::Value *dest,
bool threadlocal=false) override;
void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
llvm::Value *dest, llvm::Value *ivarOffset) override;
void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
llvm::Value *src, llvm::Value *dest) override;
void EmitGCMemmoveCollectable(CodeGenFunction &CGF, llvm::Value *DestPtr,
llvm::Value *SrcPtr,
llvm::Value *Size) override;
LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
unsigned CVRQualifiers) override;
llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar) override;
llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) override {
return NULLPtr;
}
llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
const CGBlockInfo &blockInfo) override {
return NULLPtr;
}
llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
return NULLPtr;
}
llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
bool Weak = false) override {
return nullptr;
}
};
/// Class representing the legacy GCC Objective-C ABI. This is the default when
/// -fobjc-nonfragile-abi is not specified.
///
/// The GCC ABI target actually generates code that is approximately compatible
/// with the new GNUstep runtime ABI, but refrains from using any features that
/// would not work with the GCC runtime. For example, clang always generates
/// the extended form of the class structure, and the extra fields are simply
/// ignored by GCC libobjc.
class CGObjCGCC : public CGObjCGNU {
/// The GCC ABI message lookup function. Returns an IMP pointing to the
/// method implementation for this message.
LazyRuntimeFunction MsgLookupFn;
/// The GCC ABI superclass message lookup function. Takes a pointer to a
/// structure describing the receiver and the class, and a selector as
/// arguments. Returns the IMP for the corresponding method.
LazyRuntimeFunction MsgLookupSuperFn;
protected:
llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
llvm::Value *cmd, llvm::MDNode *node,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *args[] = {
EnforceType(Builder, Receiver, IdTy),
EnforceType(Builder, cmd, SelectorTy) };
llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
imp->setMetadata(msgSendMDKind, node);
return imp.getInstruction();
}
llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
llvm::Value *cmd, MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
PtrToObjCSuperTy), cmd};
return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
}
public:
CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
// IMP objc_msg_lookup(id, SEL);
MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
nullptr);
// IMP objc_msg_lookup_super(struct objc_super*, SEL);
MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
PtrToObjCSuperTy, SelectorTy, nullptr);
}
};
/// Class used when targeting the new GNUstep runtime ABI.
class CGObjCGNUstep : public CGObjCGNU {
/// The slot lookup function. Returns a pointer to a cacheable structure
/// that contains (among other things) the IMP.
LazyRuntimeFunction SlotLookupFn;
/// The GNUstep ABI superclass message lookup function. Takes a pointer to
/// a structure describing the receiver and the class, and a selector as
/// arguments. Returns the slot for the corresponding method. Superclass
/// message lookup rarely changes, so this is a good caching opportunity.
LazyRuntimeFunction SlotLookupSuperFn;
/// Specialised function for setting atomic retain properties
LazyRuntimeFunction SetPropertyAtomic;
/// Specialised function for setting atomic copy properties
LazyRuntimeFunction SetPropertyAtomicCopy;
/// Specialised function for setting nonatomic retain properties
LazyRuntimeFunction SetPropertyNonAtomic;
/// Specialised function for setting nonatomic copy properties
LazyRuntimeFunction SetPropertyNonAtomicCopy;
/// Function to perform atomic copies of C++ objects with nontrivial copy
/// constructors from Objective-C ivars.
LazyRuntimeFunction CxxAtomicObjectGetFn;
/// Function to perform atomic copies of C++ objects with nontrivial copy
/// constructors to Objective-C ivars.
LazyRuntimeFunction CxxAtomicObjectSetFn;
/// Type of an slot structure pointer. This is returned by the various
/// lookup functions.
llvm::Type *SlotTy;
public:
llvm::Constant *GetEHType(QualType T) override;
protected:
llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
llvm::Value *cmd, llvm::MDNode *node,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Function *LookupFn = SlotLookupFn;
// Store the receiver on the stack so that we can reload it later
llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
Builder.CreateStore(Receiver, ReceiverPtr);
llvm::Value *self;
if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
self = CGF.LoadObjCSelf();
} else {
self = llvm::ConstantPointerNull::get(IdTy);
}
// The lookup function is guaranteed not to capture the receiver pointer.
LookupFn->setDoesNotCapture(1);
llvm::Value *args[] = {
EnforceType(Builder, ReceiverPtr, PtrToIdTy),
EnforceType(Builder, cmd, SelectorTy),
EnforceType(Builder, self, IdTy) };
llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
slot.setOnlyReadsMemory();
slot->setMetadata(msgSendMDKind, node);
// Load the imp from the slot
llvm::Value *imp =
Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
// The lookup function may have changed the receiver, so make sure we use
// the new one.
Receiver = Builder.CreateLoad(ReceiverPtr, true);
return imp;
}
llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
llvm::Value *cmd,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
llvm::CallInst *slot =
CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
slot->setOnlyReadsMemory();
return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
}
public:
CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
PtrTy, PtrTy, IntTy, IMPTy, nullptr);
SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
// Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
SelectorTy, IdTy, nullptr);
// Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
PtrToObjCSuperTy, SelectorTy, nullptr);
// If we're in ObjC++ mode, then we want to make
if (CGM.getLangOpts().CPlusPlus) {
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
// void *__cxa_begin_catch(void *e)
EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
// void __cxa_end_catch(void)
ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
// void _Unwind_Resume_or_Rethrow(void*)
ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
PtrTy, nullptr);
} else if (R.getVersion() >= VersionTuple(1, 7)) {
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
// id objc_begin_catch(void *e)
EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
// void objc_end_catch(void)
ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
// void _Unwind_Resume_or_Rethrow(void*)
ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
PtrTy, nullptr);
}
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
SelectorTy, IdTy, PtrDiffTy, nullptr);
SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
// void objc_setCppObjectAtomic(void *dest, const void *src, void
// *helper);
CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
PtrTy, PtrTy, nullptr);
// void objc_getCppObjectAtomic(void *dest, const void *src, void
// *helper);
CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
PtrTy, PtrTy, nullptr);
}
llvm::Constant *GetCppAtomicObjectGetFunction() override {
// The optimised functions were added in version 1.7 of the GNUstep
// runtime.
assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
VersionTuple(1, 7));
return CxxAtomicObjectGetFn;
}
llvm::Constant *GetCppAtomicObjectSetFunction() override {
// The optimised functions were added in version 1.7 of the GNUstep
// runtime.
assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
VersionTuple(1, 7));
return CxxAtomicObjectSetFn;
}
llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
bool copy) override {
// The optimised property functions omit the GC check, and so are not
// safe to use in GC mode. The standard functions are fast in GC mode,
// so there is less advantage in using them.
assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
// The optimised functions were added in version 1.7 of the GNUstep
// runtime.
assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
VersionTuple(1, 7));
if (atomic) {
if (copy) return SetPropertyAtomicCopy;
return SetPropertyAtomic;
}
return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
}
};
/// Support for the ObjFW runtime.
class CGObjCObjFW: public CGObjCGNU {
protected:
/// The GCC ABI message lookup function. Returns an IMP pointing to the
/// method implementation for this message.
LazyRuntimeFunction MsgLookupFn;
/// stret lookup function. While this does not seem to make sense at the
/// first look, this is required to call the correct forwarding function.
LazyRuntimeFunction MsgLookupFnSRet;
/// The GCC ABI superclass message lookup function. Takes a pointer to a
/// structure describing the receiver and the class, and a selector as
/// arguments. Returns the IMP for the corresponding method.
LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
llvm::Value *cmd, llvm::MDNode *node,
MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *args[] = {
EnforceType(Builder, Receiver, IdTy),
EnforceType(Builder, cmd, SelectorTy) };
llvm::CallSite imp;
if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
else
imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
imp->setMetadata(msgSendMDKind, node);
return imp.getInstruction();
}
llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
llvm::Value *cmd, MessageSendInfo &MSI) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
PtrToObjCSuperTy), cmd};
if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
else
return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
}
llvm::Value *GetClassNamed(CodeGenFunction &CGF,
const std::string &Name, bool isWeak) override {
if (isWeak)
return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
EmitClassRef(Name);
std::string SymbolName = "_OBJC_CLASS_" + Name;
llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
if (!ClassSymbol)
ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
llvm::GlobalValue::ExternalLinkage,
nullptr, SymbolName);
return ClassSymbol;
}
public:
CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
// IMP objc_msg_lookup(id, SEL);
MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
SelectorTy, nullptr);
// IMP objc_msg_lookup_super(struct objc_super*, SEL);
MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
PtrToObjCSuperTy, SelectorTy, nullptr);
MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
PtrToObjCSuperTy, SelectorTy, nullptr);
}
};
} // end anonymous namespace
/// Emits a reference to a dummy variable which is emitted with each class.
/// This ensures that a linker error will be generated when trying to link
/// together modules where a referenced class is not defined.
void CGObjCGNU::EmitClassRef(const std::string &className) {
std::string symbolRef = "__objc_class_ref_" + className;
// Don't emit two copies of the same symbol
if (TheModule.getGlobalVariable(symbolRef))
return;
std::string symbolName = "__objc_class_name_" + className;
llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
if (!ClassSymbol) {
ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
llvm::GlobalValue::ExternalLinkage,
nullptr, symbolName);
}
new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
}
static std::string SymbolNameForMethod( StringRef ClassName,
StringRef CategoryName, const Selector MethodName,
bool isClassMethod) {
std::string MethodNameColonStripped = MethodName.getAsString();
std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
':', '_');
return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
CategoryName + "_" + MethodNameColonStripped).str();
}
CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
unsigned protocolClassVersion)
: CGObjCRuntime(cgm), TheModule(CGM.getModule()),
VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
ProtocolVersion(protocolClassVersion) {
msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
CodeGenTypes &Types = CGM.getTypes();
IntTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().IntTy));
LongTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().LongTy));
SizeTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().getSizeType()));
PtrDiffTy = cast<llvm::IntegerType>(
Types.ConvertType(CGM.getContext().getPointerDiffType()));
BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Int8Ty = llvm::Type::getInt8Ty(VMContext);
// C string type. Used in lots of places.
PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
Zeros[1] = Zeros[0];
NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
// Get the selector Type.
QualType selTy = CGM.getContext().getObjCSelType();
if (QualType() == selTy) {
SelectorTy = PtrToInt8Ty;
} else {
SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
}
PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
PtrTy = PtrToInt8Ty;
Int32Ty = llvm::Type::getInt32Ty(VMContext);
Int64Ty = llvm::Type::getInt64Ty(VMContext);
IntPtrTy =
CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
// Object type
QualType UnqualIdTy = CGM.getContext().getObjCIdType();
ASTIdTy = CanQualType();
if (UnqualIdTy != QualType()) {
ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
} else {
IdTy = PtrToInt8Ty;
}
PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
// void objc_exception_throw(id);
ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
// int objc_sync_enter(id);
SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
// int objc_sync_exit(id);
SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
// void objc_enumerationMutation (id)
EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
IdTy, nullptr);
// id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
PtrDiffTy, BoolTy, nullptr);
// void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
// void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
PtrDiffTy, BoolTy, BoolTy, nullptr);
// void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
PtrDiffTy, BoolTy, BoolTy, nullptr);
// IMP type
llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
true));
const LangOptions &Opts = CGM.getLangOpts();
if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
RuntimeVersion = 10;
// Don't bother initialising the GC stuff unless we're compiling in GC mode
if (Opts.getGC() != LangOptions::NonGC) {
// This is a bit of an hack. We should sort this out by having a proper
// CGObjCGNUstep subclass for GC, but we may want to really support the old
// ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
// Get selectors needed in GC mode
RetainSel = GetNullarySelector("retain", CGM.getContext());
ReleaseSel = GetNullarySelector("release", CGM.getContext());
AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
// Get functions needed in GC mode
// id objc_assign_ivar(id, id, ptrdiff_t);
IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
nullptr);
// id objc_assign_strongCast (id, id*)
StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
PtrToIdTy, nullptr);
// id objc_assign_global(id, id*);
GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
nullptr);
// id objc_assign_weak(id, id*);
WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
// id objc_read_weak(id*);
WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
// void *objc_memmove_collectable(void*, void *, size_t);
MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
SizeTy, nullptr);
}
}
llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
const std::string &Name,
bool isWeak) {
llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
// With the incompatible ABI, this will need to be replaced with a direct
// reference to the class symbol. For the compatible nonfragile ABI we are
// still performing this lookup at run time but emitting the symbol for the
// class externally so that we can make the switch later.
//
// Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
// with memoized versions or with static references if it's safe to do so.
if (!isWeak)
EmitClassRef(Name);
ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
llvm::Constant *ClassLookupFn =
CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
"objc_lookup_class");
return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
}
// This has to perform the lookup every time, since posing and related
// techniques can modify the name -> class mapping.
llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
const ObjCInterfaceDecl *OID) {
return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
}
llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
return GetClassNamed(CGF, "NSAutoreleasePool", false);
}
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
const std::string &TypeEncoding, bool lval) {
SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
llvm::GlobalAlias *SelValue = nullptr;
for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
e = Types.end() ; i!=e ; i++) {
if (i->first == TypeEncoding) {
SelValue = i->second;
break;
}
}
if (!SelValue) {
SelValue = llvm::GlobalAlias::create(
SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
".objc_selector_" + Sel.getAsString(), &TheModule);
Types.push_back(TypedSelector(TypeEncoding, SelValue));
}
if (lval) {
llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
CGF.Builder.CreateStore(SelValue, tmp);
return tmp;
}
return SelValue;
}
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
bool lval) {
return GetSelector(CGF, Sel, std::string(), lval);
}
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
const ObjCMethodDecl *Method) {
std::string SelTypes;
CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
return GetSelector(CGF, Method->getSelector(), SelTypes, false);
}
llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
// With the old ABI, there was only one kind of catchall, which broke
// foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
// a pointer indicating object catchalls, and NULL to indicate real
// catchalls
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
return MakeConstantString("@id");
} else {
return nullptr;
}
}
// All other types should be Objective-C interface pointer types.
const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
assert(OPT && "Invalid @catch type.");
const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
assert(IDecl && "Invalid @catch type.");
return MakeConstantString(IDecl->getIdentifier()->getName());
}
llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
if (!CGM.getLangOpts().CPlusPlus)
return CGObjCGNU::GetEHType(T);
// For Objective-C++, we want to provide the ability to catch both C++ and
// Objective-C objects in the same function.
// There's a particular fixed type info for 'id'.
if (T->isObjCIdType() ||
T->isObjCQualifiedIdType()) {
llvm::Constant *IDEHType =
CGM.getModule().getGlobalVariable("__objc_id_type_info");
if (!IDEHType)
IDEHType =
new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
false,
llvm::GlobalValue::ExternalLinkage,
nullptr, "__objc_id_type_info");
return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
}
const ObjCObjectPointerType *PT =
T->getAs<ObjCObjectPointerType>();
assert(PT && "Invalid @catch type.");
const ObjCInterfaceType *IT = PT->getInterfaceType();
assert(IT && "Invalid @catch type.");
std::string className = IT->getDecl()->getIdentifier()->getName();
std::string typeinfoName = "__objc_eh_typeinfo_" + className;
// Return the existing typeinfo if it exists
llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
if (typeinfo)
return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
// Otherwise create it.
// vtable for gnustep::libobjc::__objc_class_type_info
// It's quite ugly hard-coding this. Ideally we'd generate it using the host
// platform's name mangling.
const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
if (!Vtable) {
Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
llvm::GlobalValue::ExternalLinkage,
nullptr, vtableName);
}
llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
llvm::Constant *typeName =
ExportUniqueString(className, "__objc_eh_typename_");
std::vector<llvm::Constant*> fields;
fields.push_back(Vtable);
fields.push_back(typeName);
llvm::Constant *TI =
MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
nullptr), fields, "__objc_eh_typeinfo_" + className,
llvm::GlobalValue::LinkOnceODRLinkage);
return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
}
/// Generate an NSConstantString object.
llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
std::string Str = SL->getString().str();
// Look for an existing one
llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
if (old != ObjCStrings.end())
return old->getValue();
StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
if (StringClass.empty()) StringClass = "NXConstantString";
std::string Sym = "_OBJC_CLASS_";
Sym += StringClass;
llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
if (!isa)
isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
else if (isa->getType() != PtrToIdTy)
isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
std::vector<llvm::Constant*> Ivars;
Ivars.push_back(isa);
Ivars.push_back(MakeConstantString(Str));
Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
llvm::Constant *ObjCStr = MakeGlobal(
llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
Ivars, ".objc_str");
ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
ObjCStrings[Str] = ObjCStr;
ConstantStrings.push_back(ObjCStr);
return ObjCStr;
}
///Generates a message send where the super is the receiver. This is a message
///send to self with special delivery semantics indicating which class's method
///should be called.
RValue
CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
ReturnValueSlot Return,
QualType ResultType,
Selector Sel,
const ObjCInterfaceDecl *Class,
bool isCategoryImpl,
llvm::Value *Receiver,
bool IsClassMessage,
const CallArgList &CallArgs,
const ObjCMethodDecl *Method) {
CGBuilderTy &Builder = CGF.Builder;
if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
if (Sel == RetainSel || Sel == AutoreleaseSel) {
return RValue::get(EnforceType(Builder, Receiver,
CGM.getTypes().ConvertType(ResultType)));
}
if (Sel == ReleaseSel) {
return RValue::get(nullptr);
}
}
llvm::Value *cmd = GetSelector(CGF, Sel);
CallArgList ActualArgs;
ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
ActualArgs.addFrom(CallArgs);
MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
llvm::Value *ReceiverClass = nullptr;
if (isCategoryImpl) {
llvm::Constant *classLookupFunction = nullptr;
if (IsClassMessage) {
classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
IdTy, PtrTy, true), "objc_get_meta_class");
} else {
classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
IdTy, PtrTy, true), "objc_get_class");
}
ReceiverClass = Builder.CreateCall(classLookupFunction,
MakeConstantString(Class->getNameAsString()));
} else {
// Set up global aliases for the metaclass or class pointer if they do not
// already exist. These will are forward-references which will be set to
// pointers to the class and metaclass structure created for the runtime
// load function. To send a message to super, we look up the value of the
// super_class pointer from either the class or metaclass structure.
if (IsClassMessage) {
if (!MetaClassPtrAlias) {
MetaClassPtrAlias = llvm::GlobalAlias::create(
IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
}
ReceiverClass = MetaClassPtrAlias;
} else {
if (!ClassPtrAlias) {
ClassPtrAlias = llvm::GlobalAlias::create(
IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
".objc_class_ref" + Class->getNameAsString(), &TheModule);
}
ReceiverClass = ClassPtrAlias;
}
}
// Cast the pointer to a simplified version of the class structure
ReceiverClass = Builder.CreateBitCast(ReceiverClass,
llvm::PointerType::getUnqual(
llvm::StructType::get(IdTy, IdTy, nullptr)));
// Get the superclass pointer
ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
// Load the superclass pointer
ReceiverClass = Builder.CreateLoad(ReceiverClass);
// Construct the structure used to look up the IMP
llvm::StructType *ObjCSuperTy = llvm::StructType::get(
Receiver->getType(), IdTy, nullptr);
llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
// Get the IMP
llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
imp = EnforceType(Builder, imp, MSI.MessengerType);
llvm::Metadata *impMD[] = {
llvm::MDString::get(VMContext, Sel.getAsString()),
llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
llvm::Instruction *call;
RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
&call);
call->setMetadata(msgSendMDKind, node);
return msgRet;
}
/// Generate code for a message send expression.
RValue
CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
ReturnValueSlot Return,
QualType ResultType,
Selector Sel,
llvm::Value *Receiver,
const CallArgList &CallArgs,
const ObjCInterfaceDecl *Class,
const ObjCMethodDecl *Method) {
CGBuilderTy &Builder = CGF.Builder;
// Strip out message sends to retain / release in GC mode
if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
if (Sel == RetainSel || Sel == AutoreleaseSel) {
return RValue::get(EnforceType(Builder, Receiver,
CGM.getTypes().ConvertType(ResultType)));
}
if (Sel == ReleaseSel) {
return RValue::get(nullptr);
}
}
// If the return type is something that goes in an integer register, the
// runtime will handle 0 returns. For other cases, we fill in the 0 value
// ourselves.
//
// The language spec says the result of this kind of message send is
// undefined, but lots of people seem to have forgotten to read that
// paragraph and insist on sending messages to nil that have structure
// returns. With GCC, this generates a random return value (whatever happens
// to be on the stack / in those registers at the time) on most platforms,
// and generates an illegal instruction trap on SPARC. With LLVM it corrupts
// the stack.
bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
llvm::BasicBlock *startBB = nullptr;
llvm::BasicBlock *messageBB = nullptr;
llvm::BasicBlock *continueBB = nullptr;
if (!isPointerSizedReturn) {
startBB = Builder.GetInsertBlock();
messageBB = CGF.createBasicBlock("msgSend");
continueBB = CGF.createBasicBlock("continue");
llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
llvm::Constant::getNullValue(Receiver->getType()));
Builder.CreateCondBr(isNil, continueBB, messageBB);
CGF.EmitBlock(messageBB);
}
IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
llvm::Value *cmd;
if (Method)
cmd = GetSelector(CGF, Method);
else
cmd = GetSelector(CGF, Sel);
cmd = EnforceType(Builder, cmd, SelectorTy);
Receiver = EnforceType(Builder, Receiver, IdTy);
llvm::Metadata *impMD[] = {
llvm::MDString::get(VMContext, Sel.getAsString()),
llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
CallArgList ActualArgs;
ActualArgs.add(RValue::get(Receiver), ASTIdTy);
ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
ActualArgs.addFrom(CallArgs);
MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
// Get the IMP to call
llvm::Value *imp;
// If we have non-legacy dispatch specified, we try using the objc_msgSend()
// functions. These are not supported on all platforms (or all runtimes on a
// given platform), so we
switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
case CodeGenOptions::Legacy:
imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
break;
case CodeGenOptions::Mixed:
case CodeGenOptions::NonLegacy:
if (CGM.ReturnTypeUsesFPRet(ResultType)) {
imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
"objc_msgSend_fpret");
} else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
// The actual types here don't matter - we're going to bitcast the
// function anyway
imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
"objc_msgSend_stret");
} else {
imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
"objc_msgSend");
}
}
// Reset the receiver in case the lookup modified it
ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
imp = EnforceType(Builder, imp, MSI.MessengerType);
llvm::Instruction *call;
RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
&call);
call->setMetadata(msgSendMDKind, node);
if (!isPointerSizedReturn) {
messageBB = CGF.Builder.GetInsertBlock();
CGF.Builder.CreateBr(continueBB);
CGF.EmitBlock(continueBB);
if (msgRet.isScalar()) {
llvm::Value *v = msgRet.getScalarVal();
llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
phi->addIncoming(v, messageBB);
phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
msgRet = RValue::get(phi);
} else if (msgRet.isAggregate()) {
llvm::Value *v = msgRet.getAggregateAddr();
llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
llvm::AllocaInst *NullVal =
CGF.CreateTempAlloca(RetTy->getElementType(), "null");
CGF.InitTempAlloca(NullVal,
llvm::Constant::getNullValue(RetTy->getElementType()));
phi->addIncoming(v, messageBB);
phi->addIncoming(NullVal, startBB);
msgRet = RValue::getAggregate(phi);
} else /* isComplex() */ {
std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
phi->addIncoming(v.first, messageBB);
phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
startBB);
llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
phi2->addIncoming(v.second, messageBB);
phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
startBB);
msgRet = RValue::getComplex(phi, phi2);
}
}
return msgRet;
}
/// Generates a MethodList. Used in construction of a objc_class and
/// objc_category structures.
llvm::Constant *CGObjCGNU::
GenerateMethodList(StringRef ClassName,
StringRef CategoryName,
ArrayRef<Selector> MethodSels,
ArrayRef<llvm::Constant *> MethodTypes,
bool isClassMethodList) {
if (MethodSels.empty())
return NULLPtr;
// Get the method structure type.
llvm::StructType *ObjCMethodTy = llvm::StructType::get(
PtrToInt8Ty, // Really a selector, but the runtime creates it us.
PtrToInt8Ty, // Method types
IMPTy, //Method pointer
nullptr);
std::vector<llvm::Constant*> Methods;
std::vector<llvm::Constant*> Elements;
for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
Elements.clear();
llvm::Constant *Method =
TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
MethodSels[i],
isClassMethodList));
assert(Method && "Can't generate metadata for method that doesn't exist");
llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
Elements.push_back(C);
Elements.push_back(MethodTypes[i]);
Method = llvm::ConstantExpr::getBitCast(Method,
IMPTy);
Elements.push_back(Method);
Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
}
// Array of method structures
llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
Methods.size());
llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
Methods);
// Structure containing list pointer, array and array count
llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
ObjCMethodListTy->setBody(
NextPtrTy,
IntTy,
ObjCMethodArrayTy,
nullptr);
Methods.clear();
Methods.push_back(llvm::ConstantPointerNull::get(
llvm::PointerType::getUnqual(ObjCMethodListTy)));
Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
Methods.push_back(MethodArray);
// Create an instance of the structure
return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
}
/// Generates an IvarList. Used in construction of a objc_class.
llvm::Constant *CGObjCGNU::
GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
ArrayRef<llvm::Constant *> IvarTypes,
ArrayRef<llvm::Constant *> IvarOffsets) {
if (IvarNames.size() == 0)
return NULLPtr;
// Get the method structure type.
llvm::StructType *ObjCIvarTy = llvm::StructType::get(
PtrToInt8Ty,
PtrToInt8Ty,
IntTy,
nullptr);
std::vector<llvm::Constant*> Ivars;
std::vector<llvm::Constant*> Elements;
for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
Elements.clear();
Elements.push_back(IvarNames[i]);
Elements.push_back(IvarTypes[i]);
Elements.push_back(IvarOffsets[i]);
Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
}
// Array of method structures
llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
IvarNames.size());
Elements.clear();
Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
// Structure containing array and array count
llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
ObjCIvarArrayTy,
nullptr);
// Create an instance of the structure
return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
}
/// Generate a class structure
llvm::Constant *CGObjCGNU::GenerateClassStructure(
llvm::Constant *MetaClass,
llvm::Constant *SuperClass,
unsigned info,
const char *Name,
llvm::Constant *Version,
llvm::Constant *InstanceSize,
llvm::Constant *IVars,
llvm::Constant *Methods,
llvm::Constant *Protocols,
llvm::Constant *IvarOffsets,
llvm::Constant *Properties,
llvm::Constant *StrongIvarBitmap,
llvm::Constant *WeakIvarBitmap,
bool isMeta) {
// Set up the class structure
// Note: Several of these are char*s when they should be ids. This is
// because the runtime performs this translation on load.
//
// Fields marked New ABI are part of the GNUstep runtime. We emit them
// anyway; the classes will still work with the GNU runtime, they will just
// be ignored.
llvm::StructType *ClassTy = llvm::StructType::get(
PtrToInt8Ty, // isa
PtrToInt8Ty, // super_class
PtrToInt8Ty, // name
LongTy, // version
LongTy, // info
LongTy, // instance_size
IVars->getType(), // ivars
Methods->getType(), // methods
// These are all filled in by the runtime, so we pretend
PtrTy, // dtable
PtrTy, // subclass_list
PtrTy, // sibling_class
PtrTy, // protocols
PtrTy, // gc_object_type
// New ABI:
LongTy, // abi_version
IvarOffsets->getType(), // ivar_offsets
Properties->getType(), // properties
IntPtrTy, // strong_pointers
IntPtrTy, // weak_pointers
nullptr);
llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
// Fill in the structure
std::vector<llvm::Constant*> Elements;
Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
Elements.push_back(SuperClass);
Elements.push_back(MakeConstantString(Name, ".class_name"));
Elements.push_back(Zero);
Elements.push_back(llvm::ConstantInt::get(LongTy, info));
if (isMeta) {
llvm::DataLayout td(&TheModule);
Elements.push_back(
llvm::ConstantInt::get(LongTy,
td.getTypeSizeInBits(ClassTy) /
CGM.getContext().getCharWidth()));
} else
Elements.push_back(InstanceSize);
Elements.push_back(IVars);
Elements.push_back(Methods);
Elements.push_back(NULLPtr);
Elements.push_back(NULLPtr);
Elements.push_back(NULLPtr);
Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
Elements.push_back(NULLPtr);
Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
Elements.push_back(IvarOffsets);
Elements.push_back(Properties);
Elements.push_back(StrongIvarBitmap);
Elements.push_back(WeakIvarBitmap);
// Create an instance of the structure
// This is now an externally visible symbol, so that we can speed up class
// messages in the next ABI. We may already have some weak references to
// this, so check and fix them properly.
std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
std::string(Name));
llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
llvm::GlobalValue::ExternalLinkage);
if (ClassRef) {
ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
ClassRef->getType()));
ClassRef->removeFromParent();
Class->setName(ClassSym);
}
return Class;
}
llvm::Constant *CGObjCGNU::
GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
ArrayRef<llvm::Constant *> MethodTypes) {
// Get the method structure type.
llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
PtrToInt8Ty,
nullptr);
std::vector<llvm::Constant*> Methods;
std::vector<llvm::Constant*> Elements;
for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
Elements.clear();
Elements.push_back(MethodNames[i]);
Elements.push_back(MethodTypes[i]);
Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
}
llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
MethodNames.size());
llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
Methods);
llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
IntTy, ObjCMethodArrayTy, nullptr);
Methods.clear();
Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
Methods.push_back(Array);
return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
}
// Create the protocol list structure used in classes, categories and so on
llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
Protocols.size());
llvm::StructType *ProtocolListTy = llvm::StructType::get(
PtrTy, //Should be a recurisve pointer, but it's always NULL here.
SizeTy,
ProtocolArrayTy,
nullptr);
std::vector<llvm::Constant*> Elements;
for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
iter != endIter ; iter++) {
llvm::Constant *protocol = nullptr;
llvm::StringMap<llvm::Constant*>::iterator value =
ExistingProtocols.find(*iter);
if (value == ExistingProtocols.end()) {
protocol = GenerateEmptyProtocol(*iter);
} else {
protocol = value->getValue();
}
llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
PtrToInt8Ty);
Elements.push_back(Ptr);
}
llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
Elements);
Elements.clear();
Elements.push_back(NULLPtr);
Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
Elements.push_back(ProtocolArray);
return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
}
llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
const ObjCProtocolDecl *PD) {
llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
llvm::Type *T =
CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
}
llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
const std::string &ProtocolName) {
SmallVector<std::string, 0> EmptyStringVector;
SmallVector<llvm::Constant*, 0> EmptyConstantVector;
llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
llvm::Constant *MethodList =
GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
// Protocols are objects containing lists of the methods implemented and
// protocols adopted.
llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
PtrToInt8Ty,
ProtocolList->getType(),
MethodList->getType(),
MethodList->getType(),
MethodList->getType(),
MethodList->getType(),
nullptr);
std::vector<llvm::Constant*> Elements;
// The isa pointer must be set to a magic number so the runtime knows it's
// the correct layout.
Elements.push_back(llvm::ConstantExpr::getIntToPtr(
llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
Elements.push_back(ProtocolList);
Elements.push_back(MethodList);
Elements.push_back(MethodList);
Elements.push_back(MethodList);
Elements.push_back(MethodList);
return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
}
void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
ASTContext &Context = CGM.getContext();
std::string ProtocolName = PD->getNameAsString();
// Use the protocol definition, if there is one.
if (const ObjCProtocolDecl *Def = PD->getDefinition())
PD = Def;
SmallVector<std::string, 16> Protocols;
for (const auto *PI : PD->protocols())
Protocols.push_back(PI->getNameAsString());
SmallVector<llvm::Constant*, 16> InstanceMethodNames;
SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
for (const auto *I : PD->instance_methods()) {
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(I, TypeStr);
if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
OptionalInstanceMethodNames.push_back(
MakeConstantString(I->getSelector().getAsString()));
OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
} else {
InstanceMethodNames.push_back(
MakeConstantString(I->getSelector().getAsString()));
InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
}
}
// Collect information about class methods:
SmallVector<llvm::Constant*, 16> ClassMethodNames;
SmallVector<llvm::Constant*, 16> ClassMethodTypes;
SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
for (const auto *I : PD->class_methods()) {
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(I,TypeStr);
if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
OptionalClassMethodNames.push_back(
MakeConstantString(I->getSelector().getAsString()));
OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
} else {
ClassMethodNames.push_back(
MakeConstantString(I->getSelector().getAsString()));
ClassMethodTypes.push_back(MakeConstantString(TypeStr));
}
}
llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
llvm::Constant *InstanceMethodList =
GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
llvm::Constant *ClassMethodList =
GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
llvm::Constant *OptionalInstanceMethodList =
GenerateProtocolMethodList(OptionalInstanceMethodNames,
OptionalInstanceMethodTypes);
llvm::Constant *OptionalClassMethodList =
GenerateProtocolMethodList(OptionalClassMethodNames,
OptionalClassMethodTypes);
// Property metadata: name, attributes, isSynthesized, setter name, setter
// types, getter name, getter types.
// The isSynthesized value is always set to 0 in a protocol. It exists to
// simplify the runtime library by allowing it to use the same data
// structures for protocol metadata everywhere.
llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
std::vector<llvm::Constant*> Properties;
std::vector<llvm::Constant*> OptionalProperties;
// Add all of the property methods need adding to the method list and to the
// property metadata list.
for (auto *property : PD->properties()) {
std::vector<llvm::Constant*> Fields;
Fields.push_back(MakePropertyEncodingString(property, nullptr));
PushPropertyAttributes(Fields, property);
if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(getter,TypeStr);
llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
InstanceMethodTypes.push_back(TypeEncoding);
Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
Fields.push_back(TypeEncoding);
} else {
Fields.push_back(NULLPtr);
Fields.push_back(NULLPtr);
}
if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(setter,TypeStr);
llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
InstanceMethodTypes.push_back(TypeEncoding);
Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
Fields.push_back(TypeEncoding);
} else {
Fields.push_back(NULLPtr);
Fields.push_back(NULLPtr);
}
if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
} else {
Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
}
}
llvm::Constant *PropertyArray = llvm::ConstantArray::get(
llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
llvm::Constant* PropertyListInitFields[] =
{llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
llvm::Constant *PropertyListInit =
llvm::ConstantStruct::getAnon(PropertyListInitFields);
llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
PropertyListInit, ".objc_property_list");
llvm::Constant *OptionalPropertyArray =
llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
OptionalProperties.size()) , OptionalProperties);
llvm::Constant* OptionalPropertyListInitFields[] = {
llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
OptionalPropertyArray };
llvm::Constant *OptionalPropertyListInit =
llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
OptionalPropertyListInit->getType(), false,
llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
".objc_property_list");
// Protocols are objects containing lists of the methods implemented and
// protocols adopted.
llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
PtrToInt8Ty,
ProtocolList->getType(),
InstanceMethodList->getType(),
ClassMethodList->getType(),
OptionalInstanceMethodList->getType(),
OptionalClassMethodList->getType(),
PropertyList->getType(),
OptionalPropertyList->getType(),
nullptr);
std::vector<llvm::Constant*> Elements;
// The isa pointer must be set to a magic number so the runtime knows it's
// the correct layout.
Elements.push_back(llvm::ConstantExpr::getIntToPtr(
llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
Elements.push_back(ProtocolList);
Elements.push_back(InstanceMethodList);
Elements.push_back(ClassMethodList);
Elements.push_back(OptionalInstanceMethodList);
Elements.push_back(OptionalClassMethodList);
Elements.push_back(PropertyList);
Elements.push_back(OptionalPropertyList);
ExistingProtocols[ProtocolName] =
llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
".objc_protocol"), IdTy);
}
void CGObjCGNU::GenerateProtocolHolderCategory() {
// Collect information about instance methods
SmallVector<Selector, 1> MethodSels;
SmallVector<llvm::Constant*, 1> MethodTypes;
std::vector<llvm::Constant*> Elements;
const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
const std::string CategoryName = "AnotherHack";
Elements.push_back(MakeConstantString(CategoryName));
Elements.push_back(MakeConstantString(ClassName));
// Instance method list
Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
// Class method list
Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
// Protocol list
llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
ExistingProtocols.size());
llvm::StructType *ProtocolListTy = llvm::StructType::get(
PtrTy, //Should be a recurisve pointer, but it's always NULL here.
SizeTy,
ProtocolArrayTy,
nullptr);
std::vector<llvm::Constant*> ProtocolElements;
for (llvm::StringMapIterator<llvm::Constant*> iter =
ExistingProtocols.begin(), endIter = ExistingProtocols.end();
iter != endIter ; iter++) {
llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
PtrTy);
ProtocolElements.push_back(Ptr);
}
llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
ProtocolElements);
ProtocolElements.clear();
ProtocolElements.push_back(NULLPtr);
ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
ExistingProtocols.size()));
ProtocolElements.push_back(ProtocolArray);
Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
ProtocolElements, ".objc_protocol_list"), PtrTy));
Categories.push_back(llvm::ConstantExpr::getBitCast(
MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
}
/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
/// bits set to their values, LSB first, while larger ones are stored in a
/// structure of this / form:
///
/// struct { int32_t length; int32_t values[length]; };
///
/// The values in the array are stored in host-endian format, with the least
/// significant bit being assumed to come first in the bitfield. Therefore, a
/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
/// bitfield / with the 63rd bit set will be 1<<64.
llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
int bitCount = bits.size();
int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
if (bitCount < ptrBits) {
uint64_t val = 1;
for (int i=0 ; i<bitCount ; ++i) {
if (bits[i]) val |= 1ULL<<(i+1);
}
return llvm::ConstantInt::get(IntPtrTy, val);
}
SmallVector<llvm::Constant *, 8> values;
int v=0;
while (v < bitCount) {
int32_t word = 0;
for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
if (bits[v]) word |= 1<<i;
v++;
}
values.push_back(llvm::ConstantInt::get(Int32Ty, word));
}
llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
llvm::Constant *fields[2] = {
llvm::ConstantInt::get(Int32Ty, values.size()),
array };
llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
nullptr), fields);
llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
return ptr;
}
void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
std::string ClassName = OCD->getClassInterface()->getNameAsString();
std::string CategoryName = OCD->getNameAsString();
// Collect information about instance methods
SmallVector<Selector, 16> InstanceMethodSels;
SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
for (const auto *I : OCD->instance_methods()) {
InstanceMethodSels.push_back(I->getSelector());
std::string TypeStr;
CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
}
// Collect information about class methods
SmallVector<Selector, 16> ClassMethodSels;
SmallVector<llvm::Constant*, 16> ClassMethodTypes;
for (const auto *I : OCD->class_methods()) {
ClassMethodSels.push_back(I->getSelector());
std::string TypeStr;
CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
ClassMethodTypes.push_back(MakeConstantString(TypeStr));
}
// Collect the names of referenced protocols
SmallVector<std::string, 16> Protocols;
const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
E = Protos.end(); I != E; ++I)
Protocols.push_back((*I)->getNameAsString());
std::vector<llvm::Constant*> Elements;
Elements.push_back(MakeConstantString(CategoryName));
Elements.push_back(MakeConstantString(ClassName));
// Instance method list
Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
false), PtrTy));
// Class method list
Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
PtrTy));
// Protocol list
Elements.push_back(llvm::ConstantExpr::getBitCast(
GenerateProtocolList(Protocols), PtrTy));
Categories.push_back(llvm::ConstantExpr::getBitCast(
MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
}
llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
SmallVectorImpl<Selector> &InstanceMethodSels,
SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
ASTContext &Context = CGM.getContext();
// Property metadata: name, attributes, attributes2, padding1, padding2,
// setter name, setter types, getter name, getter types.
llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
std::vector<llvm::Constant*> Properties;
// Add all of the property methods need adding to the method list and to the
// property metadata list.
for (auto *propertyImpl : OID->property_impls()) {
std::vector<llvm::Constant*> Fields;
ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
ObjCPropertyImplDecl::Synthesize);
bool isDynamic = (propertyImpl->getPropertyImplementation() ==
ObjCPropertyImplDecl::Dynamic);
Fields.push_back(MakePropertyEncodingString(property, OID));
PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(getter,TypeStr);
llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
if (isSynthesized) {
InstanceMethodTypes.push_back(TypeEncoding);
InstanceMethodSels.push_back(getter->getSelector());
}
Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
Fields.push_back(TypeEncoding);
} else {
Fields.push_back(NULLPtr);
Fields.push_back(NULLPtr);
}
if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(setter,TypeStr);
llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
if (isSynthesized) {
InstanceMethodTypes.push_back(TypeEncoding);
InstanceMethodSels.push_back(setter->getSelector());
}
Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
Fields.push_back(TypeEncoding);
} else {
Fields.push_back(NULLPtr);
Fields.push_back(NULLPtr);
}
Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
}
llvm::ArrayType *PropertyArrayTy =
llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
Properties);
llvm::Constant* PropertyListInitFields[] =
{llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
llvm::Constant *PropertyListInit =
llvm::ConstantStruct::getAnon(PropertyListInitFields);
return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
llvm::GlobalValue::InternalLinkage, PropertyListInit,
".objc_property_list");
}
void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
// Get the class declaration for which the alias is specified.
ObjCInterfaceDecl *ClassDecl =
const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
std::string ClassName = ClassDecl->getNameAsString();
std::string AliasName = OAD->getNameAsString();
ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
}
void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
ASTContext &Context = CGM.getContext();
// Get the superclass name.
const ObjCInterfaceDecl * SuperClassDecl =
OID->getClassInterface()->getSuperClass();
std::string SuperClassName;
if (SuperClassDecl) {
SuperClassName = SuperClassDecl->getNameAsString();
EmitClassRef(SuperClassName);
}
// Get the class name
ObjCInterfaceDecl *ClassDecl =
const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
std::string ClassName = ClassDecl->getNameAsString();
// Emit the symbol that is used to generate linker errors if this class is
// referenced in other modules but not declared.
std::string classSymbolName = "__objc_class_name_" + ClassName;
if (llvm::GlobalVariable *symbol =
TheModule.getGlobalVariable(classSymbolName)) {
symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
} else {
new llvm::GlobalVariable(TheModule, LongTy, false,
llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
classSymbolName);
}
// Get the size of instances.
int instanceSize =
Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
// Collect information about instance variables.
SmallVector<llvm::Constant*, 16> IvarNames;
SmallVector<llvm::Constant*, 16> IvarTypes;
SmallVector<llvm::Constant*, 16> IvarOffsets;
std::vector<llvm::Constant*> IvarOffsetValues;
SmallVector<bool, 16> WeakIvars;
SmallVector<bool, 16> StrongIvars;
int superInstanceSize = !SuperClassDecl ? 0 :
Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
// For non-fragile ivars, set the instance size to 0 - {the size of just this
// class}. The runtime will then set this to the correct value on load.
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
instanceSize = 0 - (instanceSize - superInstanceSize);
}
for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
IVD = IVD->getNextIvar()) {
// Store the name
IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
// Get the type encoding for this ivar
std::string TypeStr;
Context.getObjCEncodingForType(IVD->getType(), TypeStr);
IvarTypes.push_back(MakeConstantString(TypeStr));
// Get the offset
uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
uint64_t Offset = BaseOffset;
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Offset = BaseOffset - superInstanceSize;
}
llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
// Create the direct offset value
std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
IVD->getNameAsString();
llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
if (OffsetVar) {
OffsetVar->setInitializer(OffsetValue);
// If this is the real definition, change its linkage type so that
// different modules will use this one, rather than their private
// copy.
OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
} else
OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
false, llvm::GlobalValue::ExternalLinkage,
OffsetValue,
"__objc_ivar_offset_value_" + ClassName +"." +
IVD->getNameAsString());
IvarOffsets.push_back(OffsetValue);
IvarOffsetValues.push_back(OffsetVar);
Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
switch (lt) {
case Qualifiers::OCL_Strong:
StrongIvars.push_back(true);
WeakIvars.push_back(false);
break;
case Qualifiers::OCL_Weak:
StrongIvars.push_back(false);
WeakIvars.push_back(true);
break;
default:
StrongIvars.push_back(false);
WeakIvars.push_back(false);
}
}
llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
llvm::GlobalVariable *IvarOffsetArray =
MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
// Collect information about instance methods
SmallVector<Selector, 16> InstanceMethodSels;
SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
for (const auto *I : OID->instance_methods()) {
InstanceMethodSels.push_back(I->getSelector());
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(I,TypeStr);
InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
}
llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
InstanceMethodTypes);
// Collect information about class methods
SmallVector<Selector, 16> ClassMethodSels;
SmallVector<llvm::Constant*, 16> ClassMethodTypes;
for (const auto *I : OID->class_methods()) {
ClassMethodSels.push_back(I->getSelector());
std::string TypeStr;
Context.getObjCEncodingForMethodDecl(I,TypeStr);
ClassMethodTypes.push_back(MakeConstantString(TypeStr));
}
// Collect the names of referenced protocols
SmallVector<std::string, 16> Protocols;
for (const auto *I : ClassDecl->protocols())
Protocols.push_back(I->getNameAsString());
// Get the superclass pointer.
llvm::Constant *SuperClass;
if (!SuperClassName.empty()) {
SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
} else {
SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
}
// Empty vector used to construct empty method lists
SmallVector<llvm::Constant*, 1> empty;
// Generate the method and instance variable lists
llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
InstanceMethodSels, InstanceMethodTypes, false);
llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
ClassMethodSels, ClassMethodTypes, true);
llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
IvarOffsets);
// Irrespective of whether we are compiling for a fragile or non-fragile ABI,
// we emit a symbol containing the offset for each ivar in the class. This
// allows code compiled for the non-Fragile ABI to inherit from code compiled
// for the legacy ABI, without causing problems. The converse is also
// possible, but causes all ivar accesses to be fragile.
// Offset pointer for getting at the correct field in the ivar list when
// setting up the alias. These are: The base address for the global, the
// ivar array (second field), the ivar in this list (set for each ivar), and
// the offset (third field in ivar structure)
llvm::Type *IndexTy = Int32Ty;
llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
llvm::ConstantInt::get(IndexTy, 1), nullptr,
llvm::ConstantInt::get(IndexTy, 2) };
unsigned ivarIndex = 0;
for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
IVD = IVD->getNextIvar()) {
const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
+ IVD->getNameAsString();
offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
// Get the correct ivar field
llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
IvarList, offsetPointerIndexes);
// Get the existing variable, if one exists.
llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
if (offset) {
offset->setInitializer(offsetValue);
// If this is the real definition, change its linkage type so that
// different modules will use this one, rather than their private
// copy.
offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
} else {
// Add a new alias if there isn't one already.
offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
(void) offset; // Silence dead store warning.
}
++ivarIndex;
}
llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
//Generate metaclass for class methods
llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
empty, empty, empty), ClassMethodList, NULLPtr,
NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
// Generate the class structure
llvm::Constant *ClassStruct =
GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
ClassName.c_str(), nullptr,
llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
Properties, StrongIvarBitmap, WeakIvarBitmap);
// Resolve the class aliases, if they exist.
if (ClassPtrAlias) {
ClassPtrAlias->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
ClassPtrAlias->eraseFromParent();
ClassPtrAlias = nullptr;
}
if (MetaClassPtrAlias) {
MetaClassPtrAlias->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
MetaClassPtrAlias->eraseFromParent();
MetaClassPtrAlias = nullptr;
}
// Add class structure to list to be added to the symtab later
ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
Classes.push_back(ClassStruct);
}
llvm::Function *CGObjCGNU::ModuleInitFunction() {
// Only emit an ObjC load function if no Objective-C stuff has been called
if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
ExistingProtocols.empty() && SelectorTable.empty())
return nullptr;
// Add all referenced protocols to a category.
GenerateProtocolHolderCategory();
llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
SelectorTy->getElementType());
llvm::Type *SelStructPtrTy = SelectorTy;
if (!SelStructTy) {
SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
}
std::vector<llvm::Constant*> Elements;
llvm::Constant *Statics = NULLPtr;
// Generate statics list:
if (ConstantStrings.size()) {
llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
ConstantStrings.size() + 1);
ConstantStrings.push_back(NULLPtr);
StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
if (StringClass.empty()) StringClass = "NXConstantString";
Elements.push_back(MakeConstantString(StringClass,
".objc_static_class_name"));
Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
ConstantStrings));
llvm::StructType *StaticsListTy =
llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
llvm::Type *StaticsListPtrTy =
llvm::PointerType::getUnqual(StaticsListTy);
Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
llvm::ArrayType *StaticsListArrayTy =
llvm::ArrayType::get(StaticsListPtrTy, 2);
Elements.clear();
Elements.push_back(Statics);
Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
}
// Array of classes, categories, and constant objects
llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
Classes.size() + Categories.size() + 2);
llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
llvm::Type::getInt16Ty(VMContext),
llvm::Type::getInt16Ty(VMContext),
ClassListTy, nullptr);
Elements.clear();
// Pointer to an array of selectors used in this module.
std::vector<llvm::Constant*> Selectors;
std::vector<llvm::GlobalAlias*> SelectorAliases;
for (SelectorMap::iterator iter = SelectorTable.begin(),
iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
std::string SelNameStr = iter->first.getAsString();
llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
SmallVectorImpl<TypedSelector> &Types = iter->second;
for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
e = Types.end() ; i!=e ; i++) {
llvm::Constant *SelectorTypeEncoding = NULLPtr;
if (!i->first.empty())
SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
Elements.push_back(SelName);
Elements.push_back(SelectorTypeEncoding);
Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Elements.clear();
// Store the selector alias for later replacement
SelectorAliases.push_back(i->second);
}
}
unsigned SelectorCount = Selectors.size();
// NULL-terminate the selector list. This should not actually be required,
// because the selector list has a length field. Unfortunately, the GCC
// runtime decides to ignore the length field and expects a NULL terminator,
// and GCC cooperates with this by always setting the length to 0.
Elements.push_back(NULLPtr);
Elements.push_back(NULLPtr);
Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
Elements.clear();
// Number of static selectors
Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
".objc_selector_list");
Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
SelStructPtrTy));
// Now that all of the static selectors exist, create pointers to them.
for (unsigned int i=0 ; i<SelectorCount ; i++) {
llvm::Constant *Idxs[] = {Zeros[0],
llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
// FIXME: We're generating redundant loads and stores here!
llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
makeArrayRef(Idxs, 2));
// If selectors are defined as an opaque type, cast the pointer to this
// type.
SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
SelectorAliases[i]->replaceAllUsesWith(SelPtr);
SelectorAliases[i]->eraseFromParent();
}
// Number of classes defined.
Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Classes.size()));
// Number of categories defined
Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
Categories.size()));
// Create an array of classes, then categories, then static object instances
Classes.insert(Classes.end(), Categories.begin(), Categories.end());
// NULL-terminated list of static object instances (mainly constant strings)
Classes.push_back(Statics);
Classes.push_back(NULLPtr);
llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
Elements.push_back(ClassList);
// Construct the symbol table
llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
// The symbol table is contained in a module which has some version-checking
// constants
llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
(RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
Elements.clear();
// Runtime version, used for ABI compatibility checking.
Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
// sizeof(ModuleTy)
llvm::DataLayout td(&TheModule);
Elements.push_back(
llvm::ConstantInt::get(LongTy,
td.getTypeSizeInBits(ModuleTy) /
CGM.getContext().getCharWidth()));
// The path to the source file where this module was declared
SourceManager &SM = CGM.getContext().getSourceManager();
const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
std::string path =
std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
Elements.push_back(SymTab);
if (RuntimeVersion >= 10)
switch (CGM.getLangOpts().getGC()) {
case LangOptions::GCOnly:
Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
break;
case LangOptions::NonGC:
if (CGM.getLangOpts().ObjCAutoRefCount)
Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
else
Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
break;
case LangOptions::HybridGC:
Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
break;
}
llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
// Create the load function calling the runtime entry point with the module
// structure
llvm::Function * LoadFunction = llvm::Function::Create(
llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
llvm::GlobalValue::InternalLinkage, ".objc_load_function",
&TheModule);
llvm::BasicBlock *EntryBB =
llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
CGBuilderTy Builder(VMContext);
Builder.SetInsertPoint(EntryBB);
llvm::FunctionType *FT =
llvm::FunctionType::get(Builder.getVoidTy(),
llvm::PointerType::getUnqual(ModuleTy), true);
llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
Builder.CreateCall(Register, Module);
if (!ClassAliases.empty()) {
llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
llvm::FunctionType *RegisterAliasTy =
llvm::FunctionType::get(Builder.getVoidTy(),
ArgTypes, false);
llvm::Function *RegisterAlias = llvm::Function::Create(
RegisterAliasTy,
llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
&TheModule);
llvm::BasicBlock *AliasBB =
llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
llvm::BasicBlock *NoAliasBB =
llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
// Branch based on whether the runtime provided class_registerAlias_np()
llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
llvm::Constant::getNullValue(RegisterAlias->getType()));
Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
// The true branch (has alias registration function):
Builder.SetInsertPoint(AliasBB);
// Emit alias registration calls:
for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
iter != ClassAliases.end(); ++iter) {
llvm::Constant *TheClass =
TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
true);
if (TheClass) {
TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
Builder.CreateCall2(RegisterAlias, TheClass,
MakeConstantString(iter->second));
}
}
// Jump to end:
Builder.CreateBr(NoAliasBB);
// Missing alias registration function, just return from the function:
Builder.SetInsertPoint(NoAliasBB);
}
Builder.CreateRetVoid();
return LoadFunction;
}
llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
const ObjCContainerDecl *CD) {
const ObjCCategoryImplDecl *OCD =
dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
StringRef CategoryName = OCD ? OCD->getName() : "";
StringRef ClassName = CD->getName();
Selector MethodName = OMD->getSelector();
bool isClassMethod = !OMD->isInstanceMethod();
CodeGenTypes &Types = CGM.getTypes();
llvm::FunctionType *MethodTy =
Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
MethodName, isClassMethod);
llvm::Function *Method
= llvm::Function::Create(MethodTy,
llvm::GlobalValue::InternalLinkage,
FunctionName,
&TheModule);
return Method;
}
llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
return GetPropertyFn;
}
llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
return SetPropertyFn;
}
llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
bool copy) {
return nullptr;
}
llvm::Constant *CGObjCGNU::GetGetStructFunction() {
return GetStructPropertyFn;
}
llvm::Constant *CGObjCGNU::GetSetStructFunction() {
return SetStructPropertyFn;
}
llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
return nullptr;
}
llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
return nullptr;
}
llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
return EnumerationMutationFn;
}
void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
const ObjCAtSynchronizedStmt &S) {
EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
}
void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
const ObjCAtTryStmt &S) {
// Unlike the Apple non-fragile runtimes, which also uses
// unwind-based zero cost exceptions, the GNU Objective C runtime's
// EH support isn't a veneer over C++ EH. Instead, exception
// objects are created by objc_exception_throw and destroyed by
// the personality function; this avoids the need for bracketing
// catch handlers with calls to __blah_begin_catch/__blah_end_catch
// (or even _Unwind_DeleteException), but probably doesn't
// interoperate very well with foreign exceptions.
//
// In Objective-C++ mode, we actually emit something equivalent to the C++
// exception handler.
EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
return ;
}
void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
const ObjCAtThrowStmt &S,
bool ClearInsertionPoint) {
llvm::Value *ExceptionAsObject;
if (const Expr *ThrowExpr = S.getThrowExpr()) {
llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
ExceptionAsObject = Exception;
} else {
assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
"Unexpected rethrow outside @catch block.");
ExceptionAsObject = CGF.ObjCEHValueStack.back();
}
ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
llvm::CallSite Throw =
CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
Throw.setDoesNotReturn();
CGF.Builder.CreateUnreachable();
if (ClearInsertionPoint)
CGF.Builder.ClearInsertionPoint();
}
llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
llvm::Value *AddrWeakObj) {
CGBuilderTy &B = CGF.Builder;
AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
return B.CreateCall(WeakReadFn, AddrWeakObj);
}
void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
llvm::Value *src, llvm::Value *dst) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
dst = EnforceType(B, dst, PtrToIdTy);
B.CreateCall2(WeakAssignFn, src, dst);
}
void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
llvm::Value *src, llvm::Value *dst,
bool threadlocal) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
dst = EnforceType(B, dst, PtrToIdTy);
if (!threadlocal)
B.CreateCall2(GlobalAssignFn, src, dst);
else
// FIXME. Add threadloca assign API
llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
}
void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
llvm::Value *src, llvm::Value *dst,
llvm::Value *ivarOffset) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
dst = EnforceType(B, dst, IdTy);
B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
}
void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
llvm::Value *src, llvm::Value *dst) {
CGBuilderTy &B = CGF.Builder;
src = EnforceType(B, src, IdTy);
dst = EnforceType(B, dst, PtrToIdTy);
B.CreateCall2(StrongCastAssignFn, src, dst);
}
void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
llvm::Value *DestPtr,
llvm::Value *SrcPtr,
llvm::Value *Size) {
CGBuilderTy &B = CGF.Builder;
DestPtr = EnforceType(B, DestPtr, PtrTy);
SrcPtr = EnforceType(B, SrcPtr, PtrTy);
B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
}
llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
const ObjCInterfaceDecl *ID,
const ObjCIvarDecl *Ivar) {
const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
+ '.' + Ivar->getNameAsString();
// Emit the variable and initialize it with what we think the correct value
// is. This allows code compiled with non-fragile ivars to work correctly
// when linked against code which isn't (most of the time).
llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
if (!IvarOffsetPointer) {
// This will cause a run-time crash if we accidentally use it. A value of
// 0 would seem more sensible, but will silently overwrite the isa pointer
// causing a great deal of confusion.
uint64_t Offset = -1;
// We can't call ComputeIvarBaseOffset() here if we have the
// implementation, because it will create an invalid ASTRecordLayout object
// that we are then stuck with forever, so we only initialize the ivar
// offset variable with a guess if we only have the interface. The
// initializer will be reset later anyway, when we are generating the class
// description.
if (!CGM.getContext().getObjCImplementation(
const_cast<ObjCInterfaceDecl *>(ID)))
Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
/*isSigned*/true);
// Don't emit the guess in non-PIC code because the linker will not be able
// to replace it with the real version for a library. In non-PIC code you
// must compile with the fragile ABI if you want to use ivars from a
// GCC-compiled class.
if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
Int32Ty, false,
llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
IvarOffsetGV, Name);
} else {
IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
llvm::Type::getInt32PtrTy(VMContext), false,
llvm::GlobalValue::ExternalLinkage, nullptr, Name);
}
}
return IvarOffsetPointer;
}
LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
QualType ObjectTy,
llvm::Value *BaseValue,
const ObjCIvarDecl *Ivar,
unsigned CVRQualifiers) {
const ObjCInterfaceDecl *ID =
ObjectTy->getAs<ObjCObjectType>()->getInterface();
return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
EmitIvarOffset(CGF, ID, Ivar));
}
static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
const ObjCInterfaceDecl *OID,
const ObjCIvarDecl *OIVD) {
for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
next = next->getNextIvar()) {
if (OIVD == next)
return OID;
}
// Otherwise check in the super class.
if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
return FindIvarInterface(Context, Super, OIVD);
return nullptr;
}
llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar) {
if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
if (RuntimeVersion < 10)
return CGF.Builder.CreateZExtOrBitCast(
CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
PtrDiffTy);
std::string name = "__objc_ivar_offset_value_" +
Interface->getNameAsString() +"." + Ivar->getNameAsString();
llvm::Value *Offset = TheModule.getGlobalVariable(name);
if (!Offset)
Offset = new llvm::GlobalVariable(TheModule, IntTy,
false, llvm::GlobalValue::LinkOnceAnyLinkage,
llvm::Constant::getNullValue(IntTy), name);
Offset = CGF.Builder.CreateLoad(Offset);
if (Offset->getType() != PtrDiffTy)
Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
return Offset;
}
uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
}
CGObjCRuntime *
clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
case ObjCRuntime::GNUstep:
return new CGObjCGNUstep(CGM);
case ObjCRuntime::GCC:
return new CGObjCGCC(CGM);
case ObjCRuntime::ObjFW:
return new CGObjCObjFW(CGM);
case ObjCRuntime::FragileMacOSX:
case ObjCRuntime::MacOSX:
case ObjCRuntime::iOS:
llvm_unreachable("these runtimes are not GNU runtimes");
}
llvm_unreachable("bad runtime");
}
|
{
"content_hash": "9c107dec6f560508e86b2bcf851e033f",
"timestamp": "",
"source": "github",
"line_count": 2851,
"max_line_length": 90,
"avg_line_length": 43.59312521922133,
"alnum_prop": 0.6747851694506131,
"repo_name": "Rapier-Foundation/rapier-script",
"id": "c0dc3b8002d8afff43c108f6e01bfd0eb1888e10",
"size": "124284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/rapierlang/lib/CodeGen/CGObjCGNU.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "1429"
},
{
"name": "Assembly",
"bytes": "13988"
},
{
"name": "Batchfile",
"bytes": "10286"
},
{
"name": "C",
"bytes": "7566017"
},
{
"name": "C#",
"bytes": "12133"
},
{
"name": "C++",
"bytes": "39435677"
},
{
"name": "CMake",
"bytes": "69644"
},
{
"name": "CSS",
"bytes": "22918"
},
{
"name": "Cuda",
"bytes": "31200"
},
{
"name": "Emacs Lisp",
"bytes": "15377"
},
{
"name": "FORTRAN",
"bytes": "7033"
},
{
"name": "Groff",
"bytes": "9943"
},
{
"name": "HTML",
"bytes": "1148463"
},
{
"name": "JavaScript",
"bytes": "24233"
},
{
"name": "LLVM",
"bytes": "688"
},
{
"name": "Limbo",
"bytes": "755"
},
{
"name": "M",
"bytes": "2529"
},
{
"name": "Makefile",
"bytes": "93929"
},
{
"name": "Mathematica",
"bytes": "5122"
},
{
"name": "Matlab",
"bytes": "40309"
},
{
"name": "Mercury",
"bytes": "1222"
},
{
"name": "Objective-C",
"bytes": "4355070"
},
{
"name": "Objective-C++",
"bytes": "1428214"
},
{
"name": "Perl",
"bytes": "102454"
},
{
"name": "Python",
"bytes": "470720"
},
{
"name": "Shell",
"bytes": "6997"
}
],
"symlink_target": ""
}
|
package com.hazelcast.spi.impl.sequence;
import com.hazelcast.core.HazelcastOverloadException;
import com.hazelcast.internal.util.ConcurrencyDetection;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.RequireAssertEnabled;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class FailFastCallIdSequenceTest extends HazelcastTestSupport {
@Test
public void testGettersAndDefaults() {
CallIdSequence sequence = new FailFastCallIdSequence(100, ConcurrencyDetection.createDisabled());
assertEquals(0, sequence.getLastCallId());
assertEquals(100, sequence.getMaxConcurrentInvocations());
}
@Test
public void whenNext_thenSequenceIncrements() {
CallIdSequence sequence = new FailFastCallIdSequence(100, ConcurrencyDetection.createDisabled());
long oldSequence = sequence.getLastCallId();
long result = sequence.next();
assertEquals(oldSequence + 1, result);
assertEquals(oldSequence + 1, sequence.getLastCallId());
}
@Test(expected = HazelcastOverloadException.class)
public void next_whenNoCapacity_thenThrowException() throws InterruptedException {
CallIdSequence sequence = new FailFastCallIdSequence(1, ConcurrencyDetection.createDisabled());
// take the only slot available
sequence.next();
// this next is going to fail with an exception
sequence.next();
}
@Test
public void when_overCapacityButPriorityItem_then_noException() {
CallIdSequence sequence = new FailFastCallIdSequence(1, ConcurrencyDetection.createDisabled());
// take the only slot available
assertEquals(1, sequence.next());
assertEquals(2, sequence.forceNext());
}
@Test
public void whenComplete_thenTailIncrements() {
FailFastCallIdSequence sequence = new FailFastCallIdSequence(100, ConcurrencyDetection.createDisabled());
sequence.next();
long oldSequence = sequence.getLastCallId();
long oldTail = sequence.getTail();
sequence.complete();
assertEquals(oldSequence, sequence.getLastCallId());
assertEquals(oldTail + 1, sequence.getTail());
}
@Test(expected = AssertionError.class)
@RequireAssertEnabled
public void complete_whenNoMatchingNext() {
CallIdSequence sequence = new FailFastCallIdSequence(100, ConcurrencyDetection.createDisabled());
sequence.next();
sequence.complete();
sequence.complete();
}
}
|
{
"content_hash": "ebb929db06fff59a478110655223d0b1",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 113,
"avg_line_length": 35.18292682926829,
"alnum_prop": 0.7327556325823223,
"repo_name": "mdogan/hazelcast",
"id": "eae89d87a8a116ae7020cf9e81e0a6530f333691",
"size": "3510",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hazelcast/src/test/java/com/hazelcast/spi/impl/sequence/FailFastCallIdSequenceTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1862"
},
{
"name": "C",
"bytes": "3721"
},
{
"name": "Java",
"bytes": "45797218"
},
{
"name": "Shell",
"bytes": "30002"
}
],
"symlink_target": ""
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.cdn.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/** Defines values for QueryStringCachingBehavior. */
public enum QueryStringCachingBehavior {
/** Enum value IgnoreQueryString. */
IGNORE_QUERY_STRING("IgnoreQueryString"),
/** Enum value BypassCaching. */
BYPASS_CACHING("BypassCaching"),
/** Enum value UseQueryString. */
USE_QUERY_STRING("UseQueryString"),
/** Enum value NotSet. */
NOT_SET("NotSet");
/** The actual serialized value for a QueryStringCachingBehavior instance. */
private final String value;
QueryStringCachingBehavior(String value) {
this.value = value;
}
/**
* Parses a serialized value to a QueryStringCachingBehavior instance.
*
* @param value the serialized value to parse.
* @return the parsed QueryStringCachingBehavior object, or null if unable to parse.
*/
@JsonCreator
public static QueryStringCachingBehavior fromString(String value) {
QueryStringCachingBehavior[] items = QueryStringCachingBehavior.values();
for (QueryStringCachingBehavior item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
}
|
{
"content_hash": "6b34eeee13d366c0f1061dfa3f630fb5",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 88,
"avg_line_length": 30.132075471698112,
"alnum_prop": 0.6812773951158422,
"repo_name": "selvasingh/azure-sdk-for-java",
"id": "01ffa53248122e5ffa8c35f5d099edf39fbd0dca",
"size": "1597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/models/QueryStringCachingBehavior.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "29891970"
},
{
"name": "JavaScript",
"bytes": "6198"
},
{
"name": "PowerShell",
"bytes": "160"
},
{
"name": "Shell",
"bytes": "609"
}
],
"symlink_target": ""
}
|
<!doctype html>
<html <?php language_attributes(); ?> class="no-js">
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title>
<!-- dns prefetch -->
<link href="//www.google-analytics.com" rel="dns-prefetch">
<!-- meta -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="description" content="<?php bloginfo('description'); ?>">
<!-- icons -->
<link href="<?php echo get_template_directory_uri(); ?>/icons/favicon.ico" rel="shortcut icon">
<link href="<?php echo get_template_directory_uri(); ?>/icons/touch.png" rel="apple-touch-icon-precomposed">
<!-- css + javascript -->
<?php wp_head(); ?>
<!-- google fonts -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,800,700,600,300' rel='stylesheet' type='text/css'>
</head>
<body <?php body_class(); ?> style="
background-color: <?php echo of_get_option( 'background_color', '#fff' ); ?>;
background-image: url('<?php echo of_get_option( 'background_image' ); ?>');
background-repeat:<?php echo of_get_option( 'background_tiling' ); ?>;
background-attachment:<?php echo of_get_option( 'background_image' ); ?>;
background-position:<?php echo of_get_option( 'background_position', 'left top' ); ?>;
background-size:<?php echo of_get_option( 'background_size' ); ?>;
background-attachment:<?php if ( of_get_option( 'fix_image' ) == 1) {echo 'fixed'; } else { echo 'inherit'; }; ?>;
">
<?php if (of_get_option( 'use_wrapper' ) == 1 ) {
echo '<div id="page-wrapper" style="background-color:'. of_get_option( 'wrapper_color', '#fff' ) .';">';
} ?>
<nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<?php topbar(); ?>
</div>
</nav>
<div class="bg-page-head">
<div class="container page-head">
<div class="row">
<div class="col-sm-12">
<a class="top-logo" href="<?php echo home_url(); ?>">
<span class="inzite-inzite_tagline"></span>
</a>
</div>
</div>
</div>
</div>
|
{
"content_hash": "2fd24a84ba3e26e79bcc926599c3ad43",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 167,
"avg_line_length": 41.17910447761194,
"alnum_prop": 0.5944182674882204,
"repo_name": "Jursdotme/toro",
"id": "04497486f87ff036c25adab3413a2301f8608006",
"size": "2759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "header.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "297897"
},
{
"name": "JavaScript",
"bytes": "23142"
},
{
"name": "PHP",
"bytes": "313133"
}
],
"symlink_target": ""
}
|
/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('fullscreen', 'en,tr,sv,cs,fr_ca,zh_cn,da,he,nb,de,hu,ru,ru_KOI8-R,ru_UTF-8,nn,es,cy,is,pl,nl,fr,pt_br');
var TinyMCE_FullScreenPlugin = {
getInfo : function() {
return {
longname : 'Fullscreen',
author : 'Moxiecode Systems',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_fullscreen.html',
version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
};
},
getControlHTML : function(cn) {
switch (cn) {
case "fullscreen":
return tinyMCE.getButtonHTML(cn, 'lang_fullscreen_desc', '{$pluginurl}/images/fullscreen.gif', 'mceFullScreen');
}
return "";
},
execCommand : function(editor_id, element, command, user_interface, value) {
// Handle commands
switch (command) {
case "mceFullScreen":
if (tinyMCE.getParam('fullscreen_is_enabled')) {
// In fullscreen mode
window.opener.tinyMCE.execInstanceCommand(tinyMCE.getParam('fullscreen_editor_id'), 'mceSetContent', false, tinyMCE.getContent(editor_id));
top.close();
} else {
tinyMCE.setWindowArg('editor_id', editor_id);
var win = window.open(tinyMCE.baseURL + "/plugins/fullscreen/fullscreen.htm", "mceFullScreenPopup", "fullscreen=yes,menubar=no,toolbar=no,scrollbars=no,resizable=yes,left=0,top=0,width=" + screen.availWidth + ",height=" + screen.availHeight);
try { win.resizeTo(screen.availWidth, screen.availHeight); } catch (e) {}
}
return true;
}
// Pass to next handler in chain
return false;
},
handleNodeChange : function(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) {
if (tinyMCE.getParam('fullscreen_is_enabled'))
tinyMCE.switchClass(editor_id + '_fullscreen', 'mceButtonSelected');
return true;
}
};
tinyMCE.addPlugin("fullscreen", TinyMCE_FullScreenPlugin);
|
{
"content_hash": "61f66eeb4d637ba40a571cc7a5c734a2",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 247,
"avg_line_length": 33.857142857142854,
"alnum_prop": 0.6962025316455697,
"repo_name": "jikuindia/ona",
"id": "90c5841154b0a85597f98d44e19068ad104167bf",
"size": "2098",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/main/webapp/Editor/jscripts/tiny_mce/plugins/fullscreen/editor_plugin_src.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "56358"
},
{
"name": "Java",
"bytes": "67611"
},
{
"name": "JavaScript",
"bytes": "929308"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Wed May 05 11:17:09 PDT 2010 -->
<TITLE>
org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans (Pig 0.7.0 API)
</TITLE>
<META NAME="date" CONTENT="2010-05-05">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../../../../org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/plans/package-summary.html" target="classFrame">org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="DotMRPrinter.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">DotMRPrinter</A>
<BR>
<A HREF="DotMRPrinter.InnerOperator.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">DotMRPrinter.InnerOperator</A>
<BR>
<A HREF="DotMRPrinter.InnerPlan.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">DotMRPrinter.InnerPlan</A>
<BR>
<A HREF="EndOfAllInputSetter.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">EndOfAllInputSetter</A>
<BR>
<A HREF="MROperPlan.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">MROperPlan</A>
<BR>
<A HREF="MROpPlanVisitor.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">MROpPlanVisitor</A>
<BR>
<A HREF="MRPrinter.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">MRPrinter</A>
<BR>
<A HREF="POPackageAnnotator.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">POPackageAnnotator</A>
<BR>
<A HREF="UDFFinder.html" title="class in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans" target="classFrame">UDFFinder</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
|
{
"content_hash": "ceb0aa2910ec3b01f13ad7e3d465e909",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 219,
"avg_line_length": 49.875,
"alnum_prop": 0.7514619883040936,
"repo_name": "hirohanin/pig7hadoop21",
"id": "757f633b14248a90f0f0e4e5b217514fcec03c68",
"size": "2394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/api/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/plans/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
module TimeSpanner
class TimeUnitCollector
include TimeUnits
include Errors
AVAILABLE_UNITS = [
:millenniums,
:centuries,
:decades,
:years,
:months,
:weeks,
:days,
:hours,
:minutes,
:seconds,
:milliseconds,
:microseconds,
:nanoseconds
]
attr_reader :unit_names
attr_accessor :units
def initialize(unit_names = [])
@unit_names = collect_unit_names(unit_names)
@units = []
validate_unit_names!
collect!
end
private
def collect!
unit_names.each do |name|
units << unit_by_name(name)
end
end
def unit_by_name name
case name
when :millenniums then Millennium
when :centuries then Century
when :decades then Decade
when :years then Year
when :months then Month
when :weeks then Week
when :days then Day
when :hours then Hour
when :minutes then Minute
when :seconds then Second
when :milliseconds then Millisecond
when :microseconds then Microsecond
when :nanoseconds then Nanosecond
end
end
def collect_unit_names unit_names
!unit_names || unit_names.compact.empty? ? AVAILABLE_UNITS : unit_names
end
def validate_unit_names!
unit_names.each do |unit_name|
raise InvalidUnitError, "Unit '#{unit_name}' is not a valid time unit." unless AVAILABLE_UNITS.include?(unit_name)
end
end
end
end
|
{
"content_hash": "a6ff8905d9d8954de2bb39cab9952354",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 122,
"avg_line_length": 22.130434782608695,
"alnum_prop": 0.6005239030779306,
"repo_name": "shlub/time_spanner",
"id": "a4538c0b3c6334683de8725e79200a0dae98c9a6",
"size": "1527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/time_spanner/time_unit_collector.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "48549"
}
],
"symlink_target": ""
}
|
use std::sync::{RwLock, Mutex, Arc};
use std::net::{UdpSocket, IpAddr, SocketAddr};
use std::io;
use std::cmp::min;
use openssl::ssl::{SslAcceptor};
use std::io::{Write, Cursor};
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::mem;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use toml;
use time;
use common::{Result, ErrorLevel, HexBuf, read_string, write_string};
use constants::*;
use data::{DataChan, DataPacket};
use client::{Client, DataStats, ToAck, ToGetAcked, Ping};
use tls::{TlsState, acceptor_from_config};
use settings::{ServerSettings, ClientSettings, NetworkSide};
use vpncrypto::KeySource;
use pool::{PoolManager, pool_from_config};
type Packet = Vec<u8>;
type PacketSender = mpsc::Sender<Packet>;
/// Server shared state
pub struct Server {
pub server_name: String,
pub local_tun_addresses: Vec<IpAddr>,
pub settings: ServerSettings,
pub ssl_acceptor: Mutex<SslAcceptor>,
pub clients: RwLock<Vec<Arc<Client>>>,
pub data_stats: RwLock<DataStats>,
pub pool: Mutex<Box<PoolManager + Send>>,
}
impl Server {
pub fn new(name: &str, config: &toml::value::Table) -> Server {
let pool = pool_from_config(config.get("pool")
.and_then(|x| x.as_table())
.expect("Require server.pool table"));
pool.allocate_server_ip();
let settings = toml::Value::Table(config.clone()).try_into().unwrap();
Server {
server_name: name.to_owned(),
local_tun_addresses: pool.allocate_server_ip(),
settings: settings,
ssl_acceptor: Mutex::new(acceptor_from_config(config)),
clients: RwLock::new(Vec::new()),
data_stats: RwLock::new(DataStats::new()),
pool: Mutex::new(pool),
}
}
pub fn kill_client(&self, addr: SocketAddr, sid: Option<u64>) -> usize {
if self.find_client(addr, sid).is_none() {
return 0;
}
let mut write_lock = self.clients.write().unwrap();
let mut count = 0;
loop {
let removed = (*write_lock).iter()
.filter(|c| sid.is_none() || c.remote_session_id == sid.unwrap())
.position(|c| c.socket_addr == addr)
.map(|i| (*write_lock).remove(i))
.is_some();
if removed {
count += 1;
} else {
break
}
}
count
}
pub fn find_client(&self, addr: SocketAddr, sid: Option<u64>) -> Option<Arc<Client>> {
let lock = self.clients.read().unwrap();
for c in &*lock {
if let Some(sid_) = sid {
if sid_ != c.remote_session_id {
continue;
}
}
if c.socket_addr == addr {
return Some(c.clone());
}
}
None
}
pub fn find_client_by_local_ip(&self, addr: IpAddr) -> Option<Arc<Client>> {
let lock = self.clients.read().unwrap();
(*lock).iter().find(|x| x.has_addr(&addr)).cloned()
}
fn sync_tls(&self, client: &Client, ctrl_tls: &mut TlsState) -> io::Result<()> {
match ctrl_tls.get_outgoing() {
Some(data) => {
// headers + up to 2 ACKs (Why 2? it feels like a good idea)
let max_size = self.settings.link_mtu - 14 - 8*3;
debug!("{} Control output: {} bytes, {} bytes chunks", client, data.len(), max_size);
for c in data.chunks(max_size) {
self.send_control_packet(client, Opcode::ControlV1, c)?;
}
Ok(())
}
None => Ok(()),
}
}
pub fn process_incomming_acks(&self, client: &Client, acks: &[u32], local_sessid: u64) -> Result<()> {
if local_sessid != client.local_session_id {
return packet_error!(format!("Unexpected ACK sessid: {:x} {:x}", client.local_session_id, local_sessid));
}
let mut resend_queue = client.to_get_acked.lock().unwrap();
for pid in acks {
let removed = resend_queue.iter()
.position(|n| n.pid == *pid)
.map(|e| resend_queue.remove(e))
.is_some();
trace!("{} Processing ACK: {} / {:?} ({})", client, pid, acks, removed);
}
Ok(())
}
/// Handles packets sent to the tun interface
pub fn handle_outside_packet(&self, _from_addr: IpAddr, to_addr: IpAddr, data: &[u8]) -> Result<()> {
let lock = self.clients.read().unwrap();
let client = {
match (*lock).iter().find(|x| x.has_addr(&to_addr)) {
Some(c) => c,
None => return packet_error!("Unknown session"),
}
};
self.send_data_packet(&*client, data)
}
/// Handles packets sent to the OpenVPN server port
/// Mainly routes them to handle_tunnel_control/data
pub fn handle_tunnel_packet(&self, socket: &UdpSocket, addr: SocketAddr, data: &[u8], tun_channel: &PacketSender) -> Result<()> {
let packet_len = data.len();
let mut data = Cursor::new(data);
if packet_len < 1 {
return packet_error!("Incomplete packet (no opcode)");
}
let opcode = data.read_u8().unwrap() >> 3;
trace!("Incoming packet: opcode={} length={}", opcode, packet_len);
let result = if CONTROL_OPCODES.contains(&opcode) {
self.handle_tunnel_control(opcode, socket, addr, &mut data)
} else if DATA_OPCODES.contains(&opcode) {
self.handle_tunnel_data(opcode, addr, &mut data, tun_channel)
} else {
return packet_error!(format!("Unknown opcode {} (cannot route)", opcode));
};
if let Err(ref e) = result {
if e.level == ErrorLevel::SessionError {
// TODO: we don't track the session ID here, it will kill all sessions
// on the same (ip, port)
let n = self.kill_client(addr, None);
trace!("SessionError received, killed {} sessions.", n);
}
}
result
}
fn handle_tunnel_control(&self, opcode: u8, socket: &UdpSocket, addr: SocketAddr, data: &mut Cursor<&[u8]>) -> Result<()> {
let packet_len = data.get_ref().len();
// P_ACK packets are shorter
let min_packet_len = if opcode == Opcode::Ack as u8 { 10 } else { 14 };
// Minimal packet size
if packet_len < min_packet_len {
return packet_error!("Incomplete packet (control minimal)");
}
let session_id = data.read_u64::<BigEndian>().unwrap();
// <-- TLS-Auth HMAC here
// Find the client
let reset1 = Opcode::ControlHardResetClientV1 as u8;
let reset2 = Opcode::ControlHardResetClientV2 as u8;
let client = if opcode == reset1 || opcode == reset2 {
self.kill_client(addr, Some(session_id));
None
} else {
self.find_client(addr, Some(session_id))
};
let client: Arc<Client> = match client {
Some(c) => {
c
},
None => {
// Only create new Clients on a HARD RESET
if opcode != reset1 && opcode != reset2 {
return packet_error!(format!("Unknown session ID (opcode {})", opcode));
}
let socket_clone = match socket.try_clone() {
Ok(s) => s,
Err(e) => return session_error!("Couldnt clone socket", e),
};
let c = Arc::new(Client::new(socket_clone, addr, session_id));
info!("New client: {} lsess={:x} rsess={:x}", c, (*c).local_session_id, session_id);
let mut lock = self.clients.write().unwrap();
(*lock).push(c.clone());
c
}
};
let client: &Client = &*client;
// Decode and handle ACKs
// [1B] N, [4B*N] ACKs, [8B if N>0] session ID
{
let n_acks = data.read_u8().unwrap() as usize;
if n_acks > MAX_ACKS {
return packet_error!(format!("Too many ACKs ({})", n_acks));
}
if n_acks > 0 {
if packet_len < (min_packet_len + n_acks*4 + 8) {
return packet_error!(format!("Incomplete packet (acks)"));
}
let mut acks: Vec<u32> = Vec::new();
for _ in 0..n_acks {
acks.push(data.read_u32::<BigEndian>().unwrap());
}
let remote_session_id = data.read_u64::<BigEndian>().unwrap();
try!(self.process_incomming_acks(&*client, acks.as_slice(), remote_session_id));
}
}
if opcode == Opcode::Ack as u8 {
// P_ACK have no packet ID, we can stop to parse here
// incomming ACKs have been processed before, and there is nothing
// left to do with it.
return Ok(());
}
let pid = data.read_u32::<BigEndian>().unwrap();
let payload = cursor_slice!(data);
{
let stored_pid = client.remote_pid.load(Ordering::Relaxed) as u32;
if pid > stored_pid {
return packet_error!(format!("Received future PID {} ({})", pid, stored_pid));
}
if pid < stored_pid {
return packet_error!(format!("Received old PID {} ({})", pid, stored_pid));
}
client.remote_pid.fetch_add(1, Ordering::Relaxed) as u32;
}
client.to_ack.lock().unwrap().push(ToAck { time: time::get_time(), pid: pid });
match opcode {
x if x == Opcode::ControlHardResetClientV1 as u8 => {
return packet_error!("Unsupported HARD_RESET V1");
},
x if x == Opcode::ControlHardResetClientV2 as u8 => {
trace!("{} Received HARD_RESET", client);
self.send_control_packet(client, Opcode::ControlHardResetServerV2, &EMPTY_VEC)?;
},
x if x == Opcode::ControlV1 as u8 => {
self.handle_control(&*client, payload)?;
},
x => return packet_error!(format!("Unsupported opcode {}", x)),
}
// Each sent control packet will embed a few ACKs and pop items from the queue
// but if we still have packets to ack for some reason:
{
let to_ack_queue = (*(client.to_ack.lock().unwrap())).len();
if to_ack_queue > 0 {
debug!("{} The ACK queue contains {} items, sending dedicated ACK", client, to_ack_queue);
self.send_control_packet(&*client, Opcode::Ack, &EMPTY_VEC)?;
}
}
Ok(())
}
/// Handle incoming VPN tunnel data (data channel)
pub fn handle_tunnel_data(&self, opcode: u8, addr: SocketAddr, data: &mut Cursor<&[u8]>, tun_channel: &PacketSender) -> Result<()> {
if opcode != Opcode::DataV1 as u8 {
return packet_error!("Unsupported DATA_V2");
}
let client = match self.find_client(addr, None) {
Some(c) => c,
None => return packet_error!("Unknown session."),
};
let lock = client.data_chan.read().unwrap();
if let Some(ref data_channel) = *lock {
// Much faster than allocating a Vec or the default initializer
// https://gist.github.com/0xa/820435877d1b5ff424fcf122d71dd3b0
let mut plaintext_buffer: [u8; HARD_MTU] = unsafe { mem::zeroed() };
match data_channel.decode(&*client, data, &mut plaintext_buffer)? {
DataPacket::Data(data) => {
let data_len = data.len();
// FIXME: check for source IP
// FIXME: find a way not to copy. pls.
tun_channel.send(data.into_owned()).unwrap();
{
let mut lock = client.data_stats.lock().unwrap();
(*lock).up_bytes += data_len;
(*lock).up_packets += 1;
}
trace!("{} data: sent {} bytes", client, data_len);
}
DataPacket::Ping => {
let mut lock = client.last_received_ping.lock().unwrap();
(*lock) = Some(Ping { time: time::get_time() } );
}
}
return Ok(())
}
// TODO: maybe add that to a queue
return packet_error!("Data channel not open");
}
/// Handles a P_CONTROLV1 packet and passes encrypted data to the user's
/// TLS stream. If needed, also tried to do the handshake and writes pending
/// data
pub fn handle_control(&self, client: &Client, data: &[u8]) -> Result<()> {
debug!("{} Control IO: {} bytes", client, data.len());
// pass to TLS stream
if data.len() == 0 {
return Ok(());
}
let mut tls_lock = client.ctrl_ssl.lock().unwrap();
let tls: &mut TlsState = &mut *tls_lock;
// TLS session state and input management
// Feed data, if not ready try the handshake (again)
tls.update(data, &self.ssl_acceptor)?;
// Replies waiting to be sent
self.sync_tls(client, tls)?;
// Incoming decrypted data
match tls.get_plaintext() {
Some(data) => {
//FIXME: cursor_slice size check
let data_slice = data.as_slice();
let header = &data_slice[0..4];
let content = &data_slice[4..];
match header {
b"\x00\x00\x00\x00" => self.handle_client_auth(client, tls, content)?,
b"PUSH" => self.handle_push_message(client, tls, content)?,
_ => return packet_error!("Invalid control message header"),
}
},
None => (),
}
Ok(())
}
pub fn handle_push_message(&self, client: &Client, ctrl_tls: &mut TlsState, data: &[u8]) -> Result<()> {
// FIXME: check data
let lock = client.data_chan.read().unwrap();
if let Some(ref data_channel) = *lock {
let mut push = String::new();
push.push_str("PUSH_REPLY");
push.push_str(&format!(",ifconfig {} 255.255.255.0", data_channel.ip_addresses[0]));
trace!("{}: {}", client, push);
push.push('\0');
self.send_control_message(client, ctrl_tls, push.as_bytes())?;
return Ok(())
}
packet_error!("Data channel closed")
}
pub fn handle_client_auth(&self, client: &Client, ctrl_tls: &mut TlsState, data: &[u8]) -> Result<()> {
let mut data = Cursor::new(data);
if data.get_ref().len() < 113 {
return packet_error!("Incomplete key negotiation message");
}
let key_method = data.read_u8()?;
if key_method != 2 {
self.send_control_message(client, ctrl_tls, b"AUTH_FAILED\0")?;
return session_error!(format!("Unsupported key method: {}", key_method));
}
let ks_data = cursor_slice!(data, 112);
let ks = KeySource::import_full(ks_data);
let options = read_string(&mut data)?.unwrap_or("Missing options from control message".to_owned());
debug!("{} Options: {}", client, options);
let username = read_string(&mut data)?;
let password = read_string(&mut data)?;
let additional = read_string(&mut data)?;
debug!("{} Auth: {:?}/{:?}", client, username, password);
debug!("{} Infos: {:?}", client, additional);
debug!("{} Additional data: {:x}", client, HexBuf(cursor_slice!(data)));
{
let (settings, side) = match ClientSettings::import(&options) {
Ok(r) => r,
Err(e) => {
self.send_control_message(client, ctrl_tls, b"AUTH_FAILED\0")?;
return session_error!("{}", e)
},
};
if side != NetworkSide::Client {
self.send_control_message(client, ctrl_tls, b"AUTH_FAILED\0")?;
return session_error!("Remote side is not a client");
}
let addrs = {
let lock = self.pool.lock().unwrap();
match (*lock).allocate_ip(self, client) {
Ok(r) => r,
Err(r) => {
self.send_control_message(client, ctrl_tls, b"AUTH_FAILED\0")?;
return Err(r);
}
}
};
let dc = DataChan::new(settings, &addrs, ks, client.local_session_id, client.remote_session_id);
debug!("{} Data channel established:", client);
debug!("{} Addresses: {:?}", client, addrs);
trace!("{} l ks: {:x} {:x} {:x}", client, HexBuf(&dc.l_ks.random1), HexBuf(&dc.l_ks.random2), client.local_session_id);
trace!("{} r ks: {:x} {:x} {:x} {:x}", client, HexBuf(&dc.r_ks.random1), HexBuf(&dc.r_ks.random2), client.remote_session_id, HexBuf(&dc.r_ks.pre_master.unwrap()));
debug!("{} r cipher: {:x}", client, HexBuf(&dc.r_cipher_key));
debug!("{} r hmac : {:x}", client, HexBuf(&dc.r_hmac_key));
debug!("{} l cipher: {:x}", client, HexBuf(&dc.l_cipher_key));
debug!("{} l hmac : {:x}", client, HexBuf(&dc.l_hmac_key));
// Reply
let packet_buffer: Vec<u8> = Vec::with_capacity(self.settings.link_mtu);
let mut packet_buffer = Cursor::new(packet_buffer);
packet_buffer.write_all(b"\x00\x00\x00\x00")?;
packet_buffer.write_u8(2)?; // Key method
packet_buffer.write_all(&dc.l_ks.random1)?;
packet_buffer.write_all(&dc.l_ks.random2)?;
write_string(&mut packet_buffer, &settings.export(NetworkSide::Client))?;
self.send_control_message(client, ctrl_tls, packet_buffer.get_ref())?;
{
let mut tslock = client.data_chan.write().unwrap();
(*tslock) = Some(dc);
}
}
Ok(())
}
pub fn send_control_message(&self, client: &Client, ctrl_tls: &mut TlsState, data: &[u8]) -> Result<()> {
if let &mut TlsState::Open(ref mut stream) = ctrl_tls {
stream.write_all(data)?;
trace!("Control TLS: writted {} bytes", data.len());
} else {
return packet_error!("Control TLS channel not open");
}
self.sync_tls(client, ctrl_tls)?;
Ok(())
}
pub fn send_control_packet(&self, client: &Client, opcode: Opcode, data: &[u8]) -> io::Result<()> {
let packet_buffer: Vec<u8> = Vec::with_capacity(self.settings.link_mtu);
let mut packet_buffer = Cursor::new(packet_buffer);
let mut space_left_acks = self.settings.link_mtu - data.len() - 1 - 8 - 4;
packet_buffer.write_u8((opcode as u8) << 3)?;
packet_buffer.write_u64::<BigEndian>(client.local_session_id)?; // FIXME: local session id
trace!("{} Sending control: op {:?}({}) payload {} bytes", client, opcode, opcode as u8, data.len());
// <- HMAC here
// space_left -= 8;
// ACKs
if space_left_acks > 8 + 8 {
let mut lock = client.to_ack.lock().unwrap();
if (*lock).len() > 0 {
space_left_acks -= 9;
assert!(MAX_ACKS_TO_SEND <= 0xff);
let max_acks = min(space_left_acks / 4, MAX_ACKS_TO_SEND);
let acked_count = min((*lock).len(), max_acks);
packet_buffer.write_u8(acked_count as u8)?;
for _ in 0..acked_count {
let pid = (*lock).pop().unwrap().pid;
trace!("{} -> ACK pid {}", client, pid);
packet_buffer.write_u32::<BigEndian>(pid)?;
}
packet_buffer.write_u64::<BigEndian>(client.remote_session_id)?;
} else {
packet_buffer.write_u8(0)?;
}
} else {
packet_buffer.write_u8(0)?;
}
let pid = client.local_pid.fetch_add(1, Ordering::Relaxed) as u32;
packet_buffer.write_u32::<BigEndian>(pid)?; // local packet id
packet_buffer.write_all(data)?;
let packet_buffer = packet_buffer.into_inner();
client.socket.send_to(packet_buffer.as_slice(), &client.socket_addr)?;
{
let mut lock = client.to_get_acked.lock().unwrap();
(*lock).push(ToGetAcked { time: time::get_time(), pid: pid, data: packet_buffer });
}
Ok(())
}
pub fn send_data_packet(&self, client: &Client, data: &[u8]) -> Result<()> {
trace!("{} Sending data: {} bytes", client, data.len());
let lock = client.data_chan.read().unwrap();
if let Some(ref data_channel) = *lock {
let mut packet_buffer: [u8; HARD_MTU] = unsafe { mem::zeroed() };
let packet = {
let packet_len = data_channel.encode(client, data, &mut packet_buffer)?;
&packet_buffer[..packet_len]
};
match client.socket.send_to(packet, &client.socket_addr) {
Ok(_) => {},
Err(e) => return packet_error!("error sending packet", e),
}
{ // Updating tunnel statistics
let mut lock = client.data_stats.lock().unwrap();
(*lock).dn_bytes += data.len();
(*lock).dn_packets += 1;
}
return Ok(())
}
packet_error!("Data channel closed")
}
}
|
{
"content_hash": "1e2e196dc76d2ef0451dbd79484e6760",
"timestamp": "",
"source": "github",
"line_count": 585,
"max_line_length": 175,
"avg_line_length": 37.51111111111111,
"alnum_prop": 0.5108002187386074,
"repo_name": "0xa/ropenvpn",
"id": "264652d31f5fda5db87131725799a0e45f846e85",
"size": "21944",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/server.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "12421"
},
{
"name": "Rust",
"bytes": "88459"
},
{
"name": "Shell",
"bytes": "321"
}
],
"symlink_target": ""
}
|
<?php
namespace Ty666\PictureManager;
use SplFileInfo;
class PictureIdGenerator
{
public function generate($picture = null)
{
if ($picture instanceof SplFileInfo) {
return md5_file($picture->getRealPath());
} elseif (is_string($picture)) {
return md5($picture);
} else {
return md5(uniqid('t', true));
}
}
}
|
{
"content_hash": "c1385ea472a4a6842cb29c80164f9c58",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 53,
"avg_line_length": 20.526315789473685,
"alnum_prop": 0.5717948717948718,
"repo_name": "3tnet/pictureManager",
"id": "3f70e10b0f576ddfff07b44678f3f2136c51fb14",
"size": "390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/PictureIdGenerator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "17988"
}
],
"symlink_target": ""
}
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Abstract parent class for all PMA_GIS_<Geom_type> test classes
*
* @package PhpMyAdmin-test
*/
require_once 'libraries/gis/GIS_Geometry.class.php';
/**
* Abstract parent class for all PMA_GIS_<Geom_type> test classes
*
* @package PhpMyAdmin-test
*/
abstract class PMA_GIS_GeomTest extends PHPUnit_Framework_TestCase
{
/**
* test generateParams method
*
* @param string $wkt point in WKT form
* @param index $index index
* @param array $params expected output array
*
* @dataProvider providerForTestGenerateParams
* @return void
*/
public function testGenerateParams($wkt, $index, $params)
{
if ($index == null) {
$this->assertEquals(
$params,
$this->object->generateParams($wkt)
);
} else {
$this->assertEquals(
$params,
$this->object->generateParams($wkt, $index)
);
}
}
/**
* test scaleRow method
*
* @param string $spatial spatial data of a row
* @param array $min_max expected results
*
* @dataProvider providerForTestScaleRow
* @return void
*/
public function testScaleRow($spatial, $min_max)
{
$this->assertEquals(
$min_max,
$this->object->scaleRow($spatial)
);
}
/**
* Tests whether content is a valid image.
*
* @param object $object Image
*
* @return void
*/
public function assertImage($object)
{
$this->assertGreaterThan(0, imagesx($object));
}
}
?>
|
{
"content_hash": "9976a34b3ef04856dc681a9da934ab80",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 66,
"avg_line_length": 23.041095890410958,
"alnum_prop": 0.5570749108204518,
"repo_name": "sarukuku/ParaChute",
"id": "93cefaf8787c07adac31a198a1a3a15f665ce52d",
"size": "1682",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "parachute/phpMyAdmin/test/classes/gis/PMA_GIS_Geom_test.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2461"
},
{
"name": "CSS",
"bytes": "24199"
},
{
"name": "HTML",
"bytes": "924"
},
{
"name": "JavaScript",
"bytes": "4749790"
},
{
"name": "PHP",
"bytes": "9390028"
},
{
"name": "Perl",
"bytes": "15864"
},
{
"name": "Python",
"bytes": "16292"
},
{
"name": "Shell",
"bytes": "30217"
},
{
"name": "XML",
"bytes": "110224"
}
],
"symlink_target": ""
}
|
FROM balenalib/odroid-c1-debian:jessie-run
ENV NODE_VERSION 15.10.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "ca27a48dd9233b00c49b37a07751395657d4e454ebfa5066a6371e5f6c9969cf node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Jessie \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.10.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
{
"content_hash": "45221e16e0060e4649e6b29a38881b16",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 692,
"avg_line_length": 64.88888888888889,
"alnum_prop": 0.7041095890410959,
"repo_name": "nghiant2710/base-images",
"id": "b6d47a8df0a5f24191efc2de6e044a4d36e820bc",
"size": "2941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/odroid-c1/debian/jessie/15.10.0/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
}
|
nom: Suillus clintonianus
date: 2017-10-27 00:00:00
image: https://c1.staticflickr.com/5/4503/37392611065_7a11befe4d_n.jpg
image-originale: https://www.flickr.com/photos/kaufholtz/37392611065/in/photolist-YYfUwM-YFuRrd-YFuV2u
album-flickr:
- 72157687604988591
details:
nom-francais: Bolet de Clinton
domaine: Eucaryote
regne: Fungi
phylum: Basidiomycota
sous-phylum: Agaricomycotina
classe: Agaricomycetes
sous-classe: Agaricomycetidae
ordre: Boletales
famille: Suillaceae
genre: Suillus
espece: <i>Suillus clintonianus</i> (Peck) Kuntze
litterature: Kuntze, O. 1898. Revisio generum plantarum. 3(2):1-576
collections:
- fongarium: cKc0674
date: 16 septembre 2017
planche:
numero:
miniature: # Largeur 320px. ici
originale: # Exemple: ici
geolocalisation: # Exemple: 46°45'23.55"N 71°19'19.47"O
elevation:
determinee:
confirmee: Claude Kaufholtz-Couture
description:
acanthocytes:
acanthophyses:
aiguillons:
aleurioconidies:
anamorphe:
anamorphe-conidien:
anneau:
apothecie:
arete-lamellaire:
arthroconidies:
articles:
ascome:
ascospores:
asques:
asterohyphidies:
avertissement:
base-du-pied:
base-sterile:
base-stipitiforme:
basides:
basidiospores:
basidioles:
basidiome:
bibliographies:
biotopes: pousse au sol, sous conifères (<i>Larix laricina</i>)
boucles:
brachybasidioles:
calicule:
capillitium:
capitule:
caulobasides:
caulocystides:
caulocystides-medianes:
caulocystides-sommitales:
cauloparacystides:
cellules-hymeniales-diverticulees:
cellules-hymeniales-en-brosses:
cellules-marginales-paracystides:
cellules-peritheciales:
cellules-stromatiques:
chair: jaune orangé pâle, meurtrissant brun rosâtre à la coupe ou au froissement
chancre:
cheilochrysocystides:
cheilocystides:
cheilomacrocystides:
chlamydospores:
chrysocystides:
circumcystides:
clavules:
columelle:
comestibilite:
commentaires:
conidies:
conidiome:
conidiophores:
consistance:
contexte:
cordons-myceliens:
cordons-rhizomorphiques:
cortex:
cortex-caulinaire:
cortex-du-pied-et-du-bulbe:
cortex-peridial:
cortex-sclerotial:
cortine:
coupe-sterile:
cristaux:
cristaux-d-oxalate:
cristaux-apicaux:
cuticule:
cutis:
cycle:
cystides:
cystides-hymeniales:
cystides-intermediaires:
cystidioles:
dendrohyphydies:
depots-de-pigment-interhyphal:
dermatocystides-caulocystides-et-pileipellis:
derniere-correction:
dicaryophyses:
dichophyses:
disque-basal:
distribution: commun
elateres:
elements-acanthophyses:
elements-cystidioides:
elements-hyphoides:
elements-setoides:
elements-steriles:
elements-sur-les-cotes:
elements-velaires:
endoperidium:
especes-identification:
especes-semblables:
excipulum:
excipulum-medullaire-superieur:
excipulum-medullaire-moyen:
excipulum-medullaire-inferieur:
excipulum-ectal:
exhalaison: indistincte à acidulée
exhalaison-de-la-chair:
exhalaison-des-lames:
exoperidium:
extremites-hyphales:
face-externe:
face-poroïde: jaune au début puis jaune olive ou brun olive à maturité, devenant brunâtre lorsque meurtri, adné à déprimé; pores anguleux, 1-3 par mm
feutrage-basal:
fragments-sporaux:
funicule:
glebe:
gleocystides:
gleocystides-hymeniales:
gleocystides-subhymeniales:
granules-calcaires:
groupe:
hymenium:
hymenocystides:
hymenophore:
hyphes:
hyphes-de-la-chair:
hyphes-de-l-anneau:
hyphes-du-pied:
hyphes-glebales:
hyphes-gleopleres:
hyphes-hymeniales:
hyphes-ligatives:
hyphes-oleiferes:
hyphes-pectinees:
hyphes-primordiales:
hyphes-setales:
hyphes-squelettiques:
hyphes-skeletoligative:
hyphes-subiculaires:
hyphes-thrombopleres:
hyphes-tramales:
hyphes-vesiculaires:
hyphidies:
hyphique:
hypobasides:
hypoderme:
hypoge:
hypophylle:
hypothalle:
hypothece:
hysterothece:
lames:
lamprocystides:
lamprocheilocystides:
lampropleurocystides:
lamprocaulocystides:
latex:
leptocystides:
leptocheilocystides:
leptopleurocystides:
macrocystides:
macropleurocystides:
marge:
marge-et-face-externe:
mediostrate:
medulla:
medulla-caulinaire:
medulla-clavariale:
medulla-clavulaire:
microconidies:
mode-de-croissance: isolé, ou grégaire en petit groupe
mycelium-basal:
myxocarpe:
nouvelle-espece:
note-taxonomique:
oeuf:
paracapillitium:
paraphyses:
parasite:
paroi-peritheciale:
partie-apicale:
peridiole:
peridiopellis:
peridium:
peritheces:
phenologie: d'août à septembre
phialoconidies:
pieds-steriles:
pigments:
pileipellis:
pileitrame:
pileocystides:
pileus: 35-140 mm de Ø, convexe, devenant largement convexe à subétalé à maturité; à marge incurvée au début, appenticulée; surface glabre, brillante, visqueuse à glutineuse; couleurs variables, jaune orangé, rouge terne, brun rougeâtre, brun rougeâtre, brun rougeâtre foncé ou marron foncé
plasmode:
pleurochrysocystides:
pleurocystides:
poils:
poils-basaux:
poils-caulinaires:
poils-du-cortex:
poils-externes:
poils-lateraux-et-caulinaires:
poils-marginaux:
poils-mycelien-basaux:
poils-peridiaux:
poils-peritheciaux:
poils-pileiques:
pores:
premiere-mention:
pseudocapillitium:
pseudocolumelle:
pseudocystides:
pseudo-peridioles:
publications: |
<b>Bessette, Alan E.; Bessette, Arleen R.; Roody, William, C.</b> <i>North American Boletes (A Color Guide to the Fleshy Pored Mushrooms)</i>, Syracuse University Press, 2010, 400 p.
<b>Noordeloos, Machiel E.; Kuyper, Th. W.; Vellinger, E. C.</b> <i>Flora Agaricina Neerlandica, vol. 6, critical monograph on families of agarics and boleti occuring in the Netherlands</i>, Taylor & Francis group, 2005, 236 p.
<b>Smith, Alexander H. ; Thiers, Harry D.</b> <i>The Boletes of Michigan</i>, Ann Arbor, The University of Michigan Press, 1971, 610 p.
publications-microscopiques:
reactions-chimiques-naturelles:
reactions-macrochimiques: |
Ammoniaque (NH<sub>4</sub>OH 10%) = vert foncé à noir olive sur le pileus; rosâtre à rouge puis bleu-vert sur la chair
Potasse (KOH 10%) = noir verdâtre sur le pileus; flash rose puis instantanément bleu à noir bleuâtre sur la chair
Sulfate de fer (FeSO<sub>4</sub>) = brun olive à noir olive sur la chair
receptacle:
remarques:
repartition:
rhizomorphes:
sac-sporifere:
saveur: indistincte
sclerocystides:
sclerote:
soies:
soies-hymeniales:
sporee: brun cannelle foncé
spherocytes:
sporocystes:
stipe: 40-140 x 10-30 mm Ø, cylindrique à subégale ou légèrement élargie vers la base, épais, plein, jaune et lisse au-dessus de l'anneau; strié de brun rougeâtre à brunâtre et souvent blanchâtre près de la base; gluant à visqueux; chair jaunâtre, parfois tachée de vert, surtout près de la base lorsqu'il est coupé
stipitipellis:
stipititrame:
stroma:
subhymenium:
subiculum:
substrat:
symptomes:
syndrome:
synonymie: |
<i>Boletus clintonianus</i> Peck, Annual Report on the New York State Museum of Natural History 23:128 (1872)
<i>Suillus grevillei var. clintonianus</i> (Peck) Singer, Lilloa 22:657 (1951)
systeme-hyphal:
textura:
tomentum-caulinaire:
tomentum-pileique:
trame-hymenophorale:
trame-lamellaire:
trame-tubulaire:
tubes: de 4-12 mm de profondeur
type:
typique:
velipellis:
voile:
voile-general:
voile-partiel: cotonneux avec une couche gélatineuse, formant un anneau supérieur gélatineux, jaunâtre avec des stries brun rougeâtre
volve:
zone-perihymeniale:
---
|
{
"content_hash": "964eb926de352d58f8623793fc11d240",
"timestamp": "",
"source": "github",
"line_count": 294,
"max_line_length": 317,
"avg_line_length": 26.727891156462587,
"alnum_prop": 0.7246118605243065,
"repo_name": "19Inocybe63/Fungiquebec",
"id": "7b0ec0e91c7a1ee68ec7a9dffc3cc7dc856e9a49",
"size": "7934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_champignons/Suillus-clintonianus.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "40070"
},
{
"name": "HTML",
"bytes": "71257"
},
{
"name": "JavaScript",
"bytes": "567980"
},
{
"name": "Ruby",
"bytes": "43"
}
],
"symlink_target": ""
}
|
package com.sandislandserv.rourke750.Commands;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import com.sandislandserv.rourke750.BetterAssociations;
import com.sandislandserv.rourke750.database.AssociationsManager;
import com.sandislandserv.rourke750.database.BanManager;
import com.sandislandserv.rourke750.database.BaseValues;
import com.sandislandserv.rourke750.database.PlayerManager;
public class BanCommand {
private BanManager bm;
private AssociationsManager am;
private PlayerManager pm;
public BanCommand(BaseValues db){
bm = db.getBanManager();
am = db.getAssociationsManager();
pm = db.getPlayerManager();
}
public void banPlayer(CommandSender sender, String[] args){
if (args.length == 2){
sender.sendMessage(ChatColor.RED + "Must give player name to ban!");
return;
}
String ban = args[2];
OfflinePlayer pl = Bukkit.getOfflinePlayer(ban);
if (!pl.hasPlayedBefore()){
sender.sendMessage(ChatColor.RED + "Player has not played before.");
return;
}
String reason = "";
for (int x = 3; x < args.length; x++){
reason += args[x];
}
if (reason.equals("")){
reason = BetterAssociations.getConfigFile().getString("banmanager.set.defaultbanreason");
bm.banPlayer(reason, pl.getUniqueId());
sender.sendMessage(ChatColor.RED + "Player banned with default reason: " + reason);
}
else{
bm.banPlayer(reason, pl.getUniqueId());
sender.sendMessage(ChatColor.RED + "Player banned with reason: " + reason);
}
return;
}
public void unBanPlayer(CommandSender sender, String[] args){
if (args.length == 2){
sender.sendMessage(ChatColor.RED + "Must give a player name to unban!");
return;
}
String unban = args[2];
OfflinePlayer pl = Bukkit.getOfflinePlayer(unban);
bm.unbanPlayer(pl.getUniqueId());
sender.sendMessage(ChatColor.RED + "Player has been unbanned.");
return;
}
public void banAllAlts(CommandSender sender, String[] args){
if (args.length == 2){
sender.sendMessage(ChatColor.RED + "Must give a player name to ban all his alts!");
return;
}
String playerName = args[2];
UUID uuid = pm.getUUIDfromPlayerName(playerName);
List<UUID> alts = am.getAltsListUUID(uuid);
String reason = "";
for (int x = 3; x < args.length; x++){
reason += args[x];
}
if (reason.equals("")){
reason = BetterAssociations.getConfigFile().getString("banmanager.set.defaultbanreason");
bm.banPlayers(alts, reason);
sender.sendMessage(ChatColor.RED + "Player banned with default reason: " + reason);
}
else{
bm.banPlayers(alts, reason);
sender.sendMessage(ChatColor.RED + "Player banned with reason: " + reason);
}
}
}
|
{
"content_hash": "3455b61725f1eccfe9fd24aa986aecb7",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 92,
"avg_line_length": 31.179775280898877,
"alnum_prop": 0.7181981981981982,
"repo_name": "rourke750/BetterAssociations",
"id": "482f94111f739e63429d6e9b12cb453066750d37",
"size": "2775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/sandislandserv/rourke750/Commands/BanCommand.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "63740"
}
],
"symlink_target": ""
}
|
package com.ibm.watson.text_to_speech.v1.model;
import static org.testng.Assert.*;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.watson.text_to_speech.v1.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.testng.annotations.Test;
/** Unit test class for the AddCustomPromptOptions model. */
public class AddCustomPromptOptionsTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata =
TestUtilities.creatMockListFileWithMetadata();
@Test
public void testAddCustomPromptOptions() throws Throwable {
PromptMetadata promptMetadataModel =
new PromptMetadata.Builder().promptText("testString").speakerId("testString").build();
assertEquals(promptMetadataModel.promptText(), "testString");
assertEquals(promptMetadataModel.speakerId(), "testString");
AddCustomPromptOptions addCustomPromptOptionsModel =
new AddCustomPromptOptions.Builder()
.customizationId("testString")
.promptId("testString")
.metadata(promptMetadataModel)
.file(TestUtilities.createMockStream("This is a mock file."))
.build();
assertEquals(addCustomPromptOptionsModel.customizationId(), "testString");
assertEquals(addCustomPromptOptionsModel.promptId(), "testString");
assertEquals(addCustomPromptOptionsModel.metadata(), promptMetadataModel);
assertEquals(
IOUtils.toString(addCustomPromptOptionsModel.file()),
IOUtils.toString(TestUtilities.createMockStream("This is a mock file.")));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testAddCustomPromptOptionsError() throws Throwable {
new AddCustomPromptOptions.Builder().build();
}
}
|
{
"content_hash": "d993cb1e8a946c9c6206363787b176c0",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 94,
"avg_line_length": 40.57446808510638,
"alnum_prop": 0.7587834294703724,
"repo_name": "watson-developer-cloud/java-sdk",
"id": "695d6b50fb1303bb0d6fd7f81c49f2967c284962",
"size": "2491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "text-to-speech/src/test/java/com/ibm/watson/text_to_speech/v1/model/AddCustomPromptOptionsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "350"
},
{
"name": "HTML",
"bytes": "50951"
},
{
"name": "Java",
"bytes": "7270071"
},
{
"name": "Makefile",
"bytes": "3123"
},
{
"name": "Python",
"bytes": "381"
},
{
"name": "Shell",
"bytes": "7894"
}
],
"symlink_target": ""
}
|
@echo off
@rem
@rem
@rem The hbase command script. Based on the hadoop command script putting
@rem in hbase classes, libs and configurations ahead of hadoop's.
@rem
@rem TODO: Narrow the amount of duplicated code.
@rem
@rem Environment Variables:
@rem
@rem JAVA_HOME The java implementation to use. Overrides JAVA_HOME.
@rem
@rem HBASE_CLASSPATH Extra Java CLASSPATH entries.
@rem
@rem HBASE_HEAPSIZE The maximum amount of heap to use, in MB.
@rem Default is 1000.
@rem
@rem HBASE_OPTS Extra Java runtime options.
@rem
@rem HBASE_CONF_DIR Alternate conf dir. Default is ${HBASE_HOME}/conf.
@rem
@rem HBASE_ROOT_LOGGER The root appender. Default is INFO,console
@rem
@rem JRUBY_HOME JRuby path: $JRUBY_HOME\lib\jruby.jar should exist.
@rem Defaults to the jar packaged with HBase.
@rem
@rem JRUBY_OPTS Extra options (eg '--1.9') passed to the hbase shell.
@rem Empty by default.
@rem HBASE_SHELL_OPTS Extra options passed to the hbase shell.
@rem Empty by default.
setlocal enabledelayedexpansion
for %%i in (%0) do (
if not defined HBASE_BIN_PATH (
set HBASE_BIN_PATH=%%~dpi
)
)
if "%HBASE_BIN_PATH:~-1%" == "\" (
set HBASE_BIN_PATH=%HBASE_BIN_PATH:~0,-1%
)
rem This will set HBASE_HOME, etc.
set hbase-config-script=%HBASE_BIN_PATH%\hbase-config.cmd
call "%hbase-config-script%" %*
if "%1" == "--config" (
shift
shift
)
rem Detect if we are in hbase sources dir
set in_dev_env=false
if exist "%HBASE_HOME%\target" set in_dev_env=true
rem --service is an internal option. used by MSI setup to install HBase as a windows service
if "%1" == "--service" (
set service_entry=true
shift
)
set hbase-command=%1
shift
@rem if no args specified, show usage
if "%hbase-command%"=="" (
goto :print_usage
endlocal
goto :eof
)
set JAVA_HEAP_MAX=-Xmx1000m
rem check envvars which might override default args
if defined HBASE_HEAPSIZE (
set JAVA_HEAP_MAX=-Xmx%HBASE_HEAPSIZE%m
)
set CLASSPATH=%HBASE_CONF_DIR%;%JAVA_HOME%\lib\tools.jar
rem Add maven target directory
set cached_classpath_filename=%HBASE_HOME%\target\cached_classpath.txt
if "%in_dev_env%"=="true" (
rem adding maven main classes to classpath
for /f %%i in ('dir /b "%HBASE_HOME%\hbase-*"') do (
if exist %%i\target\classes set CLASSPATH=!CLASSPATH!;%%i\target\classes
)
rem adding maven test classes to classpath
rem For developers, add hbase classes to CLASSPATH
for /f %%i in ('dir /b "%HBASE_HOME%\hbase-*"') do (
if exist %%i\target\test-classes set CLASSPATH=!CLASSPATH!;%%i\target\test-classes
)
if not exist "%cached_classpath_filename%" (
echo "As this is a development environment, we need %cached_classpath_filename% to be generated from maven (command: mvn install -DskipTests)"
goto :eof
)
for /f "delims=" %%i in ('type "%cached_classpath_filename%"') do set CLASSPATH=%CLASSPATH%;%%i
)
@rem For releases add hbase webapps to CLASSPATH
@rem Webapps must come first else it messes up Jetty
if exist "%HBASE_HOME%\hbase-webapps" (
set CLASSPATH=%CLASSPATH%;%HBASE_HOME%
)
if exist "%HBASE_HOME%\target\hbase-webapps" (
set CLASSPATH=%CLASSPATH%;%HBASE_HOME%\target
)
for /F %%f in ('dir /b "%HBASE_HOME%\hbase*.jar" 2^>nul') do (
if not "%%f:~-11"=="sources.jar" (
set CLASSPATH=!CLASSPATH!;%HBASE_HOME%\%%f
)
)
@rem Add libs to CLASSPATH
if exist "%HBASE_HOME%\lib" (
set CLASSPATH=!CLASSPATH!;%HBASE_HOME%\lib\*
)
@rem Add user-specified CLASSPATH last
if defined HBASE_CLASSPATH (
set CLASSPATH=%CLASSPATH%;%HBASE_CLASSPATH%
)
@rem Default log directory and file
if not defined HBASE_LOG_DIR (
set HBASE_LOG_DIR=%HBASE_HOME%\logs
)
if not defined HBASE_LOGFILE (
set HBASE_LOGFILE=hbase.log
)
set JAVA_PLATFORM=
rem If avail, add Hadoop to the CLASSPATH and to the JAVA_LIBRARY_PATH
set PATH=%PATH%;"%HADOOP_HOME%\bin"
set HADOOP_IN_PATH=hadoop.cmd
if exist "%HADOOP_HOME%\bin\%HADOOP_IN_PATH%" (
set hadoopCpCommand=call %HADOOP_IN_PATH% classpath 2^>nul
for /f "eol= delims=" %%i in ('!hadoopCpCommand!') do set CLASSPATH_FROM_HADOOP=%%i
if defined CLASSPATH_FROM_HADOOP (
set CLASSPATH=%CLASSPATH%;!CLASSPATH_FROM_HADOOP!
)
set HADOOP_CLASSPATH=%CLASSPATH%
set hadoopJLPCommand=call %HADOOP_IN_PATH% org.apache.hadoop.hbase.util.GetJavaProperty java.library.path 2^>nul
for /f "eol= delims=" %%i in ('!hadoopJLPCommand!') do set HADOOP_JAVA_LIBRARY_PATH=%%i
if not defined JAVA_LIBRARY_PATH (
set JAVA_LIBRARY_PATH=!HADOOP_JAVA_LIBRARY_PATH!
) else (
set JAVA_LIBRARY_PATH=%JAVA_LIBRARY_PATH%;!HADOOP_JAVA_LIBRARY_PATH!
)
)
if exist "%HBASE_HOME%\build\native" (
set platformCommand=call %JAVA% -classpath "%CLASSPATH%" org.apache.hadoop.util.PlatformName
for /f %%i in ('!platformCommand!') do set JAVA_PLATFORM=%%i
set _PATH_TO_APPEND=%HBASE_HOME%\build\native\!JAVA_PLATFORM!;%HBASE_HOME%\build\native\!JAVA_PLATFORM!\lib
if not defined JAVA_LIBRARY_PATH (
set JAVA_LIBRARY_PATH=!_PATH_TO_APPEND!
) else (
set JAVA_LIBRARY_PATH=%JAVA_LIBRARY_PATH%;!_PATH_TO_APPEND!
)
)
rem This loop would set %hbase-command-arguments%
set _hbasearguments=
:MakeCmdArgsLoop
if [%1]==[] goto :EndLoop
if not defined _hbasearguments (
set _hbasearguments=%1
) else (
set _hbasearguments=!_hbasearguments! %1
)
shift
goto :MakeCmdArgsLoop
:EndLoop
set hbase-command-arguments=%_hbasearguments%
@rem figure out which class to run
set corecommands=shell master regionserver thrift thrift2 rest avro hlog hbck hfile zookeeper zkcli upgrade mapredcp
for %%i in ( %corecommands% ) do (
if "%hbase-command%"=="%%i" set corecommand=true
)
if defined corecommand (
call :%hbase-command% %hbase-command-arguments%
) else (
if "%hbase-command%" == "classpath" (
echo %CLASSPATH%
goto :eof
)
if "%hbase-command%" == "version" (
set CLASS=org.apache.hadoop.hbase.util.VersionInfo
) else (
set CLASS=%hbase-command%
)
)
if not defined HBASE_IDENT_STRING (
set HBASE_IDENT_STRING=%USERNAME%
)
@rem Set the right GC options based on the what we are running
set servercommands=master regionserver thrift thrift2 rest avro zookeeper
for %%i in ( %servercommands% ) do (
if "%hbase-command%"=="%%i" set servercommand=true
)
if "%servercommand%" == "true" (
set HBASE_OPTS=%HBASE_OPTS% %SERVER_GC_OPTS%
) else (
set HBASE_OPTS=%HBASE_OPTS% %CLIENT_GC_OPTS%
)
@rem If HBase is run as a windows service, configure logging
if defined service_entry (
set HBASE_LOG_PREFIX=hbase-%hbase-command%-%COMPUTERNAME%
set HBASE_LOGFILE=!HBASE_LOG_PREFIX!.log
if not defined HBASE_ROOT_LOGGER (
set HBASE_ROOT_LOGGER=INFO,DRFA
)
set HBASE_SECURITY_LOGGER=INFO,DRFAS
set loggc=!HBASE_LOG_DIR!\!HBASE_LOG_PREFIX!.gc
set loglog=!HBASE_LOG_DIR!\!HBASE_LOGFILE!
if "%HBASE_USE_GC_LOGFILE%" == "true" (
set HBASE_OPTS=%HBASE_OPTS% -Xloggc:"!loggc!"
)
)
@rem Have JVM dump heap if we run out of memory. Files will be 'launch directory'
@rem and are named like the following: java_pid21612.hprof. Apparently it does not
@rem 'cost' to have this flag enabled. Its a 1.6 flag only. See:
@rem http://blogs.sun.com/alanb/entry/outofmemoryerror_looks_a_bit_better
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.log.dir="%HBASE_LOG_DIR%"
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.log.file="%HBASE_LOGFILE%"
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.home.dir="%HBASE_HOME%"
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.id.str="%HBASE_IDENT_STRING%"
set HBASE_OPTS=%HBASE_OPTS% -XX:OnOutOfMemoryError="taskkill /F /PID %p"
if not defined HBASE_ROOT_LOGGER (
set HBASE_ROOT_LOGGER=INFO,console
)
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.root.logger="%HBASE_ROOT_LOGGER%"
if defined JAVA_LIBRARY_PATH (
set HBASE_OPTS=%HBASE_OPTS% -Djava.library.path="%JAVA_LIBRARY_PATH%"
)
rem Enable security logging on the master and regionserver only
if not defined HBASE_SECURITY_LOGGER (
set HBASE_SECURITY_LOGGER=INFO,NullAppender
if "%hbase-command%"=="master" (
set HBASE_SECURITY_LOGGER=INFO,DRFAS
)
if "%hbase-command%"=="regionserver" (
set HBASE_SECURITY_LOGGER=INFO,DRFAS
)
)
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.security.logger="%HBASE_SECURITY_LOGGER%"
set java_arguments=%JAVA_HEAP_MAX% %HBASE_OPTS% -classpath "%CLASSPATH%" %CLASS% %hbase-command-arguments%
if defined service_entry (
call :makeServiceXml %java_arguments%
) else (
call %JAVA% %java_arguments%
)
endlocal
goto :eof
:shell
rem eg export JRUBY_HOME=/usr/local/share/jruby
if defined JRUBY_HOME (
set CLASSPATH=%CLASSPATH%;%JRUBY_HOME%\lib\jruby.jar
set HBASE_OPTS=%HBASE_OPTS% -Djruby.home="%JRUBY_HOME%" -Djruby.lib="%JRUBY_HOME%\lib"
)
rem find the hbase ruby sources
if exist "%HBASE_HOME%\lib\ruby" (
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.ruby.sources="%HBASE_HOME%\lib\ruby"
) else (
set HBASE_OPTS=%HBASE_OPTS% -Dhbase.ruby.sources="%HBASE_HOME%\hbase-shell\src\main\ruby"
)
set HBASE_OPTS=%HBASE_OPTS% %HBASE_SHELL_OPTS%
set CLASS=org.jruby.Main -X+O %JRUBY_OPTS% "%HBASE_HOME%\bin\hirb.rb"
goto :eof
:master
set CLASS=org.apache.hadoop.hbase.master.HMaster
if NOT "%1"=="stop" (
set HBASE_OPTS=%HBASE_OPTS% %HBASE_MASTER_OPTS%
)
goto :eof
:regionserver
set CLASS=org.apache.hadoop.hbase.regionserver.HRegionServer
if NOT "%1"=="stop" (
set HBASE_OPTS=%HBASE_OPTS% %HBASE_REGIONSERVER_OPTS%
)
goto :eof
:thrift
set CLASS=org.apache.hadoop.hbase.thrift.ThriftServer
if NOT "%1" == "stop" (
set HBASE_OPTS=%HBASE_OPTS% %HBASE_THRIFT_OPTS%
)
goto :eof
:thrift2
set CLASS=org.apache.hadoop.hbase.thrift2.ThriftServer
if NOT "%1" == "stop" (
set HBASE_OPTS=%HBASE_OPTS% %HBASE_THRIFT_OPTS%
)
goto :eof
:rest
set CLASS=org.apache.hadoop.hbase.rest.RESTServer
if NOT "%1"=="stop" (
set HBASE_OPTS=%HBASE_OPTS% %HBASE_REST_OPTS%
)
goto :eof
:avro
set CLASS=org.apache.hadoop.hbase.avro.AvroServer
if NOT "%1"== "stop" (
set HBASE_OPTS=%HBASE_OPTS% %HBASE_AVRO_OPTS%
)
goto :eof
:zookeeper
set CLASS=org.apache.hadoop.hbase.zookeeper.HQuorumPeer
if NOT "%1"=="stop" (
set HBASE_OPTS=%HBASE_OPTS% %HBASE_ZOOKEEPER_OPTS%
)
goto :eof
:hbck
set CLASS=org.apache.hadoop.hbase.util.HBaseFsck
goto :eof
:hlog
set CLASS=org.apache.hadoop.hbase.regionserver.wal.HLogPrettyPrinter
goto :eof
:hfile
set CLASS=org.apache.hadoop.hbase.io.hfile.HFile
goto :eof
:zkcli
set CLASS=org.apache.hadoop.hbase.zookeeper.ZooKeeperMainServer
goto :eof
:upgrade
set CLASS=org.apache.hadoop.hbase.migration.UpgradeTo96
goto :eof
:mapredcp
set CLASS=org.apache.hadoop.hbase.util.MapreduceDependencyClasspathTool
goto :eof
:makeServiceXml
set arguments=%*
@echo ^<service^>
@echo ^<id^>%hbase-command%^</id^>
@echo ^<name^>%hbase-command%^</name^>
@echo ^<description^>This service runs Isotope %hbase-command%^</description^>
@echo ^<executable^>%JAVA%^</executable^>
@echo ^<arguments^>%arguments%^</arguments^>
@echo ^</service^>
goto :eof
:print_usage
echo Usage: hbase [^<options^>] ^<command^> [^<args^>]
echo where ^<command^> an option from one of these categories::
echo Options:
echo --config DIR Configuration direction to use. Default: ./conf
echo.
echo Commands:
echo Some commands take arguments. Pass no args or -h for usage."
echo shell Run the HBase shell
echo hbck Run the hbase 'fsck' tool
echo hlog Write-ahead-log analyzer
echo hfile Store file analyzer
echo zkcli Run the ZooKeeper shell
echo upgrade Upgrade hbase
echo master Run an HBase HMaster node
echo regionserver Run an HBase HRegionServer node
echo zookeeper Run a Zookeeper server
echo rest Run an HBase REST server
echo thrift Run the HBase Thrift server
echo thrift2 Run the HBase Thrift2 server
echo classpath Dump hbase CLASSPATH
echo mapredcp Dump CLASSPATH entries required by mapreduce
echo version Print the version
echo CLASSNAME Run the class named CLASSNAME
goto :eof
|
{
"content_hash": "a1054466cfd90bef844643c4e56e91e2",
"timestamp": "",
"source": "github",
"line_count": 411,
"max_line_length": 148,
"avg_line_length": 29.664233576642335,
"alnum_prop": 0.6938156167979003,
"repo_name": "carpedm20/pinpoint",
"id": "42eb7b50299b2270cf513b518576f78a357468ae",
"size": "13061",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "quickstart/support/hbase-win/bin/hbase.cmd",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "163098"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "982261"
},
{
"name": "Java",
"bytes": "5744100"
},
{
"name": "JavaScript",
"bytes": "2894123"
},
{
"name": "Makefile",
"bytes": "15485"
},
{
"name": "Python",
"bytes": "11423"
},
{
"name": "Shell",
"bytes": "65205"
},
{
"name": "Thrift",
"bytes": "5508"
}
],
"symlink_target": ""
}
|
package com.commercetools.sunrise.productcatalog.productoverview.search.facetedsearch.categorytree.viewmodels;
import com.commercetools.sunrise.framework.localization.UserLanguage;
import com.commercetools.sunrise.framework.reverserouters.productcatalog.product.ProductReverseRouter;
import com.commercetools.sunrise.framework.viewmodels.forms.FormSelectableOptionViewModel;
import com.commercetools.sunrise.search.facetedsearch.viewmodels.FacetOptionViewModel;
import com.commercetools.sunrise.test.TestableCall;
import io.sphere.sdk.categories.Category;
import io.sphere.sdk.categories.CategoryTree;
import io.sphere.sdk.models.LocalizedString;
import io.sphere.sdk.search.TermFacetResult;
import io.sphere.sdk.search.TermStats;
import org.junit.Test;
import play.Application;
import play.mvc.Http;
import play.test.WithApplication;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static play.test.Helpers.fakeRequest;
public class CategoryTreeFacetOptionViewModelFactoryTest extends WithApplication {
private final static String CAT_A_ID = "d5a0952b-6574-49c9-b0cd-61e0d21d36cc";
private final static String CAT_B_ID = "e92b6d26-7a34-4960-804c-0fc9e40c64e3";
private final static String CAT_C_ID = "1acce167-cd23-4fd7-b344-af76941cb375";
private final static String CAT_D_ID = "f5b288e8-d19c-4c0d-a18a-8ca68f982b8e";
private final static String CAT_E_ID = "b00b1eb9-f051-4f13-8f9c-1bb73e13e8a1";
private static final Category CAT_A = category(CAT_A_ID, null, "A");
private static final Category CAT_B = category(CAT_B_ID, CAT_A_ID, "B");
private static final Category CAT_C = category(CAT_C_ID, CAT_B_ID, "C");
private static final Category CAT_D = category(CAT_D_ID, CAT_B_ID, "D");
private static final Category CAT_E = category(CAT_E_ID, CAT_A_ID, "E");
private static final TermStats TERM_B = TermStats.of(CAT_B_ID, 4L, 1L);
private static final TermStats TERM_C = TermStats.of(CAT_C_ID, 8L, 2L);
private static final TermStats TERM_D = TermStats.of(CAT_D_ID, 7L, 3L);
private static final CategoryTree ALL_CATEGORY_TREE = CategoryTree.of(asList(CAT_A, CAT_B, CAT_C, CAT_D, CAT_E));
private static final CategoryTree EMPTY_CATEGORY_TREE = CategoryTree.of(emptyList());
/* A
* |-- B
* | |-- C
* | |-- D
* |
* |-- E
*/
@Override
protected Application provideApplication() {
final Application application = super.provideApplication();
Http.Context.current.set(new Http.Context(fakeRequest()));
return application;
}
@Test
public void resolvesCategory() throws Exception {
test(CAT_B, ALL_CATEGORY_TREE, singletonList(TERM_B), viewModel -> {
assertThat(viewModel.getLabel()).isEqualTo("B");
assertThat(viewModel.getValue()).isEqualTo("B-slug");
assertThat(viewModel.getCount()).isEqualTo(1);
assertThat(viewModel.isSelected()).isFalse();
assertThat(viewModel.getChildren()).isNullOrEmpty();
});
}
@Test
public void emptyChildrenWithEmptyCategoryTree() throws Exception {
test(CAT_B, EMPTY_CATEGORY_TREE, singletonList(TERM_B), viewModel -> {
assertThat(viewModel.getLabel()).isEqualTo("B");
assertThat(viewModel.getCount()).isEqualTo(1);
assertThat(viewModel.isSelected()).isFalse();
assertThat(viewModel.getChildren()).isNullOrEmpty();
});
}
@Test
public void zeroCountWithEmptyFacetResults() throws Exception {
test(CAT_B, ALL_CATEGORY_TREE, emptyList(), viewModel -> {
assertThat(viewModel.getLabel()).isEqualTo("B");
assertThat(viewModel.getCount()).isZero();
assertThat(viewModel.isSelected()).isFalse();
assertThat(viewModel.getChildren()).isNullOrEmpty();
});
}
@Test
public void keepsOrderFromCategoryTree() throws Exception {
test(CAT_B, ALL_CATEGORY_TREE, asList(TERM_D, TERM_C), viewModel ->
assertThat(viewModel.getChildren())
.extracting(FormSelectableOptionViewModel::getLabel)
.containsExactly("C", "D"));
}
@Test
public void inheritsInformationFromLeaves() throws Exception {
test(CAT_B, ALL_CATEGORY_TREE, asList(TERM_D, TERM_C, TERM_B), viewModel -> {
assertThat(viewModel.getLabel()).isEqualTo("B");
assertThat(viewModel.getCount()).isEqualTo(6);
assertThat(viewModel.isSelected()).isTrue();
assertThat(viewModel.getChildren())
.extracting(FormSelectableOptionViewModel::getLabel)
.containsExactly("C", "D");
});
}
@Test
public void discardsEmptyLeaves() throws Exception {
test(CAT_B, ALL_CATEGORY_TREE, asList(TERM_C, TERM_B), viewModel ->
assertThat(viewModel.getChildren())
.extracting(FormSelectableOptionViewModel::getLabel)
.containsExactly("C"));
}
@Test
public void discardsEmptyBranches() throws Exception {
test(CAT_A, ALL_CATEGORY_TREE, asList(TERM_D, TERM_C, TERM_B), viewModelA -> {
assertThat(viewModelA.getLabel()).isEqualTo("A");
assertThat(viewModelA.getCount()).isEqualTo(6);
assertThat(viewModelA.isSelected()).isTrue();
assertThat(viewModelA.getChildren()).hasSize(1);
final FacetOptionViewModel viewModelB = viewModelA.getChildren().get(0);
assertThat(viewModelB.getLabel()).isEqualTo("B");
assertThat(viewModelB.getCount()).isEqualTo(6);
assertThat(viewModelB.isSelected()).isTrue();
assertThat(viewModelB.getChildren())
.extracting(FormSelectableOptionViewModel::getLabel)
.containsExactly("C", "D");
});
}
private void test(final Category category, final CategoryTree categoryTree, final List<TermStats> termStats, final Consumer<FacetOptionViewModel> test) {
final UserLanguage userLanguage = mock(UserLanguage.class);
when(userLanguage.locales()).thenReturn(singletonList(Locale.ENGLISH));
final CategoryTreeFacetOptionViewModelFactory factory = new CategoryTreeFacetOptionViewModelFactory(userLanguage, categoryTree, reverseRouter());
final TermFacetResult termFacetResult = TermFacetResult.of(0L, 0L, 0L, termStats);
test.accept(factory.create(termFacetResult, category, CAT_C));
}
private static Category category(final String id, @Nullable final String parentId, final String name) {
final Category category = mock(Category.class);
when(category.getId()).thenReturn(id);
when(category.getName()).thenReturn(LocalizedString.ofEnglish(name));
when(category.getSlug()).thenReturn(LocalizedString.ofEnglish(name + "-slug"));
when(category.getParent()).thenReturn(parentId != null ? Category.reference(parentId) : null);
return category;
}
private static ProductReverseRouter reverseRouter() {
final ProductReverseRouter productReverseRouter = mock(ProductReverseRouter.class);
when(productReverseRouter.productOverviewPageCall(any(Category.class)))
.then(invocation -> ((Category) invocation.getArgument(0)).getSlug()
.find(Locale.ENGLISH)
.map(TestableCall::new));
return productReverseRouter;
}
}
|
{
"content_hash": "63a1fbebcf28c692ed826498ec7b0171",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 157,
"avg_line_length": 47.30538922155689,
"alnum_prop": 0.6853164556962026,
"repo_name": "sphereio/sphere-sunrise",
"id": "59944e47d74dd8e25a0a7ae65d6136f0cd53a9a8",
"size": "7900",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "product-catalog/pt/com/commercetools/sunrise/productcatalog/productoverview/search/facetedsearch/categorytree/viewmodels/CategoryTreeFacetOptionViewModelFactoryTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "191"
},
{
"name": "HTML",
"bytes": "2157"
},
{
"name": "Java",
"bytes": "495887"
},
{
"name": "JavaScript",
"bytes": "1112"
},
{
"name": "Scala",
"bytes": "8874"
},
{
"name": "Shell",
"bytes": "19258"
}
],
"symlink_target": ""
}
|
<html>
<head>
<title>
JsonCpp - JSON data format manipulation library
</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#ffffff">
<table width="100%">
<tr>
<td width="40%" align="left" valign="center">
<a href="https://github.com/open-source-parsers/jsoncpp">
JsonCpp project page
</a>
</td>
<td width="40%" align="right" valign="center">
<a href="http://open-source-parsers.github.io/jsoncpp-docs/doxygen/">JsonCpp home page</a>
</td>
</tr>
</table>
<hr>
<!-- Generated by Doxygen 1.8.11 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li class="current"><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_d44c64559bbebec7f509842c48db8b23.html">include</a></li><li class="navelem"><a class="el" href="dir_afd937d70611a55c9601734fb033a9b9.html">json</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">json Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
Files</h2></td></tr>
<tr class="memitem:allocator_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="allocator_8h.html">allocator.h</a> <a href="allocator_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:assertions_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="assertions_8h.html">assertions.h</a> <a href="assertions_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:autolink_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="autolink_8h.html">autolink.h</a> <a href="autolink_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:config_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="config_8h.html">config.h</a> <a href="config_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:features_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="features_8h.html">features.h</a> <a href="features_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:forwards_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="forwards_8h.html">forwards.h</a> <a href="forwards_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:json_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="json_8h.html">json.h</a> <a href="json_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:reader_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="reader_8h.html">reader.h</a> <a href="reader_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:value_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="value_8h.html">value.h</a> <a href="value_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:version_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="version_8h.html">version.h</a> <a href="version_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:writer_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="writer_8h.html">writer.h</a> <a href="writer_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<hr>
</body>
</html>
|
{
"content_hash": "9a320049e9c7fbfef8ec989af410f8fa",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 255,
"avg_line_length": 69.6923076923077,
"alnum_prop": 0.6548933038999264,
"repo_name": "CapitanLiteral/Wingman",
"id": "23584a97d1b95b8c17df13fee9673733d7b0bf3c",
"size": "5436",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Engine/jsoncpp/doxygen/jsoncpp-api-html-1.7.7/dir_afd937d70611a55c9601734fb033a9b9.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3526557"
},
{
"name": "C++",
"bytes": "4412267"
},
{
"name": "CSS",
"bytes": "27034"
},
{
"name": "HTML",
"bytes": "2620954"
},
{
"name": "JavaScript",
"bytes": "3422"
},
{
"name": "Objective-C",
"bytes": "61094"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sat Jun 21 06:31:11 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.util.bloom.HashFunction (Apache Hadoop Main 2.4.1 API)
</TITLE>
<META NAME="date" CONTENT="2014-06-21">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.util.bloom.HashFunction (Apache Hadoop Main 2.4.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/util/bloom/HashFunction.html" title="class in org.apache.hadoop.util.bloom"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/util/bloom//class-useHashFunction.html" target="_top"><B>FRAMES</B></A>
<A HREF="HashFunction.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.util.bloom.HashFunction</B></H2>
</CENTER>
No usage of org.apache.hadoop.util.bloom.HashFunction
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/util/bloom/HashFunction.html" title="class in org.apache.hadoop.util.bloom"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/util/bloom//class-useHashFunction.html" target="_top"><B>FRAMES</B></A>
<A HREF="HashFunction.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
|
{
"content_hash": "ca16c2c8ac72bdfe30de8455ba7f9b34",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 229,
"avg_line_length": 42.90344827586207,
"alnum_prop": 0.614049188233403,
"repo_name": "gsoundar/mambo-ec2-deploy",
"id": "bfa9474f9ae6ef7ac9259809f2ab1baf4eb95317",
"size": "6221",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "packages/hadoop-2.4.1/share/doc/hadoop/api/org/apache/hadoop/util/bloom/class-use/HashFunction.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "23179"
},
{
"name": "CSS",
"bytes": "39965"
},
{
"name": "HTML",
"bytes": "263271260"
},
{
"name": "Java",
"bytes": "103085"
},
{
"name": "JavaScript",
"bytes": "1347"
},
{
"name": "Python",
"bytes": "4101"
},
{
"name": "Ruby",
"bytes": "262588"
},
{
"name": "Shell",
"bytes": "118548"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->
<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8 ie7"><![endif]-->
<!--[if IE 8]><html class="no-js lt-ie9 ie8"><![endif]-->
<!--[if IE 9]><html class="no-js ie9"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"><!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>ONS Alpha Pattern Library</title>
<meta charset="utf-8"/>
<meta content="width=device-width,initial-scale=1.0" name="viewport"/>
<meta content="on" http-equiv="cleartype"/>
<link rel="stylesheet" href="/dist/css/main.css"/>
<script src="/ui/js/lib/modernizr.min.js"></script>
<!-- These are inline styles, should be refactored into a file -->
<style>
/*
* Put styles in here which are required to make the style guide work with the project
*/
body {
max-width: 100%;
}
.color-block {
float: none;
display: inline-block;
}
.language-markup {
overflow-wrap: normal;
}
.grid-col {
word-wrap: break-word;
}
.swatch {
border-radius: 100%;
display: inline-table;
width: 110px;
height: 110px;
padding: 15px;
margin: 20px;
text-align: center;
border: 1px solid black;
position: relative;
}
.swatch div {
display: table-cell;
height: 100%;
width: 100%;
vertical-align: middle;
text-align: center;
}
.grid-wrap {
margin-top: 20px;
margin-bottom: 20px;
}
.grid-col code {
border: 1px dashed #ccc;
background: #fff;
padding: 10px;
display: block;
}
</style>
</head>
<body>
<h2>Nested grid</h2><div class="grid-wrap">
<div class="grid-col desktop-grid-one-half">
<div class="grid-wrap">
<div class="grid-col desktop-grid-one-half">
<code>One Half of one half</code>
</div>
<div class="grid-col desktop-grid-one-half">
<code>One Half of one half</code>
</div>
</div>
</div>
<div class="grid-col desktop-grid-one-half">
<div class="grid-wrap">
<div class="grid-col desktop-grid-one-third">
<code>One third of one half</code>
</div>
<div class="grid-col desktop-grid-one-third">
<code>One third of one half</code>
</div>
<div class="grid-col desktop-grid-one-third">
<code>One third of one half</code>
</div>
</div>
</div>
</div>
<script src="/dist/js/footer.js"></script>
</body>
</html>
|
{
"content_hash": "746d9063cbf8e162d36e4ec5811cfc55",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 90,
"avg_line_length": 24.141509433962263,
"alnum_prop": 0.5693630324345448,
"repo_name": "ONSdigital/pattern-library",
"id": "df13413d37798f2318a6c6f4f0a455ae837f1bb2",
"size": "2559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/visual-language-grid-nested-grid-external.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "301340"
},
{
"name": "HTML",
"bytes": "15303"
},
{
"name": "JavaScript",
"bytes": "144311"
},
{
"name": "Liquid",
"bytes": "342519"
},
{
"name": "Ruby",
"bytes": "677"
},
{
"name": "Shell",
"bytes": "46"
}
],
"symlink_target": ""
}
|
module Dragon
class CityNarrator < Narrator
def narrate(terminal)
describe prefix: "You are visiting ", terminal: terminal
end
end
end
|
{
"content_hash": "94f3206307c4d9b4612cd4f4ec1a8430",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 62,
"avg_line_length": 21.857142857142858,
"alnum_prop": 0.7058823529411765,
"repo_name": "jweissman/dragon",
"id": "f12359e47253a03fd387597fc40eebab018e8c54",
"size": "153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/dragon/narration/city_narrator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3150"
},
{
"name": "HTML",
"bytes": "5322"
},
{
"name": "JavaScript",
"bytes": "707"
},
{
"name": "Ruby",
"bytes": "218362"
}
],
"symlink_target": ""
}
|
Contains custom plugins that can be integrated into Ansible. Currently holds the callback plugin which has been modified
to hide/suppress certain messages during failed retries in a loop-execution.
|
{
"content_hash": "8e09ef2508d2ee1d0c8e977633ce9108",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 121,
"avg_line_length": 67,
"alnum_prop": 0.8258706467661692,
"repo_name": "yudaykiran/openebs",
"id": "3856439279264d4b70ff8d877dc13eccf0fbb4fc",
"size": "238",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "e2e/ansible/plugins/callback/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "107"
}
],
"symlink_target": ""
}
|
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Proc. Amer. Acad. Arts 20:359. 1885
#### Original name
null
### Remarks
null
|
{
"content_hash": "1c89e6a19d8083ad383c463e59423001",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 12.615384615384615,
"alnum_prop": 0.6890243902439024,
"repo_name": "mdoering/backbone",
"id": "ba7cfda1af074418f97d488952ed8bdd4bf2e3b1",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Errazurizia/Errazurizia megacarpa/ Syn. Dalea megacarpa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
package com.aspose.email.examples.email;
import com.aspose.email.EmlLoadOptions;
import com.aspose.email.HtmlLoadOptions;
import com.aspose.email.MailMessage;
import com.aspose.email.MhtmlLoadOptions;
import com.aspose.email.MsgLoadOptions;
import com.aspose.email.TnefLoadOptions;
/*
* Not an example. Is just for Gist Creation
*/
public class LoadingAMessageWithLoadOptions {
public static void main(String[] args) {
// Loading with default options
// Load from eml
MailMessage eml = MailMessage.load("test.eml", new EmlLoadOptions());
// Load from html
MailMessage html = MailMessage.load("test.html", new HtmlLoadOptions());
// load from mhtml
MailMessage mhtml = MailMessage.load("test.mhtml", new MhtmlLoadOptions());
// load from msg
MailMessage msg = MailMessage.load("test.msg", new MsgLoadOptions());
// load from thef fomat
MailMessage thef = MailMessage.load("winmail.dat", new TnefLoadOptions());
// Loading with custom options
EmlLoadOptions opt = new EmlLoadOptions();
opt.setPreserveTnefAttachments(true);
MailMessage emlMailMessage = MailMessage.load("test.html", opt);
HtmlLoadOptions htmlOpt = new HtmlLoadOptions();
htmlOpt.shouldAddPlainTextView(true);
MailMessage htmlMailMessage = MailMessage.load("test.html", htmlOpt);
}
}
|
{
"content_hash": "38f9d52aa995b09ae9d73e08c6e9a36a",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 77,
"avg_line_length": 29.545454545454547,
"alnum_prop": 0.7553846153846154,
"repo_name": "kashifiqb/Aspose.Email-for-Java",
"id": "75598c914e918354e4a5e2ff0574228593a0f6b6",
"size": "1300",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Examples/src/main/java/com/aspose/email/examples/email/LoadingAMessageWithLoadOptions.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2264"
},
{
"name": "Java",
"bytes": "275191"
},
{
"name": "PHP",
"bytes": "41447"
},
{
"name": "Python",
"bytes": "89260"
},
{
"name": "Ruby",
"bytes": "36574"
}
],
"symlink_target": ""
}
|
namespace Google.Cloud.Spanner.Admin.Instance.V1.Snippets
{
// [START spanner_v1_generated_InstanceAdmin_CreateInstanceConfig_async_flattened]
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.LongRunning;
using System.Threading.Tasks;
public sealed partial class GeneratedInstanceAdminClientSnippets
{
/// <summary>Snippet for CreateInstanceConfigAsync</summary>
/// <remarks>
/// 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/dotnet/docs/reference/help/client-configuration#endpoint.
/// </remarks>
public async Task CreateInstanceConfigAsync()
{
// Create client
InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
InstanceConfig instanceConfig = new InstanceConfig();
string instanceConfigId = "";
// Make the request
Operation<InstanceConfig, CreateInstanceConfigMetadata> response = await instanceAdminClient.CreateInstanceConfigAsync(parent, instanceConfig, instanceConfigId);
// Poll until the returned long-running operation is complete
Operation<InstanceConfig, CreateInstanceConfigMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
InstanceConfig result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<InstanceConfig, CreateInstanceConfigMetadata> retrievedResponse = await instanceAdminClient.PollOnceCreateInstanceConfigAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
InstanceConfig retrievedResult = retrievedResponse.Result;
}
}
}
// [END spanner_v1_generated_InstanceAdmin_CreateInstanceConfig_async_flattened]
}
|
{
"content_hash": "548c4463c37a74dade8932abf382b01a",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 173,
"avg_line_length": 54.255319148936174,
"alnum_prop": 0.6909803921568628,
"repo_name": "googleapis/google-cloud-dotnet",
"id": "03be92c21b6fc6f546a44e8f05792866c8e463b3",
"size": "3172",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "apis/Google.Cloud.Spanner.Admin.Instance.V1/Google.Cloud.Spanner.Admin.Instance.V1.GeneratedSnippets/InstanceAdminClient.CreateInstanceConfigAsyncSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "767"
},
{
"name": "C#",
"bytes": "319820004"
},
{
"name": "Dockerfile",
"bytes": "3415"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Python",
"bytes": "2744"
},
{
"name": "Shell",
"bytes": "65881"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>Рецепты</title>
<link href="material-icons/material-icons.css" rel="stylesheet"/>
<!-- Path to Framework7 Library CSS-->
<link rel="stylesheet" href="framework7/css/framework7.material.min.css">
<link rel="stylesheet" href="framework7/css/framework7.material.colors.min.css">
<!-- Path to your custom app styles-->
<link rel="stylesheet" href="css/app.css">
</head>
<body class="_theme-bluegray theme-deeporange _layout-dark">
<!-- Views -->
<div class="views">
<!-- Your main view, should have "view-main" class -->
<div class="view view-main">
<!-- Pages container, because we use fixed navbar and toolbar, it has additional appropriate classes-->
<div class="pages navbar-fixed _toolbar-fixed">
<!-- Page, "data-page" contains page name -->
<div data-page="index" class="page">
<!-- Top Navbar. In Material theme it should be inside of the page-->
<div class="navbar">
<div class="navbar-inner">
<div class="left">
<a href="#" class="link icon-only open-panel"><i class="material-icons">menu</i></a>
</div>
<div class="center" id="title">Рецепты</div>
<div class="right">
</div>
</div>
</div>
<form class="searchbar">
<div class="searchbar-input">
<input type="search" placeholder="Поиск">
<a href="#" class="searchbar-clear"></a>
</div>
<a href="#" class="searchbar-cancel">Отмена</a>
</form>
<!-- Search Bar overlay-->
<div class="searchbar-overlay"></div>
<!-- Scrollable page content -->
<div class="page-content _hide-navbar-on-scroll infinite-scroll" data-distance="100">
<!--<div class="content-block-title">Список</div>-->
<div class="" id="myContent"></div>
</div>
<div class="toolbar tabbar toolbar-bottom layout-dark">
<div class="toolbar-inner art-tabs">
<a id="tab-all" href="#myContent" class="tab-all tab-link active"><i class="material-icons">home</i></a>
<a id="tab-cat" href="#myContent" class="tab-categories tab-link"><i class="material-icons">label</i></a>
<a id="tab-types" href="#myContent" class="tab-types tab-link"><i class="material-icons">flag</i></a>
<a id="tab-nat" href="#myContent" class="tab-nations tab-link"><i class="material-icons">language</i></a>
<a id="tab-fav" href="#myContent" class="tab-fav tab-link"><i class="material-icons">star</i></a>
</div>
</div>
<!-- First, we need to add Panel's overlay that will overlays app while panel is opened -->
<div class="panel-overlay"></div>
<!-- Left panel -->
<div class="panel panel-left panel-cover layout-dark">
<div class="list-block media-list">
<ul>
<li>
<a href="#" class="tab-all item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">Все рецепты</div>
</div>
</div>
</a>
</li>
<li>
<a href="#" class="tab-categories item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">Категории</div>
</div>
</div>
</a>
</li>
<li>
<a href="#" class="tab-types item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">Типы блюд</div>
</div>
</div>
</a>
</li>
<li>
<a href="#" class="tab-nations item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">Национальная кухня</div>
</div>
</div>
</a>
</li>
<li>
<a href="#" class="tab-history item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">История</div>
</div>
</div>
</a>
</li>
<li>
<a href="#" class="tab-fav item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">Избранные</div>
</div>
</div>
</a>
</li>
<li>
<a target="_system" href="https://play.google.com/store/apps/details?id=com.uartema.dish_pro" class="external tab-form item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">Поиск по ингридиентам</div>
</div>
</div>
</a>
</li>
<li>
<a href="#" class="tab-creds item-link item-content">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">О приложении</div>
</div>
</div>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Templates -->
<script id="categories" type="text/template7">
<div class="list-block media-list">
<ul>
{{#each categoies}}
<li>
<a class="item-link item-content" href="#" data-id="{{this.id}}">
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">
{{this.name}}
</div>
<div class="item-after">
{{this.cnt*1}}
</div>
</div>
</div>
</a>
</li>
{{/each}}
</ul>
</div>
</script>
<script id="recepts" type="text/template7">
{{#each recepts}}
<a data-id="{{this.recept.id}}" href="" class="recept-link card recept-card-header-pic">
<div style="background-image:url('http://r.uartema.com/photos/{{this.recept.photo}}')" valign="bottom" class="card-header color-white no-border">{{this.recept.name}}</div>
<div class="card-content">
<div class="card-content-inner">
<p class="color-gray">
{{#if this.category}}{{this.category.name}}{{/if}}{{#if this.nationality}}, {{this.nationality.name}} кухня{{/if}}
</p>
{{#if this.recept.description}}
<p class="color-black">{{this.recept.description}}</p>
{{/if}}
</div>
</div>
</a>
{{/each}}
</script>
<script id="recept" type="text/template7">
<div class="content-block">
<p>
<h1 class="recept-title">Рецепт</h1>
</p>
<div class="">время приготовления: {{recept.minut}}, {{recept.portion}} порций</div>
<a href="#" class="close-popup close-recept"><i class="material-icons">close</i></a>
</div>
<div class="content-block">
<a href="#" class="chip open-category" id="category-chip" style="display: none">
<span class="chip-label"></span>
</a>
<a href="#" class="chip open-nation" id="nation-chip" style="display: none">
<span class="chip-label"></span>
</a>
<a href="#" class="chip open-type" id="type-chip" style="display: none">
<span class="chip-label"></span>
</a>
</div>
<div class="content-block">
<img src="http://r.uartema.com/photos/{{recept.photo}}" style="width: 100%" />
</div>
{{#if recept.description}}
<div class="content-block">
<div class="content-block-inner">{{recept.description}}</div>
</div>
{{/if}}
<div class="content-block-title ingr-rel">Ингридиенты</div>
<div class="content-block inset ingr-rel"><div class="content-block-inner" id="ingrs"></div></div>
<div class="content-block-title">Пошаговая инструкция</div>
<div class="content-block inset"><div class="content-block-inner" id="steps"></div></div>
<div class="content-block inset"><div class="content-block-inner">
<p class="buttons-row">
<a href="#" data-id="{{recept.id}}" style="display:none" class="add-fav-rec button button-fill color-green">Сохранить</a>
<a href="#" data-id="{{recept.id}}" style="display:none" class="rm-fav-rec button button-fill color-blue">Убрать</a>
<a href="#" class="close-popup button button-fill color-orange">Закрыть</a>
</p>
</div></div>
</script>
<script id="ingrstpl" type="text/template7">
{{#each ingrds}}
<p>
{{this.ing.name}}
{{#if this.di.cnt}}
({{#if this.di.cnt}}{{this.di.cnt}} {{this.di.measure}}{{/if}}{{#if this.di.prim}}, {{this.di.prim}}{{/if}})
{{/if}}
</p>
{{/each}}
</script>
<script id="stepstpl" type="text/template7">
{{#each steps}}
<p>
{{@index+1}}:
{{#if this.photo}}
<img src="http://r.uartema.com/photos/{{this.photo}}" style="width: 100%">
{{/if}}
{{this.text}}
</p>
{{/each}}
</script>
<script id="creds" type="text/template7">
<div class="content-block-title">О приложении</div>
<div class="content-block-inner">
Разработано в <a class="external" target="_system" href="http://uartema.com">UArtema Software</a>
с использованием <a class="external" target="_system" href="https://framework7.io/">Framework7</a>,
<a class="external" target="_system" href="https://material.io/icons/">Material Icons</a>
и <a class="external" target="_system" href="http://phonegap.com/">Adobe PhoneGap</a>.
</div>
</script>
<!-- /Templates -->
<!-- Popup -->
<div class="popup popup-recept"></div>
<script type="text/javascript" src="cordova.js"></script>
<!-- Path to Framework7 Library JS-->
<script type="text/javascript" src="framework7/js/framework7.min.js"></script>
<!-- Path to your app js-->
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
|
{
"content_hash": "3fcbbeb2e987e77787a51e0408bf1721",
"timestamp": "",
"source": "github",
"line_count": 312,
"max_line_length": 187,
"avg_line_length": 41.67307692307692,
"alnum_prop": 0.4334717735732964,
"repo_name": "uavn/pg-dish",
"id": "6000fd8c88aca326aa9ed4125c069c64c72fc4d4",
"size": "13249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3033"
},
{
"name": "C",
"bytes": "4790"
},
{
"name": "C#",
"bytes": "429794"
},
{
"name": "C++",
"bytes": "432816"
},
{
"name": "CSS",
"bytes": "1881764"
},
{
"name": "HTML",
"bytes": "41187"
},
{
"name": "Java",
"bytes": "740072"
},
{
"name": "JavaScript",
"bytes": "1722821"
},
{
"name": "Objective-C",
"bytes": "784228"
},
{
"name": "QML",
"bytes": "15363"
}
],
"symlink_target": ""
}
|
using System.Linq;
using NUnit.Framework;
using SJP.Schematic.Core;
namespace SJP.Schematic.Oracle.Tests;
[TestFixture]
internal static class DefaultOracleIdentifierResolutionStrategyTests
{
[Test]
public static void GetResolutionOrder_GivenNullIdentifier_ThrowsArgumentNullException()
{
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
Assert.That(() => identifierResolver.GetResolutionOrder(null), Throws.ArgumentNullException);
}
[Test]
public static void GetResolutionOrder_GivenFullyUppercaseAndQualifiedIdentifier_ReturnsOneIdentifier()
{
var input = new Identifier("A", "B", "C", "D");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Has.Exactly(1).Items);
}
[Test]
public static void GetResolutionOrder_GivenFullyUppercaseAndQualifiedIdentifier_ReturnsIdentifierEqualToInput()
{
var input = new Identifier("A", "B", "C", "D");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result[0], Is.EqualTo(input));
}
[Test]
public static void GetResolutionOrder_GivenLowercaseServerIdentifier_ReturnsOneIdentifier()
{
var input = new Identifier("a", "B", "C", "D");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Has.Exactly(1).Items);
}
[Test]
public static void GetResolutionOrder_GivenLowercaseServerIdentifier_ReturnsIdentifierEqualToInput()
{
var input = new Identifier("a", "B", "C", "D");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result[0], Is.EqualTo(input));
}
[Test]
public static void GetResolutionOrder_GivenLowercaseDatabaseIdentifier_ReturnsOneIdentifier()
{
var input = new Identifier("A", "b", "C", "D");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Has.Exactly(1).Items);
}
[Test]
public static void GetResolutionOrder_GivenLowercaseDatabaseIdentifier_ReturnsUppercasedIdentifier()
{
var input = new Identifier("A", "b", "C", "D");
var expectedResults = new[] { new Identifier("A", "B", "C", "D") };
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Is.EqualTo(expectedResults));
}
[Test]
public static void GetResolutionOrder_GivenLowercaseSchemaIdentifier_ReturnsTwoIdentifiers()
{
var input = new Identifier("A", "B", "c", "D");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Has.Exactly(2).Items);
}
[Test]
public static void GetResolutionOrder_GivenLowercaseSchemaIdentifier_ReturnsUppercasedIdentifierAndIdentifierEqualToInput()
{
var input = new Identifier("A", "B", "c", "D");
var expectedResults = new[]
{
new Identifier("A", "B", "C", "D"),
input
};
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Is.EqualTo(expectedResults));
}
[Test]
public static void GetResolutionOrder_GivenLowercaseLocalNameIdentifier_ReturnsTwoIdentifiers()
{
var input = new Identifier("A", "B", "C", "d");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Has.Exactly(2).Items);
}
[Test]
public static void GetResolutionOrder_GivenLowercaseLocalNameIdentifier_ReturnsUppercasedIdentifierAndIdentifierEqualToInput()
{
var input = new Identifier("A", "B", "C", "d");
var expectedResults = new[]
{
new Identifier("A", "B", "C", "D"),
input
};
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Is.EqualTo(expectedResults));
}
[Test]
public static void GetResolutionOrder_GivenLowercaseSchemaAndLocalNameIdentifier_ReturnsFourIdentifiers()
{
var input = new Identifier("A", "B", "c", "d");
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Has.Exactly(4).Items);
}
[Test]
public static void GetResolutionOrder_GivenLowercaseSchemaAndLocalNameIdentifier_ReturnsExpectedResults()
{
var input = new Identifier("A", "B", "c", "d");
var expectedResults = new[]
{
new Identifier("A", "B", "C", "D"),
new Identifier("A", "B", "C", "d"),
new Identifier("A", "B", "c", "D"),
input
};
var identifierResolver = new DefaultOracleIdentifierResolutionStrategy();
var result = identifierResolver.GetResolutionOrder(input).ToList();
Assert.That(result, Is.EqualTo(expectedResults));
}
}
|
{
"content_hash": "36426b0bb34266c3574f00e643d911ac",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 130,
"avg_line_length": 35.28915662650602,
"alnum_prop": 0.6765107545237282,
"repo_name": "sjp/Schematic",
"id": "45fe70742f875635301f47138e7167d9530b94d4",
"size": "5860",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SJP.Schematic.Oracle.Tests/DefaultOracleIdentifierResolutionStrategyTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "390"
},
{
"name": "C#",
"bytes": "4826011"
},
{
"name": "CSS",
"bytes": "2985"
},
{
"name": "Dockerfile",
"bytes": "858"
},
{
"name": "HTML",
"bytes": "172575"
},
{
"name": "JavaScript",
"bytes": "23414"
},
{
"name": "Shell",
"bytes": "836"
}
],
"symlink_target": ""
}
|
set -eu
# FIXME: auto-random is only stable on master currently.
check_cluster_version 4 0 0 AUTO_RANDOM || exit 0
for backend in tidb importer local; do
if [ "$backend" = 'local' ]; then
check_cluster_version 4 0 0 'local backend' || continue
fi
run_sql 'DROP DATABASE IF EXISTS auto_random;'
run_lightning --backend $backend
run_sql "SELECT count(*) from auto_random.t"
check_contains "count(*): 6"
run_sql "SELECT id & b'000001111111111111111111111111111111111111111111111111111111111' as inc FROM auto_random.t"
check_contains 'inc: 1'
check_contains 'inc: 2'
check_contains 'inc: 3'
if [ "$backend" = 'tidb' ]; then
check_contains 'inc: 4'
check_contains 'inc: 5'
check_contains 'inc: 6'
NEXT_AUTO_RAND_VAL=7
else
check_contains 'inc: 25'
check_contains 'inc: 26'
check_contains 'inc: 27'
NEXT_AUTO_RAND_VAL=28
fi
# tidb backend randomly generate the auto-random bit for each statement, so with 2 statements,
# the distinct auto_random prefix values can be 1 or 2, so we skip this check with tidb backend
if [ "$backend" != 'tidb' ]; then
run_sql "select count(distinct id >> 58) as count from auto_random.t"
check_contains "count: 2"
fi
# auto random base is 4
run_sql "SELECT max(id & b'000001111111111111111111111111111111111111111111111111111111111') >= $NEXT_AUTO_RAND_VAL as ge FROM auto_random.t"
check_contains 'ge: 0'
run_sql "INSERT INTO auto_random.t VALUES ();"
run_sql "SELECT max(id & b'000001111111111111111111111111111111111111111111111111111111111') >= $NEXT_AUTO_RAND_VAL as ge FROM auto_random.t"
check_contains 'ge: 1'
done
|
{
"content_hash": "834239c5d4922b735379f760dc053e34",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 145,
"avg_line_length": 37.30434782608695,
"alnum_prop": 0.6742424242424242,
"repo_name": "coocood/tidb",
"id": "432582bf72e24d762a5481b224d31420f8a55a63",
"size": "2306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "br/tests/lightning_auto_random_default/run.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1272"
},
{
"name": "Go",
"bytes": "14251260"
},
{
"name": "Makefile",
"bytes": "9315"
},
{
"name": "Shell",
"bytes": "15615"
}
],
"symlink_target": ""
}
|
/**
* x is a value between 0 and 1, indicating where in the animation you are.
*/
var duScrollDefaultEasing = function (x) {
'use strict';
if(x < 0.5) {
return Math.pow(x*2, 2)/2;
}
return 1-Math.pow((1-x)*2, 2)/2;
};
angular.module('duScroll', [
'duScroll.scrollspy',
'duScroll.smoothScroll',
'duScroll.scrollContainer',
'duScroll.spyContext',
'duScroll.scrollHelpers'
])
//Default animation duration for smoothScroll directive
.value('duScrollDuration', 350)
//Scrollspy debounce interval, set to 0 to disable
.value('duScrollSpyWait', 100)
//Wether or not multiple scrollspies can be active at once
.value('duScrollGreedy', false)
//Default offset for smoothScroll directive
.value('duScrollOffset', 0)
//Default easing function for scroll animation
.value('duScrollEasing', duScrollDefaultEasing);
angular.module('duScroll.scrollHelpers', ['duScroll.requestAnimation'])
.run(["$window", "$q", "cancelAnimation", "requestAnimation", "duScrollEasing", "duScrollDuration", "duScrollOffset", function($window, $q, cancelAnimation, requestAnimation, duScrollEasing, duScrollDuration, duScrollOffset) {
'use strict';
var proto = angular.element.prototype;
var isDocument = function(el) {
return (typeof HTMLDocument !== 'undefined' && el instanceof HTMLDocument) || (el.nodeType && el.nodeType === el.DOCUMENT_NODE);
};
var isElement = function(el) {
return (typeof HTMLElement !== 'undefined' && el instanceof HTMLElement) || (el.nodeType && el.nodeType === el.ELEMENT_NODE);
};
var unwrap = function(el) {
return isElement(el) || isDocument(el) ? el : el[0];
};
proto.scrollTo = function(left, top, duration, easing) {
var aliasFn;
if(angular.isElement(left)) {
aliasFn = this.scrollToElement;
} else if(duration) {
aliasFn = this.scrollToAnimated;
}
if(aliasFn) {
return aliasFn.apply(this, arguments);
}
var el = unwrap(this);
if(isDocument(el)) {
return $window.scrollTo(left, top);
}
el.scrollLeft = left;
el.scrollTop = top;
};
var scrollAnimation, deferred;
proto.scrollToAnimated = function(left, top, duration, easing) {
if(duration && !easing) {
easing = duScrollEasing;
}
var startLeft = this.scrollLeft(),
startTop = this.scrollTop(),
deltaLeft = Math.round(left - startLeft),
deltaTop = Math.round(top - startTop);
var startTime = null;
var el = this;
var cancelOnEvents = 'scroll mousedown mousewheel touchmove keydown';
var cancelScrollAnimation = function($event) {
if (!$event || $event.which > 0) {
el.unbind(cancelOnEvents, cancelScrollAnimation);
cancelAnimation(scrollAnimation);
deferred.reject();
scrollAnimation = null;
}
};
if(scrollAnimation) {
cancelScrollAnimation();
}
deferred = $q.defer();
if(!deltaLeft && !deltaTop) {
deferred.resolve();
return deferred.promise;
}
var animationStep = function(timestamp) {
if (startTime === null) {
startTime = timestamp;
}
var progress = timestamp - startTime;
var percent = (progress >= duration ? 1 : easing(progress/duration));
el.scrollTo(
startLeft + Math.ceil(deltaLeft * percent),
startTop + Math.ceil(deltaTop * percent)
);
if(percent < 1) {
scrollAnimation = requestAnimation(animationStep);
} else {
el.unbind(cancelOnEvents, cancelScrollAnimation);
scrollAnimation = null;
deferred.resolve();
}
};
//Fix random mobile safari bug when scrolling to top by hitting status bar
el.scrollTo(startLeft, startTop);
el.bind(cancelOnEvents, cancelScrollAnimation);
scrollAnimation = requestAnimation(animationStep);
return deferred.promise;
};
proto.scrollToElement = function(target, offset, duration, easing) {
var el = unwrap(this);
if(!angular.isNumber(offset) || isNaN(offset)) {
offset = duScrollOffset;
}
var top = this.scrollTop() + unwrap(target).getBoundingClientRect().top - offset;
if(isElement(el)) {
top -= el.getBoundingClientRect().top;
}
return this.scrollTo(0, top, duration, easing);
};
var overloaders = {
scrollLeft: function(value, duration, easing) {
if(angular.isNumber(value)) {
return this.scrollTo(value, this.scrollTop(), duration, easing);
}
var el = unwrap(this);
if(isDocument(el)) {
return $window.scrollX || document.documentElement.scrollLeft || document.body.scrollLeft;
}
return el.scrollLeft;
},
scrollTop: function(value, duration, easing) {
if(angular.isNumber(value)) {
return this.scrollTo(this.scrollTop(), value, duration, easing);
}
var el = unwrap(this);
if(isDocument(el)) {
return $window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
}
return el.scrollTop;
}
};
proto.scrollToElementAnimated = function(target, offset, duration, easing) {
return this.scrollToElement(target, offset, duration || duScrollDuration, easing);
};
proto.scrollTopAnimated = function(top, duration, easing) {
return this.scrollTop(top, duration || duScrollDuration, easing);
};
proto.scrollLeftAnimated = function(left, duration, easing) {
return this.scrollLeft(left, duration || duScrollDuration, easing);
};
//Add duration and easing functionality to existing jQuery getter/setters
var overloadScrollPos = function(superFn, overloadFn) {
return function(value, duration, easing) {
if(duration) {
return overloadFn.apply(this, arguments);
}
return superFn.apply(this, arguments);
};
};
for(var methodName in overloaders) {
proto[methodName] = (proto[methodName] ? overloadScrollPos(proto[methodName], overloaders[methodName]) : overloaders[methodName]);
}
}]);
//Adapted from https://gist.github.com/paulirish/1579671
angular.module('duScroll.polyfill', [])
.factory('polyfill', ["$window", function($window) {
'use strict';
var vendors = ['webkit', 'moz', 'o', 'ms'];
return function(fnName, fallback) {
if($window[fnName]) {
return $window[fnName];
}
var suffix = fnName.substr(0, 1).toUpperCase() + fnName.substr(1);
for(var key, i = 0; i < vendors.length; i++) {
key = vendors[i]+suffix;
if($window[key]) {
return $window[key];
}
}
return fallback;
};
}]);
angular.module('duScroll.requestAnimation', ['duScroll.polyfill'])
.factory('requestAnimation', ["polyfill", "$timeout", function(polyfill, $timeout) {
'use strict';
var lastTime = 0;
var fallback = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = $timeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
return polyfill('requestAnimationFrame', fallback);
}])
.factory('cancelAnimation', ["polyfill", "$timeout", function(polyfill, $timeout) {
'use strict';
var fallback = function(promise) {
$timeout.cancel(promise);
};
return polyfill('cancelAnimationFrame', fallback);
}]);
angular.module('duScroll.spyAPI', ['duScroll.scrollContainerAPI'])
.factory('spyAPI', ["$rootScope", "$timeout", "scrollContainerAPI", "duScrollGreedy", "duScrollSpyWait", function($rootScope, $timeout, scrollContainerAPI, duScrollGreedy, duScrollSpyWait) {
'use strict';
var createScrollHandler = function(context) {
var timer = false, queued = false;
var handler = function() {
queued = false;
var container = context.container,
containerEl = container[0],
containerOffset = 0;
if (typeof HTMLElement !== 'undefined' && containerEl instanceof HTMLElement || containerEl.nodeType && containerEl.nodeType === containerEl.ELEMENT_NODE) {
containerOffset = containerEl.getBoundingClientRect().top;
}
var i, currentlyActive, toBeActive, spies, spy, pos;
spies = context.spies;
currentlyActive = context.currentlyActive;
toBeActive = undefined;
for(i = 0; i < spies.length; i++) {
spy = spies[i];
pos = spy.getTargetPosition();
if (!pos) continue;
if(pos.top + spy.offset - containerOffset < 20 && (pos.top*-1 + containerOffset) < pos.height) {
if(!toBeActive || toBeActive.top < pos.top) {
toBeActive = {
top: pos.top,
spy: spy
};
}
}
}
if(toBeActive) {
toBeActive = toBeActive.spy;
}
if(currentlyActive === toBeActive || (duScrollGreedy && !toBeActive)) return;
if(currentlyActive) {
currentlyActive.$element.removeClass('active');
$rootScope.$broadcast('duScrollspy:becameInactive', currentlyActive.$element);
}
if(toBeActive) {
toBeActive.$element.addClass('active');
$rootScope.$broadcast('duScrollspy:becameActive', toBeActive.$element);
}
context.currentlyActive = toBeActive;
};
if(!duScrollSpyWait) {
return handler;
}
//Debounce for potential performance savings
return function() {
if(!timer) {
handler();
timer = $timeout(function() {
timer = false;
if(queued) {
handler();
}
}, duScrollSpyWait, false);
} else {
queued = true;
}
};
};
var contexts = {};
var createContext = function($scope) {
var id = $scope.$id;
var context = {
spies: []
};
context.handler = createScrollHandler(context);
contexts[id] = context;
$scope.$on('$destroy', function() {
destroyContext($scope);
});
return id;
};
var destroyContext = function($scope) {
var id = $scope.$id;
var context = contexts[id], container = context.container;
if(container) {
container.off('scroll', context.handler);
}
delete contexts[id];
};
var defaultContextId = createContext($rootScope);
var getContextForScope = function(scope) {
if(contexts[scope.$id]) {
return contexts[scope.$id];
}
if(scope.$parent) {
return getContextForScope(scope.$parent);
}
return contexts[defaultContextId];
};
var getContextForSpy = function(spy) {
var context, contextId, scope = spy.$element.scope();
if(scope) {
return getContextForScope(scope);
}
//No scope, most likely destroyed
for(contextId in contexts) {
context = contexts[contextId];
if(context.spies.indexOf(spy) !== -1) {
return context;
}
}
};
var isElementInDocument = function(element) {
while (element.parentNode) {
element = element.parentNode;
if (element === document) {
return true;
}
}
return false;
};
var addSpy = function(spy) {
var context = getContextForSpy(spy);
if (!context) return;
context.spies.push(spy);
if (!context.container || !isElementInDocument(context.container)) {
if(context.container) {
context.container.off('scroll', context.handler);
}
context.container = scrollContainerAPI.getContainer(spy.$element.scope());
context.container.on('scroll', context.handler).triggerHandler('scroll');
}
};
var removeSpy = function(spy) {
var context = getContextForSpy(spy);
if(spy === context.currentlyActive) {
context.currentlyActive = null;
}
var i = context.spies.indexOf(spy);
if(i !== -1) {
context.spies.splice(i, 1);
}
};
return {
addSpy: addSpy,
removeSpy: removeSpy,
createContext: createContext,
destroyContext: destroyContext,
getContextForScope: getContextForScope
};
}]);
angular.module('duScroll.scrollContainerAPI', [])
.factory('scrollContainerAPI', ["$document", function($document) {
'use strict';
var containers = {};
var setContainer = function(scope, element) {
var id = scope.$id;
containers[id] = element;
return id;
};
var getContainerId = function(scope) {
if(containers[scope.$id]) {
return scope.$id;
}
if(scope.$parent) {
return getContainerId(scope.$parent);
}
return;
};
var getContainer = function(scope) {
var id = getContainerId(scope);
return id ? containers[id] : $document;
};
var removeContainer = function(scope) {
var id = getContainerId(scope);
if(id) {
delete containers[id];
}
};
return {
getContainerId: getContainerId,
getContainer: getContainer,
setContainer: setContainer,
removeContainer: removeContainer
};
}]);
angular.module('duScroll.smoothScroll', ['duScroll.scrollHelpers', 'duScroll.scrollContainerAPI'])
.directive('duSmoothScroll', ["duScrollDuration", "duScrollOffset", "scrollContainerAPI", function(duScrollDuration, duScrollOffset, scrollContainerAPI) {
'use strict';
return {
link : function($scope, $element, $attr) {
$element.on('click', function(e) {
if(!$attr.href || $attr.href.indexOf('#') === -1) return;
var target = document.getElementById($attr.href.replace(/.*(?=#[^\s]+$)/, '').substring(1));
if(!target || !target.getBoundingClientRect) return;
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
var offset = $attr.offset ? parseInt($attr.offset, 10) : duScrollOffset;
var duration = $attr.duration ? parseInt($attr.duration, 10) : duScrollDuration;
var container = scrollContainerAPI.getContainer($scope);
container.scrollToElement(
angular.element(target),
isNaN(offset) ? 0 : offset,
isNaN(duration) ? 0 : duration
);
});
}
};
}]);
angular.module('duScroll.spyContext', ['duScroll.spyAPI'])
.directive('duSpyContext', ["spyAPI", function(spyAPI) {
'use strict';
return {
restrict: 'A',
scope: true,
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink($scope, iElement, iAttrs, controller) {
spyAPI.createContext($scope);
}
};
}
};
}]);
angular.module('duScroll.scrollContainer', ['duScroll.scrollContainerAPI'])
.directive('duScrollContainer', ["scrollContainerAPI", function(scrollContainerAPI){
'use strict';
return {
restrict: 'A',
scope: true,
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink($scope, iElement, iAttrs, controller) {
iAttrs.$observe('duScrollContainer', function(element) {
if(angular.isString(element)) {
element = document.getElementById(element);
}
element = (angular.isElement(element) ? angular.element(element) : iElement);
scrollContainerAPI.setContainer($scope, element);
$scope.$on('$destroy', function() {
scrollContainerAPI.removeContainer($scope);
});
});
}
};
}
};
}]);
angular.module('duScroll.scrollspy', ['duScroll.spyAPI'])
.directive('duScrollspy', ["spyAPI", "duScrollOffset", "$timeout", "$rootScope", function(spyAPI, duScrollOffset, $timeout, $rootScope) {
'use strict';
var Spy = function(targetElementOrId, $element, offset) {
if(angular.isElement(targetElementOrId)) {
this.target = targetElementOrId;
} else if(angular.isString(targetElementOrId)) {
this.targetId = targetElementOrId;
}
this.$element = $element;
this.offset = offset;
};
Spy.prototype.getTargetElement = function() {
if (!this.target && this.targetId) {
this.target = document.getElementById(this.targetId);
}
return this.target;
};
Spy.prototype.getTargetPosition = function() {
var target = this.getTargetElement();
if(target) {
return target.getBoundingClientRect();
}
};
Spy.prototype.flushTargetCache = function() {
if(this.targetId) {
this.target = undefined;
}
};
return {
link: function ($scope, $element, $attr) {
var href = $attr.ngHref || $attr.href;
var targetId;
if (href && href.indexOf('#') !== -1) {
targetId = href.replace(/.*(?=#[^\s]+$)/, '').substring(1);
} else if($attr.duScrollspy) {
targetId = $attr.duScrollspy;
}
if(!targetId) return;
// Run this in the next execution loop so that the scroll context has a chance
// to initialize
$timeout(function() {
var spy = new Spy(targetId, $element, -($attr.offset ? parseInt($attr.offset, 10) : duScrollOffset));
spyAPI.addSpy(spy);
$scope.$on('$destroy', function() {
spyAPI.removeSpy(spy);
});
$scope.$on('$locationChangeSuccess', spy.flushTargetCache.bind(spy));
$rootScope.$on('$stateChangeSuccess', spy.flushTargetCache.bind(spy));
}, 0, false);
}
};
}]);
|
{
"content_hash": "18e7611479ecabe4d11e17ce8e3c815c",
"timestamp": "",
"source": "github",
"line_count": 589,
"max_line_length": 226,
"avg_line_length": 29.112054329371816,
"alnum_prop": 0.6299644252638945,
"repo_name": "apicatus/landing",
"id": "41feec94854ef4d0b2b9dd9b93ecc1d52ed667e0",
"size": "17147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/angular-scroll.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26438"
},
{
"name": "JavaScript",
"bytes": "313503"
}
],
"symlink_target": ""
}
|
package com.amazonaws.services.sagemaker.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.sagemaker.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateEndpointRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateEndpointRequestProtocolMarshaller implements Marshaller<Request<UpdateEndpointRequest>, UpdateEndpointRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).operationIdentifier("SageMaker.UpdateEndpoint")
.serviceName("AmazonSageMaker").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public UpdateEndpointRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<UpdateEndpointRequest> marshall(UpdateEndpointRequest updateEndpointRequest) {
if (updateEndpointRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<UpdateEndpointRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
updateEndpointRequest);
protocolMarshaller.startMarshalling();
UpdateEndpointRequestMarshaller.getInstance().marshall(updateEndpointRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
{
"content_hash": "6f6446315a99fa5d6506b349fe455391",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 152,
"avg_line_length": 40.40384615384615,
"alnum_prop": 0.7615421227986673,
"repo_name": "aws/aws-sdk-java",
"id": "90afc165dc29b570c74c6593e503944587aea82b",
"size": "2681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/transform/UpdateEndpointRequestProtocolMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
import React, {PropTypes, Component} from 'react';
require('./LiveEvents.scss');
export default class LiveEvents extends Component {
state = {
expanded: true
}
handleCollapseExpand = () => {
this.setState({
expanded: !this.state.expanded
});
}
render() {
let eventList = null;
let stateButtonLabel = '+';
if (this.state.expanded) {
stateButtonLabel = '-';
eventList = <div className="SSUI-LiveEvents-List">
{this.props.children}
</div>;
}
return (
<div className="SSUI-LiveEvents">
<div className="SSUI-LiveEvents-Header">
<div className="SSUI-LiveEvents-Header-Home">
<div className="SSUI-LiveEvents-Header-Logo">
<img src={this.props.homeTeam.logoUrl}/>
</div>
<div className="SSUI-LiveEvents-Header-Text">
<span>{this.props.homeTeam.name}</span>
</div>
</div>
<div className="SSUI-LiveEvents-Header-Data">
<div className="SSUI-LiveEvents-Header-Data-Score">
{this.props.matchData.score}
</div>
<div className="SSUI-LiveEvents-Header-Data-Time">
{this.props.matchData.time}
</div>
</div>
<div className="SSUI-LiveEvents-Header-Away">
<div className="SSUI-LiveEvents-Header-Logo">
<img src={this.props.awayTeam.logoUrl}/>
</div>
<div className="SSUI-LiveEvents-Header-Text">
<span>{this.props.awayTeam.name}</span>
</div>
</div>
<button className="SSUI-LiveEvents-List-ExpandCollapse" onClick={this.handleCollapseExpand}>{stateButtonLabel}</button>
</div>
{eventList}
</div>
);
}
}
|
{
"content_hash": "68a8f3e5d97033763735a2e12b0dce3f",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 139,
"avg_line_length": 37.35,
"alnum_prop": 0.4524765729585007,
"repo_name": "alexadam/live-score",
"id": "1d457b7091a4e8429d71807e0e5f884973aaf7f5",
"size": "2241",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/live-events/LiveEvents.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16005"
},
{
"name": "HTML",
"bytes": "1966"
},
{
"name": "JavaScript",
"bytes": "1960539"
}
],
"symlink_target": ""
}
|
"""
Module for the Poisson distribution node.
"""
import numpy as np
from scipy import special
from .expfamily import ExponentialFamily
from .expfamily import ExponentialFamilyDistribution
from .node import Moments
from .gamma import GammaMoments
from bayespy.utils import misc
class PoissonMoments(Moments):
"""
Class for the moments of Poisson variables
"""
dims = ( (), )
def compute_fixed_moments(self, x):
"""
Compute the moments for a fixed value
"""
# Make sure the values are integers in valid range
x = np.asanyarray(x)
if not misc.isinteger(x):
raise ValueError("Count not integer")
# Now, the moments are just the counts
return [x]
@classmethod
def from_values(cls, x):
"""
Return the shape of the moments for a fixed value.
The realizations are scalars, thus the shape of the moment is ().
"""
return cls()
class PoissonDistribution(ExponentialFamilyDistribution):
"""
Class for the VMP formulas of Poisson variables.
"""
def compute_message_to_parent(self, parent, index, u, u_lambda):
"""
Compute the message to a parent node.
"""
if index == 0:
m0 = -1
m1 = np.copy(u[0])
return [m0, m1]
else:
raise ValueError("Index out of bounds")
def compute_phi_from_parents(self, u_lambda, mask=True):
"""
Compute the natural parameter vector given parent moments.
"""
l = u_lambda[0]
logl = u_lambda[1]
phi0 = logl
return [phi0]
def compute_moments_and_cgf(self, phi, mask=True):
"""
Compute the moments and :math:`g(\phi)`.
"""
u0 = np.exp(phi[0])
u = [u0]
g = -u0
return (u, g)
def compute_cgf_from_parents(self, u_lambda):
"""
Compute :math:`\mathrm{E}_{q(p)}[g(p)]`
"""
l = u_lambda[0]
g = -l
return g
def compute_fixed_moments_and_f(self, x, mask=True):
"""
Compute the moments and :math:`f(x)` for a fixed value.
"""
# Check the validity of x
x = np.asanyarray(x)
if not misc.isinteger(x):
raise ValueError("Values must be integers")
if np.any(x < 0):
raise ValueError("Values must be positive")
# Compute moments
u0 = np.copy(x)
u = [u0]
# Compute f(x)
f = -special.gammaln(x+1)
return (u, f)
def random(self, *phi):
"""
Draw a random sample from the distribution.
"""
raise NotImplementedError()
class Poisson(ExponentialFamily):
"""
Node for Poisson random variables.
The node uses Poisson distribution:
.. math::
p(x) = \mathrm{Poisson}(x|\lambda)
where :math:`\lambda` is the rate parameter.
Parameters
----------
l : gamma-like node or scalar or array
:math:`\lambda`, rate parameter
See also
--------
Gamma, Exponential
"""
dims = ( (), )
_moments = PoissonMoments()
_parent_moments = [GammaMoments()]
_distribution = PoissonDistribution()
def __init__(self, l, **kwargs):
"""
Create Poisson random variable node
"""
super().__init__(l, **kwargs)
def __str__(self):
"""
Print the distribution using standard parameterization.
"""
l = self.u[0]
return ("%s ~ Categorical(lambda)\n"
" lambda =\n"
"%s\n"
% (self.name, l))
|
{
"content_hash": "882bec3c35ae5f0fbbd272bb836403bf",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 73,
"avg_line_length": 21.823529411764707,
"alnum_prop": 0.5358490566037736,
"repo_name": "dungvtdev/upsbayescpm",
"id": "9fc95ab2c6d52d36883036b24092fb3b043d783d",
"size": "3960",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bayespy/inference/vmp/nodes/poisson.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groff",
"bytes": "902"
},
{
"name": "Python",
"bytes": "2515965"
},
{
"name": "Shell",
"bytes": "66"
}
],
"symlink_target": ""
}
|
MogKit transformations are implemented using _Transducers_. This is what gives them the composable features and makes them independent of the underlying context.
For an [introduction to transducers](http://blog.cognitect.com/blog/2014/8/6/transducers-are-coming), see [Clojure - Transducers](http://clojure.org/transducers) and the presentation by Clojure creator [Rich Hickey](https://www.youtube.com/watch?v=6mTbuzafcII).
.. Add more
|
{
"content_hash": "6a4229f7203b018b7e214a3e033860bb",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 261,
"avg_line_length": 87.6,
"alnum_prop": 0.7945205479452054,
"repo_name": "mhallendal/MogKit",
"id": "a70fa38af1b2068129870071f6e9eee702a1b2ba",
"size": "438",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/creating-transformations.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "59322"
},
{
"name": "Ruby",
"bytes": "1639"
},
{
"name": "Shell",
"bytes": "2490"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html >
<html>
<head>
<link rel="stylesheet" href="demos.css" type="text/css" media="screen" />
<script src="../libraries/RGraph.common.core.js" ></script>
<script src="../libraries/RGraph.common.dynamic.js" ></script>
<script src="../libraries/RGraph.common.tooltips.js" ></script>
<script src="../libraries/RGraph.common.effects.js" ></script>
<script src="../libraries/RGraph.line.js" ></script>
<script src="/mps/libs/jquery-1.11.3/jquery-1.11.3.js"></script>
<!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]-->
<title>A spline Line chart with multiple lines given as an array</title>
<meta name="robots" content="noindex,nofollow" />
<meta name="description" content="A curvy Line chart (a spline) that has multiple lines. It uses the Line chart Trace effect. In this chart the arguments are given as one big multidimensional array" />
</head>
<body>
<h1>A spline Line chart with multiple lines given as an array</h1>
<p>
In this example the two datasets are given to the constructor as one big multidimensional array. This method can be useful
when you're using AJAX.
</p>
<canvas id="cvs" width="600" height="250">[No canvas support]</canvas>
<script>
$(document).ready(function ()
{
var dataset1 = [4,5,1,6,3,5,2];
var dataset2 = [7,7,8,6,2,1,1];
var line = new RGraph.Line({
id: 'cvs',
data: [dataset1, dataset2],
options: {
spline: true,
linewidth: 3,
hmargin: 5,
labels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],
tooltips: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],
tickmarks: 'circle',
ticksize: 5
}
}).trace2();
});
</script>
<p>
<a href="./">« Back</a>
</p>
<p></p>
This goes in the documents header (or you could place it just above the jQuery ready event code):
<pre class="code">
<script src="/mps/libs/jquery-1.11.3/jquery-1.11.3.js"></script>
<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.dynamic.js"></script>
<script src="RGraph.common.tooltips.js"></script>
<script src="RGraph.common.effects.js"></script>
<script src="RGraph.line.js"></script>
</pre>
Put this where you want the chart to show up:
<pre class="code">
<canvas id="cvs" width="600" height="250">
[No canvas support]
</canvas>
</pre>
This is the code that generates the chart. Because it's using the jQuery ready event you can put this at the
bottom of the document:
<pre class="code">
<script>
$(document).ready(function ()
{
var dataset1 = [4,5,1,6,3,5,2];
var dataset2 = [7,7,8,6,2,1,1];
var line = new RGraph.Line({
id: 'cvs',
data: [dataset1, dataset2],
options: {
spline: true,
linewidth: 3,
hmargin: 5,
labels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],
tooltips: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],
tickmarks: 'circle',
ticksize: 5
}
}).trace2();
});
</script>
</pre>
<p>
<a href="https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net" target="_blank" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net', null, 'top=50,left=50,width=600,height=368'); return false"><img src="../images/facebook-large.png" width="200" height="43" alt="Share on Facebook" border="0" title="Visit the RGraph Facebook page" /></a>
<a href="https://twitter.com/_rgraph" target="_blank" onclick="window.open('https://twitter.com/_rgraph', null, 'top=50,left=50,width=700,height=400'); return false"><img src="../images/twitter-large.png" width="200" height="43" alt="Share on Twitter" border="0" title="Mention RGraph on Twitter" /></a>
</p>
</body>
</html>
|
{
"content_hash": "a108aa8e8fac478879e6b23f7607eb58",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 396,
"avg_line_length": 37.35964912280702,
"alnum_prop": 0.5707912655552947,
"repo_name": "mabetle/mps",
"id": "9f8d3ee9762dae1d4a0b6acfa3a644deae1ade2d",
"size": "4259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_libs/RGraph-4.32/demos/line-spline-multiple-lines-array.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "912598"
},
{
"name": "HTML",
"bytes": "16579"
},
{
"name": "JavaScript",
"bytes": "2790381"
},
{
"name": "Makefile",
"bytes": "192"
}
],
"symlink_target": ""
}
|
package gov.hhs.onc.dcdt.mail.smtp;
import gov.hhs.onc.dcdt.beans.ToolIdentifier;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ObjectUtils;
public enum SmtpAuthMechanism implements ToolIdentifier {
PLAIN(null), LOGIN(null), GSSAPI(null), DIGEST_MD5("DIGEST-MD5"), MD5(null), CRAM_MD5("CRAM-MD5");
private final String id;
private SmtpAuthMechanism(@Nullable String id) {
this.id = ObjectUtils.defaultIfNull(id, this.name());
}
@Override
public String getId() {
return this.id;
}
}
|
{
"content_hash": "456b59a8628f18520e4fd7737114823a",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 102,
"avg_line_length": 27.55,
"alnum_prop": 0.7041742286751361,
"repo_name": "elizabethso/dcdt",
"id": "e3dc551fb4188557ff6f5e71d1ac3e3b46daeb47",
"size": "551",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dcdt-core/src/main/java/gov/hhs/onc/dcdt/mail/smtp/SmtpAuthMechanism.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7846"
},
{
"name": "Groovy",
"bytes": "18146"
},
{
"name": "Java",
"bytes": "1541925"
},
{
"name": "JavaScript",
"bytes": "54163"
}
],
"symlink_target": ""
}
|
"""
Based on SmBe19's RedditBots BotSkeleton
Requires an oauth.txt file to function
Written by /u/risos
"""
import re
import os
import time
import praw
import ast
import shutil
from pyTwistyScrambler import scrambler333
# Used for extracting the scramble from the webpage
# from bs4 import BeautifulSoup
# from urllib.request import urlopen
# Contains URLs that will go in the comment
from botConfig import *
# Can't find the relative files for some reason
cwd = os.getcwd() + '/'
USERAGENT = 'rubiks v0.3 by /u/risos'
SUBREDDIT = 'cubers'
# Number of posts to try before stopping
# Only useful for when AutoModerator breaks or something
POST_LIMIT = 40
def get_scramble():
"""
Generates a scramble using euphwes' pyTwistyScrambler module
"""
scramble = scrambler333.get_WCA_scramble()
# We can do this because scramble only contains ascii characters
return str(scramble)
def scramble_to_url(scramble):
"""
Parse the scramble and generate the alg.cubing.net url for it
"""
url = 'https://alg.cubing.net/?setup='
for i in scramble:
if i == '\'':
url += '-'
elif i == ' ':
url += '_'
else:
url += i
return url
def run_bot():
"""
Main function
"""
# Get the scramble and parse it
scramble = get_scramble()
scramble_url = scramble_to_url(scramble)
# Reddit stuff
r = praw.Reddit('rubiksBot', user_agent=USERAGENT)
sub = r.subreddit(SUBREDDIT)
posted = False
print('Starting bot for subreddit', SUBREDDIT, '\n')
# Main body
# Read the scramble day from the scramble_day.txt file which just holds an integer number
with open(cwd + 'scramble_day.txt', 'r') as f:
SCRAMBLE_DAY = f.read()
SCRAMBLE_DAY = SCRAMBLE_DAY.strip('\n')
if not os.path.isfile(cwd + 'posts_replied_to.txt'):
posts_replied_to = []
else:
with open(cwd + 'posts_replied_to.txt', 'r') as f:
posts_replied_to = f.read()
posts_replied_to = posts_replied_to.split('\n')
posts_replied_to = list(filter(None, posts_replied_to))
tries = 0
# For each new submission in chronological order (newest to oldest)
for submission in sub.new(limit=POST_LIMIT):
tries += 1
if tries > POST_LIMIT:
print(str(POST_LIMIT) + " post limit reached. Stopping bot.")
break
try:
if submission.id not in posts_replied_to:
if re.search('daily discussion thread', submission.title, re.IGNORECASE):
comment = '## Daily Scramble ' + str(SCRAMBLE_DAY) + '!\n\nScramble: [`' + scramble + '`](' + scramble_url + ')\n\nPlease count up your moves using [STM](' + STM_URL + ').\n'
postedComment = submission.reply(comment)
posted = True
print('\nBot replying to:', submission.title)
print('\nText:', comment)
# We only want to post on the most recent daily thread which is today's
break
except:
# I doubt this will ever happen
print('Ran out of posts')
break
# Only allowed to send 1 request per second
# Not sure if this really needs to be here, but better to be safe than sorry
print('Checking post...')
# So the bot doesn't post to the same daily thread twice
if posted:
posts_replied_to.append(submission.id)
with open(cwd + 'posts_replied_to.txt', 'w') as f:
for post_id in posts_replied_to:
f.write(post_id + '\n')
SCRAMBLE_DAY = str(int(SCRAMBLE_DAY) + 1)
with open(cwd + 'scramble_day.txt', 'w') as f:
f.write(SCRAMBLE_DAY + '\n')
else:
print('No comment was posted.')
if __name__ == '__main__':
if not USERAGENT:
print('Missing useragent')
elif not SUBREDDIT:
print('Missing subreddit')
else:
run_bot()
print('Bot finished running.')
|
{
"content_hash": "da75739667e66409b4c8867c0e235c57",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 194,
"avg_line_length": 29.496503496503497,
"alnum_prop": 0.5749170222854434,
"repo_name": "adamsko15/rubiksBot",
"id": "810c61909ea35553c39c3331f5adbd3d5fe8ef0f",
"size": "4241",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rubiksBot.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "4254"
}
],
"symlink_target": ""
}
|
//
// Created by Martin Miralles-Cordal on 4/19/2018.
//
#pragma once
#include <device/Device.hpp>
#include <device/storage/AtaDevice.hpp>
#include <cstdint>
#include <cstring>
#include "device/storage/AtaDeviceDescriptor.hpp"
#include "device/storage/AtapiCommand.hpp"
/** Representation of an ATA or ATAPI device for X86. */
class X86AtaDevice : public AtaDevice
{
public:
/**
* Gets the type of device in the given slot.
* @param primary Whether it's primary or secondary.
* @param master Whether it's master or slave.
* @return The probed type.
*/
static Type typeOf(bool primary, bool master);
/**
* Constructs a blank ATA device representation for the given slot.
* @param primary Whether it's primary or secondary.
* @param master Whether it's master or slave.
*/
X86AtaDevice(bool primary, bool master) : _primary(primary)
, _slaveBit(slaveBit(master)), _ioPort(ioPort(primary)), _controlPort(controlPort(primary)) {}
/**
* Returns whether the device is primary or secondary. Relevant only for P-ATA/P-ATAPI.
* @return true if primary, false otherwise.
*/
bool isPrimary() const override { return _primary; }
/**
* Returns whether the device is a master or slave. Relevant only for P-ATA/P-ATAPI.
* @return True if master, false if slave.
*/
bool isMaster() const override { return !_slaveBit; }
/**
* Returns whether or not there is a device attached in this slot.
* @return True if a device is there, false otherwise.
*/
virtual bool isAttached() const override;
/**
* The name of the device as reported by the device.
* @return A C string with the device's name.
*/
char const *model() override;
/**
* The serial code of the device reported by the device.
* @return A C string with the device's serial.
*/
char const *serial() override;
/**
* The firmware version of the device as reported by the device.
* @return A C string with the device's firmware version.
*/
char const *firmware() override;
/**
* The size of the device's sectors.
* @return An unsigned 32-bit integer with the sector size in bytes.
*/
uint32_t sectorSize() const override { return descriptor().sectorSize(); }
/**
* The type of device. [P-ATA, P-ATAPI, S-ATA, S-ATAPI, unknown]
* @return The Type enum value for this device.
*/
Type type() const override;
/**
* Reads in a sector.
* @param address The linear block address of the sector to read.
* @param buf The buffer to store the fetched data in. It should be at least
* the size of the device sector.
* @param sectors The number of sectors to read. Defaults to 1.
* @return true if successful, false otherwise.
*/
bool read(uint64_t address, uint16_t *buf, size_t sectors = 1) override;
private:
AtaDeviceDescriptor &descriptor() const
{
if (!_identified) identify();
return _descriptor;
}
// ====================================================
// ATA base ports and bits
// ====================================================
static uint8_t slaveBit(bool master) { return static_cast<uint8_t>(master ? 0 : 1); }
static uint16_t ioPort(bool primary) { return static_cast<uint16_t>(primary ? 0x1F0 : 0x170); }
static uint16_t controlPort(bool primary) { return static_cast<uint16_t>(primary ? 0x3F6 : 0x376); }
// ====================================================
// ATA IO port offsets (port = ioPort() + kFoo)
// ====================================================
static constexpr uint8_t kAtaRegisterDataPort = 0x00;
static constexpr uint8_t kAtaRegisterFeatureInfo = 0x01;
static constexpr uint8_t kAtaRegisterSectorCount = 0x02;
static constexpr uint8_t kAtaRegisterLbaLow = 0x03;
static constexpr uint8_t kAtaRegisterSectorNo = 0x03;
static constexpr uint8_t kAtaRegisterLbaMid = 0x04;
static constexpr uint8_t kAtaRegisterCylinderLow = 0x04;
static constexpr uint8_t kAtaRegisterLbaHigh = 0x05;
static constexpr uint8_t kAtaRegisterCylinderHigh = 0x05;
static constexpr uint8_t kAtaRegisterDriveSelect = 0x06;
static constexpr uint8_t kAtaRegisterStatus = 0x07;
static constexpr uint8_t kAtaRegisterCommand = 0x07;
// ====================================================
// Status byte bits
// ====================================================
/**
* Indicates the drive is preparing to send/receive data (wait for it to clear).
* In case of 'hang' (it never clears), do a software reset.
*/
static constexpr uint8_t kAtaStatusBitBusy = 0x80; // bit 7
/** Bit is clear when drive is spun down, or after an error. Set otherwise. */
static constexpr uint8_t kAtaStatusBitReady = 0x40; // bit 6
/** Drive Fault Error (does not set ERR). */
static constexpr uint8_t kAtaStatusBitDriveFault = 0x20; // bit 5
/** Overlapped Mode Service Request. */
static constexpr uint8_t kAtaStatusBitSRV = 0x10; // bit 4
/** Set when the drive has PIO data to transfer, or is ready to accept PIO data. */
static constexpr uint8_t kAtaStatusBitDRQ = 0x08; // bit 3
/** Indicates an error occurred. Send a new command to clear it (or nuke it with a Software Reset). */
static constexpr uint8_t kAtaStatusBitError = 0x01; // bit 0
/**
* Waits for the device to not be busy, then returns the status.
* @param timeout The number of attempts to make (1 attempt ~ 100ns). Set to
* -1 for no timeout.
* @return The device status.
*/
uint8_t waitForStatus(int timeout) const;
/** Performs the IO operations to soft reset the ATA device. */
void softReset() const;
/**
* Waits for the device to be ready.
* @param errorCheck Additionally check that the device is not in an error state.
* @return 0 if the device is in a good state, 1 if in an error state.
*/
uint8_t waitUntilReady(bool errorCheck) const;
/** Waits roughly 400ns by polling 4 times. */
void ioWait() const;
/** Identifies the device's name, model, firmware. */
void identify() const;
/**
* Sends an ATA PACKET command plus the corresponding ATAPI command.
* @param cmd The AtapiCommand to send
* @param buf The buffer to read WORDS (uint16_t) into.
* @param bufSize The size of the PIO buffer, in BYTES.
* @return true if success, false if error
*/
bool performPioAtapiOperation(const AtapiCommand &cmd, uint16_t *buf,
size_t bufSize) const;
/**
* Reads in data via PIO from the device.
* @param buf The buffer to read WORDS into.
* @param bytesToRead The amount of data to read, in BYTES. Should be
* divisible by 2, as we read in 2-byte words.
*/
void pioRead(uint16_t *buf, uint32_t bytesToRead) const;
/**
* Writes out data via PIO to the device.
* @param buf The buffer to read WORDS from.
* @param bytesToRead The amount of data to write, in BYTES. Should be
* divisible by 2, as we write out in 2-byte words.
*/
void pioWrite(uint16_t *buf, uint32_t bytesToRead) const;
bool readInternal(uint64_t address, uint16_t *buf, size_t sectors);
bool const _primary;
uint16_t const _slaveBit;
uint16_t const _ioPort;
uint16_t const _controlPort;
mutable bool _identified = false;
mutable AtaDeviceDescriptor _descriptor{true};
};
|
{
"content_hash": "2609f3097265733c49047c1ab5465eea",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 106,
"avg_line_length": 37.6,
"alnum_prop": 0.6227296315516346,
"repo_name": "axalon900/LambOS",
"id": "9bc9d57e6092bdcfb2fd59a33f395404a7de59d3",
"size": "7708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kernel/include/arch/i386/device/storage/X86AtaDevice.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "11519"
},
{
"name": "C",
"bytes": "62707"
},
{
"name": "C++",
"bytes": "366889"
},
{
"name": "CMake",
"bytes": "16750"
},
{
"name": "Shell",
"bytes": "344"
}
],
"symlink_target": ""
}
|
// *** THIS FILE IS GENERATED - DO NOT EDIT ***
// See object_tracker_generator.py for modifications
void PostCallRecordCreateInstance(
const VkInstanceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkInstance* pInstance,
VkResult result);
bool PreCallValidateDestroyInstance(
VkInstance instance,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyInstance(
VkInstance instance,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateEnumeratePhysicalDevices(
VkInstance instance,
uint32_t* pPhysicalDeviceCount,
VkPhysicalDevice* pPhysicalDevices) const;
void PostCallRecordEnumeratePhysicalDevices(
VkInstance instance,
uint32_t* pPhysicalDeviceCount,
VkPhysicalDevice* pPhysicalDevices,
VkResult result);
bool PreCallValidateGetPhysicalDeviceFeatures(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceFeatures* pFeatures) const;
bool PreCallValidateGetPhysicalDeviceFormatProperties(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties* pFormatProperties) const;
bool PreCallValidateGetPhysicalDeviceImageFormatProperties(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkImageType type,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkImageFormatProperties* pImageFormatProperties) const;
bool PreCallValidateGetPhysicalDeviceProperties(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties* pProperties) const;
bool PreCallValidateGetPhysicalDeviceQueueFamilyProperties(
VkPhysicalDevice physicalDevice,
uint32_t* pQueueFamilyPropertyCount,
VkQueueFamilyProperties* pQueueFamilyProperties) const;
bool PreCallValidateGetPhysicalDeviceMemoryProperties(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties* pMemoryProperties) const;
bool PreCallValidateGetInstanceProcAddr(
VkInstance instance,
const char* pName) const;
bool PreCallValidateGetDeviceProcAddr(
VkDevice device,
const char* pName) const;
bool PreCallValidateCreateDevice(
VkPhysicalDevice physicalDevice,
const VkDeviceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDevice* pDevice) const;
void PostCallRecordCreateDevice(
VkPhysicalDevice physicalDevice,
const VkDeviceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDevice* pDevice,
VkResult result);
bool PreCallValidateDestroyDevice(
VkDevice device,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDevice(
VkDevice device,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateEnumerateDeviceExtensionProperties(
VkPhysicalDevice physicalDevice,
const char* pLayerName,
uint32_t* pPropertyCount,
VkExtensionProperties* pProperties) const;
bool PreCallValidateEnumerateDeviceLayerProperties(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkLayerProperties* pProperties) const;
bool PreCallValidateGetDeviceQueue(
VkDevice device,
uint32_t queueFamilyIndex,
uint32_t queueIndex,
VkQueue* pQueue) const;
void PostCallRecordGetDeviceQueue(
VkDevice device,
uint32_t queueFamilyIndex,
uint32_t queueIndex,
VkQueue* pQueue);
bool PreCallValidateQueueSubmit(
VkQueue queue,
uint32_t submitCount,
const VkSubmitInfo* pSubmits,
VkFence fence) const;
bool PreCallValidateQueueWaitIdle(
VkQueue queue) const;
bool PreCallValidateDeviceWaitIdle(
VkDevice device) const;
bool PreCallValidateAllocateMemory(
VkDevice device,
const VkMemoryAllocateInfo* pAllocateInfo,
const VkAllocationCallbacks* pAllocator,
VkDeviceMemory* pMemory) const;
void PostCallRecordAllocateMemory(
VkDevice device,
const VkMemoryAllocateInfo* pAllocateInfo,
const VkAllocationCallbacks* pAllocator,
VkDeviceMemory* pMemory,
VkResult result);
bool PreCallValidateFreeMemory(
VkDevice device,
VkDeviceMemory memory,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordFreeMemory(
VkDevice device,
VkDeviceMemory memory,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateMapMemory(
VkDevice device,
VkDeviceMemory memory,
VkDeviceSize offset,
VkDeviceSize size,
VkMemoryMapFlags flags,
void** ppData) const;
bool PreCallValidateUnmapMemory(
VkDevice device,
VkDeviceMemory memory) const;
bool PreCallValidateFlushMappedMemoryRanges(
VkDevice device,
uint32_t memoryRangeCount,
const VkMappedMemoryRange* pMemoryRanges) const;
bool PreCallValidateInvalidateMappedMemoryRanges(
VkDevice device,
uint32_t memoryRangeCount,
const VkMappedMemoryRange* pMemoryRanges) const;
bool PreCallValidateGetDeviceMemoryCommitment(
VkDevice device,
VkDeviceMemory memory,
VkDeviceSize* pCommittedMemoryInBytes) const;
bool PreCallValidateBindBufferMemory(
VkDevice device,
VkBuffer buffer,
VkDeviceMemory memory,
VkDeviceSize memoryOffset) const;
bool PreCallValidateBindImageMemory(
VkDevice device,
VkImage image,
VkDeviceMemory memory,
VkDeviceSize memoryOffset) const;
bool PreCallValidateGetBufferMemoryRequirements(
VkDevice device,
VkBuffer buffer,
VkMemoryRequirements* pMemoryRequirements) const;
bool PreCallValidateGetImageMemoryRequirements(
VkDevice device,
VkImage image,
VkMemoryRequirements* pMemoryRequirements) const;
bool PreCallValidateGetImageSparseMemoryRequirements(
VkDevice device,
VkImage image,
uint32_t* pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements* pSparseMemoryRequirements) const;
bool PreCallValidateGetPhysicalDeviceSparseImageFormatProperties(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkImageType type,
VkSampleCountFlagBits samples,
VkImageUsageFlags usage,
VkImageTiling tiling,
uint32_t* pPropertyCount,
VkSparseImageFormatProperties* pProperties) const;
bool PreCallValidateQueueBindSparse(
VkQueue queue,
uint32_t bindInfoCount,
const VkBindSparseInfo* pBindInfo,
VkFence fence) const;
bool PreCallValidateCreateFence(
VkDevice device,
const VkFenceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence) const;
void PostCallRecordCreateFence(
VkDevice device,
const VkFenceCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence,
VkResult result);
bool PreCallValidateDestroyFence(
VkDevice device,
VkFence fence,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyFence(
VkDevice device,
VkFence fence,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateResetFences(
VkDevice device,
uint32_t fenceCount,
const VkFence* pFences) const;
bool PreCallValidateGetFenceStatus(
VkDevice device,
VkFence fence) const;
bool PreCallValidateWaitForFences(
VkDevice device,
uint32_t fenceCount,
const VkFence* pFences,
VkBool32 waitAll,
uint64_t timeout) const;
bool PreCallValidateCreateSemaphore(
VkDevice device,
const VkSemaphoreCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSemaphore* pSemaphore) const;
void PostCallRecordCreateSemaphore(
VkDevice device,
const VkSemaphoreCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSemaphore* pSemaphore,
VkResult result);
bool PreCallValidateDestroySemaphore(
VkDevice device,
VkSemaphore semaphore,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroySemaphore(
VkDevice device,
VkSemaphore semaphore,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateEvent(
VkDevice device,
const VkEventCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkEvent* pEvent) const;
void PostCallRecordCreateEvent(
VkDevice device,
const VkEventCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkEvent* pEvent,
VkResult result);
bool PreCallValidateDestroyEvent(
VkDevice device,
VkEvent event,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyEvent(
VkDevice device,
VkEvent event,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetEventStatus(
VkDevice device,
VkEvent event) const;
bool PreCallValidateSetEvent(
VkDevice device,
VkEvent event) const;
bool PreCallValidateResetEvent(
VkDevice device,
VkEvent event) const;
bool PreCallValidateCreateQueryPool(
VkDevice device,
const VkQueryPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkQueryPool* pQueryPool) const;
void PostCallRecordCreateQueryPool(
VkDevice device,
const VkQueryPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkQueryPool* pQueryPool,
VkResult result);
bool PreCallValidateDestroyQueryPool(
VkDevice device,
VkQueryPool queryPool,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyQueryPool(
VkDevice device,
VkQueryPool queryPool,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetQueryPoolResults(
VkDevice device,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount,
size_t dataSize,
void* pData,
VkDeviceSize stride,
VkQueryResultFlags flags) const;
bool PreCallValidateCreateBuffer(
VkDevice device,
const VkBufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBuffer* pBuffer) const;
void PostCallRecordCreateBuffer(
VkDevice device,
const VkBufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBuffer* pBuffer,
VkResult result);
bool PreCallValidateDestroyBuffer(
VkDevice device,
VkBuffer buffer,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyBuffer(
VkDevice device,
VkBuffer buffer,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateBufferView(
VkDevice device,
const VkBufferViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBufferView* pView) const;
void PostCallRecordCreateBufferView(
VkDevice device,
const VkBufferViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkBufferView* pView,
VkResult result);
bool PreCallValidateDestroyBufferView(
VkDevice device,
VkBufferView bufferView,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyBufferView(
VkDevice device,
VkBufferView bufferView,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateImage(
VkDevice device,
const VkImageCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImage* pImage) const;
void PostCallRecordCreateImage(
VkDevice device,
const VkImageCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImage* pImage,
VkResult result);
bool PreCallValidateDestroyImage(
VkDevice device,
VkImage image,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyImage(
VkDevice device,
VkImage image,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetImageSubresourceLayout(
VkDevice device,
VkImage image,
const VkImageSubresource* pSubresource,
VkSubresourceLayout* pLayout) const;
bool PreCallValidateCreateImageView(
VkDevice device,
const VkImageViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImageView* pView) const;
void PostCallRecordCreateImageView(
VkDevice device,
const VkImageViewCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkImageView* pView,
VkResult result);
bool PreCallValidateDestroyImageView(
VkDevice device,
VkImageView imageView,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyImageView(
VkDevice device,
VkImageView imageView,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateShaderModule(
VkDevice device,
const VkShaderModuleCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkShaderModule* pShaderModule) const;
void PostCallRecordCreateShaderModule(
VkDevice device,
const VkShaderModuleCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkShaderModule* pShaderModule,
VkResult result);
bool PreCallValidateDestroyShaderModule(
VkDevice device,
VkShaderModule shaderModule,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyShaderModule(
VkDevice device,
VkShaderModule shaderModule,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreatePipelineCache(
VkDevice device,
const VkPipelineCacheCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineCache* pPipelineCache) const;
void PostCallRecordCreatePipelineCache(
VkDevice device,
const VkPipelineCacheCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineCache* pPipelineCache,
VkResult result);
bool PreCallValidateDestroyPipelineCache(
VkDevice device,
VkPipelineCache pipelineCache,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyPipelineCache(
VkDevice device,
VkPipelineCache pipelineCache,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetPipelineCacheData(
VkDevice device,
VkPipelineCache pipelineCache,
size_t* pDataSize,
void* pData) const;
bool PreCallValidateMergePipelineCaches(
VkDevice device,
VkPipelineCache dstCache,
uint32_t srcCacheCount,
const VkPipelineCache* pSrcCaches) const;
bool PreCallValidateCreateGraphicsPipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) const;
void PostCallRecordCreateGraphicsPipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines,
VkResult result);
bool PreCallValidateCreateComputePipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) const;
void PostCallRecordCreateComputePipelines(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines,
VkResult result);
bool PreCallValidateDestroyPipeline(
VkDevice device,
VkPipeline pipeline,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyPipeline(
VkDevice device,
VkPipeline pipeline,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreatePipelineLayout(
VkDevice device,
const VkPipelineLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineLayout* pPipelineLayout) const;
void PostCallRecordCreatePipelineLayout(
VkDevice device,
const VkPipelineLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineLayout* pPipelineLayout,
VkResult result);
bool PreCallValidateDestroyPipelineLayout(
VkDevice device,
VkPipelineLayout pipelineLayout,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyPipelineLayout(
VkDevice device,
VkPipelineLayout pipelineLayout,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateSampler(
VkDevice device,
const VkSamplerCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSampler* pSampler) const;
void PostCallRecordCreateSampler(
VkDevice device,
const VkSamplerCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSampler* pSampler,
VkResult result);
bool PreCallValidateDestroySampler(
VkDevice device,
VkSampler sampler,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroySampler(
VkDevice device,
VkSampler sampler,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateDescriptorSetLayout(
VkDevice device,
const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorSetLayout* pSetLayout) const;
void PostCallRecordCreateDescriptorSetLayout(
VkDevice device,
const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorSetLayout* pSetLayout,
VkResult result);
bool PreCallValidateDestroyDescriptorSetLayout(
VkDevice device,
VkDescriptorSetLayout descriptorSetLayout,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDescriptorSetLayout(
VkDevice device,
VkDescriptorSetLayout descriptorSetLayout,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateDescriptorPool(
VkDevice device,
const VkDescriptorPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorPool* pDescriptorPool) const;
void PostCallRecordCreateDescriptorPool(
VkDevice device,
const VkDescriptorPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorPool* pDescriptorPool,
VkResult result);
bool PreCallValidateDestroyDescriptorPool(
VkDevice device,
VkDescriptorPool descriptorPool,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDescriptorPool(
VkDevice device,
VkDescriptorPool descriptorPool,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateResetDescriptorPool(
VkDevice device,
VkDescriptorPool descriptorPool,
VkDescriptorPoolResetFlags flags) const;
bool PreCallValidateAllocateDescriptorSets(
VkDevice device,
const VkDescriptorSetAllocateInfo* pAllocateInfo,
VkDescriptorSet* pDescriptorSets) const;
void PostCallRecordAllocateDescriptorSets(
VkDevice device,
const VkDescriptorSetAllocateInfo* pAllocateInfo,
VkDescriptorSet* pDescriptorSets,
VkResult result);
bool PreCallValidateFreeDescriptorSets(
VkDevice device,
VkDescriptorPool descriptorPool,
uint32_t descriptorSetCount,
const VkDescriptorSet* pDescriptorSets) const;
bool PreCallValidateUpdateDescriptorSets(
VkDevice device,
uint32_t descriptorWriteCount,
const VkWriteDescriptorSet* pDescriptorWrites,
uint32_t descriptorCopyCount,
const VkCopyDescriptorSet* pDescriptorCopies) const;
bool PreCallValidateCreateFramebuffer(
VkDevice device,
const VkFramebufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFramebuffer* pFramebuffer) const;
void PostCallRecordCreateFramebuffer(
VkDevice device,
const VkFramebufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFramebuffer* pFramebuffer,
VkResult result);
bool PreCallValidateDestroyFramebuffer(
VkDevice device,
VkFramebuffer framebuffer,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyFramebuffer(
VkDevice device,
VkFramebuffer framebuffer,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateRenderPass(
VkDevice device,
const VkRenderPassCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass) const;
void PostCallRecordCreateRenderPass(
VkDevice device,
const VkRenderPassCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass,
VkResult result);
bool PreCallValidateDestroyRenderPass(
VkDevice device,
VkRenderPass renderPass,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyRenderPass(
VkDevice device,
VkRenderPass renderPass,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetRenderAreaGranularity(
VkDevice device,
VkRenderPass renderPass,
VkExtent2D* pGranularity) const;
bool PreCallValidateCreateCommandPool(
VkDevice device,
const VkCommandPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkCommandPool* pCommandPool) const;
void PostCallRecordCreateCommandPool(
VkDevice device,
const VkCommandPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkCommandPool* pCommandPool,
VkResult result);
bool PreCallValidateDestroyCommandPool(
VkDevice device,
VkCommandPool commandPool,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyCommandPool(
VkDevice device,
VkCommandPool commandPool,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateResetCommandPool(
VkDevice device,
VkCommandPool commandPool,
VkCommandPoolResetFlags flags) const;
bool PreCallValidateAllocateCommandBuffers(
VkDevice device,
const VkCommandBufferAllocateInfo* pAllocateInfo,
VkCommandBuffer* pCommandBuffers) const;
void PostCallRecordAllocateCommandBuffers(
VkDevice device,
const VkCommandBufferAllocateInfo* pAllocateInfo,
VkCommandBuffer* pCommandBuffers,
VkResult result);
bool PreCallValidateFreeCommandBuffers(
VkDevice device,
VkCommandPool commandPool,
uint32_t commandBufferCount,
const VkCommandBuffer* pCommandBuffers) const;
bool PreCallValidateBeginCommandBuffer(
VkCommandBuffer commandBuffer,
const VkCommandBufferBeginInfo* pBeginInfo) const;
bool PreCallValidateEndCommandBuffer(
VkCommandBuffer commandBuffer) const;
bool PreCallValidateResetCommandBuffer(
VkCommandBuffer commandBuffer,
VkCommandBufferResetFlags flags) const;
bool PreCallValidateCmdBindPipeline(
VkCommandBuffer commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
VkPipeline pipeline) const;
bool PreCallValidateCmdSetViewport(
VkCommandBuffer commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const VkViewport* pViewports) const;
bool PreCallValidateCmdSetScissor(
VkCommandBuffer commandBuffer,
uint32_t firstScissor,
uint32_t scissorCount,
const VkRect2D* pScissors) const;
bool PreCallValidateCmdSetLineWidth(
VkCommandBuffer commandBuffer,
float lineWidth) const;
bool PreCallValidateCmdSetDepthBias(
VkCommandBuffer commandBuffer,
float depthBiasConstantFactor,
float depthBiasClamp,
float depthBiasSlopeFactor) const;
bool PreCallValidateCmdSetBlendConstants(
VkCommandBuffer commandBuffer,
const float blendConstants[4]) const;
bool PreCallValidateCmdSetDepthBounds(
VkCommandBuffer commandBuffer,
float minDepthBounds,
float maxDepthBounds) const;
bool PreCallValidateCmdSetStencilCompareMask(
VkCommandBuffer commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t compareMask) const;
bool PreCallValidateCmdSetStencilWriteMask(
VkCommandBuffer commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t writeMask) const;
bool PreCallValidateCmdSetStencilReference(
VkCommandBuffer commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t reference) const;
bool PreCallValidateCmdBindDescriptorSets(
VkCommandBuffer commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout,
uint32_t firstSet,
uint32_t descriptorSetCount,
const VkDescriptorSet* pDescriptorSets,
uint32_t dynamicOffsetCount,
const uint32_t* pDynamicOffsets) const;
bool PreCallValidateCmdBindIndexBuffer(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkIndexType indexType) const;
bool PreCallValidateCmdBindVertexBuffers(
VkCommandBuffer commandBuffer,
uint32_t firstBinding,
uint32_t bindingCount,
const VkBuffer* pBuffers,
const VkDeviceSize* pOffsets) const;
bool PreCallValidateCmdDraw(
VkCommandBuffer commandBuffer,
uint32_t vertexCount,
uint32_t instanceCount,
uint32_t firstVertex,
uint32_t firstInstance) const;
bool PreCallValidateCmdDrawIndexed(
VkCommandBuffer commandBuffer,
uint32_t indexCount,
uint32_t instanceCount,
uint32_t firstIndex,
int32_t vertexOffset,
uint32_t firstInstance) const;
bool PreCallValidateCmdDrawIndirect(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride) const;
bool PreCallValidateCmdDrawIndexedIndirect(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride) const;
bool PreCallValidateCmdDispatch(
VkCommandBuffer commandBuffer,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ) const;
bool PreCallValidateCmdDispatchIndirect(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset) const;
bool PreCallValidateCmdCopyBuffer(
VkCommandBuffer commandBuffer,
VkBuffer srcBuffer,
VkBuffer dstBuffer,
uint32_t regionCount,
const VkBufferCopy* pRegions) const;
bool PreCallValidateCmdCopyImage(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageCopy* pRegions) const;
bool PreCallValidateCmdBlitImage(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageBlit* pRegions,
VkFilter filter) const;
bool PreCallValidateCmdCopyBufferToImage(
VkCommandBuffer commandBuffer,
VkBuffer srcBuffer,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkBufferImageCopy* pRegions) const;
bool PreCallValidateCmdCopyImageToBuffer(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkBuffer dstBuffer,
uint32_t regionCount,
const VkBufferImageCopy* pRegions) const;
bool PreCallValidateCmdUpdateBuffer(
VkCommandBuffer commandBuffer,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize dataSize,
const void* pData) const;
bool PreCallValidateCmdFillBuffer(
VkCommandBuffer commandBuffer,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize size,
uint32_t data) const;
bool PreCallValidateCmdClearColorImage(
VkCommandBuffer commandBuffer,
VkImage image,
VkImageLayout imageLayout,
const VkClearColorValue* pColor,
uint32_t rangeCount,
const VkImageSubresourceRange* pRanges) const;
bool PreCallValidateCmdClearDepthStencilImage(
VkCommandBuffer commandBuffer,
VkImage image,
VkImageLayout imageLayout,
const VkClearDepthStencilValue* pDepthStencil,
uint32_t rangeCount,
const VkImageSubresourceRange* pRanges) const;
bool PreCallValidateCmdClearAttachments(
VkCommandBuffer commandBuffer,
uint32_t attachmentCount,
const VkClearAttachment* pAttachments,
uint32_t rectCount,
const VkClearRect* pRects) const;
bool PreCallValidateCmdResolveImage(
VkCommandBuffer commandBuffer,
VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageResolve* pRegions) const;
bool PreCallValidateCmdSetEvent(
VkCommandBuffer commandBuffer,
VkEvent event,
VkPipelineStageFlags stageMask) const;
bool PreCallValidateCmdResetEvent(
VkCommandBuffer commandBuffer,
VkEvent event,
VkPipelineStageFlags stageMask) const;
bool PreCallValidateCmdWaitEvents(
VkCommandBuffer commandBuffer,
uint32_t eventCount,
const VkEvent* pEvents,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
uint32_t memoryBarrierCount,
const VkMemoryBarrier* pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const VkBufferMemoryBarrier* pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const VkImageMemoryBarrier* pImageMemoryBarriers) const;
bool PreCallValidateCmdPipelineBarrier(
VkCommandBuffer commandBuffer,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
VkDependencyFlags dependencyFlags,
uint32_t memoryBarrierCount,
const VkMemoryBarrier* pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const VkBufferMemoryBarrier* pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const VkImageMemoryBarrier* pImageMemoryBarriers) const;
bool PreCallValidateCmdBeginQuery(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query,
VkQueryControlFlags flags) const;
bool PreCallValidateCmdEndQuery(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query) const;
bool PreCallValidateCmdResetQueryPool(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount) const;
bool PreCallValidateCmdWriteTimestamp(
VkCommandBuffer commandBuffer,
VkPipelineStageFlagBits pipelineStage,
VkQueryPool queryPool,
uint32_t query) const;
bool PreCallValidateCmdCopyQueryPoolResults(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize stride,
VkQueryResultFlags flags) const;
bool PreCallValidateCmdPushConstants(
VkCommandBuffer commandBuffer,
VkPipelineLayout layout,
VkShaderStageFlags stageFlags,
uint32_t offset,
uint32_t size,
const void* pValues) const;
bool PreCallValidateCmdBeginRenderPass(
VkCommandBuffer commandBuffer,
const VkRenderPassBeginInfo* pRenderPassBegin,
VkSubpassContents contents) const;
bool PreCallValidateCmdNextSubpass(
VkCommandBuffer commandBuffer,
VkSubpassContents contents) const;
bool PreCallValidateCmdEndRenderPass(
VkCommandBuffer commandBuffer) const;
bool PreCallValidateCmdExecuteCommands(
VkCommandBuffer commandBuffer,
uint32_t commandBufferCount,
const VkCommandBuffer* pCommandBuffers) const;
bool PreCallValidateBindBufferMemory2(
VkDevice device,
uint32_t bindInfoCount,
const VkBindBufferMemoryInfo* pBindInfos) const;
bool PreCallValidateBindImageMemory2(
VkDevice device,
uint32_t bindInfoCount,
const VkBindImageMemoryInfo* pBindInfos) const;
bool PreCallValidateGetDeviceGroupPeerMemoryFeatures(
VkDevice device,
uint32_t heapIndex,
uint32_t localDeviceIndex,
uint32_t remoteDeviceIndex,
VkPeerMemoryFeatureFlags* pPeerMemoryFeatures) const;
bool PreCallValidateCmdSetDeviceMask(
VkCommandBuffer commandBuffer,
uint32_t deviceMask) const;
bool PreCallValidateCmdDispatchBase(
VkCommandBuffer commandBuffer,
uint32_t baseGroupX,
uint32_t baseGroupY,
uint32_t baseGroupZ,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ) const;
bool PreCallValidateEnumeratePhysicalDeviceGroups(
VkInstance instance,
uint32_t* pPhysicalDeviceGroupCount,
VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties) const;
bool PreCallValidateGetImageMemoryRequirements2(
VkDevice device,
const VkImageMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) const;
bool PreCallValidateGetBufferMemoryRequirements2(
VkDevice device,
const VkBufferMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) const;
bool PreCallValidateGetImageSparseMemoryRequirements2(
VkDevice device,
const VkImageSparseMemoryRequirementsInfo2* pInfo,
uint32_t* pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements2* pSparseMemoryRequirements) const;
bool PreCallValidateGetPhysicalDeviceFeatures2(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceFeatures2* pFeatures) const;
bool PreCallValidateGetPhysicalDeviceProperties2(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties2* pProperties) const;
bool PreCallValidateGetPhysicalDeviceFormatProperties2(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties2* pFormatProperties) const;
bool PreCallValidateGetPhysicalDeviceImageFormatProperties2(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo,
VkImageFormatProperties2* pImageFormatProperties) const;
bool PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
VkPhysicalDevice physicalDevice,
uint32_t* pQueueFamilyPropertyCount,
VkQueueFamilyProperties2* pQueueFamilyProperties) const;
bool PreCallValidateGetPhysicalDeviceMemoryProperties2(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties2* pMemoryProperties) const;
bool PreCallValidateGetPhysicalDeviceSparseImageFormatProperties2(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo,
uint32_t* pPropertyCount,
VkSparseImageFormatProperties2* pProperties) const;
bool PreCallValidateTrimCommandPool(
VkDevice device,
VkCommandPool commandPool,
VkCommandPoolTrimFlags flags) const;
bool PreCallValidateGetDeviceQueue2(
VkDevice device,
const VkDeviceQueueInfo2* pQueueInfo,
VkQueue* pQueue) const;
void PostCallRecordGetDeviceQueue2(
VkDevice device,
const VkDeviceQueueInfo2* pQueueInfo,
VkQueue* pQueue);
bool PreCallValidateCreateSamplerYcbcrConversion(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion) const;
void PostCallRecordCreateSamplerYcbcrConversion(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion,
VkResult result);
bool PreCallValidateDestroySamplerYcbcrConversion(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroySamplerYcbcrConversion(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreateDescriptorUpdateTemplate(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const;
void PostCallRecordCreateDescriptorUpdateTemplate(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate,
VkResult result);
bool PreCallValidateDestroyDescriptorUpdateTemplate(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDescriptorUpdateTemplate(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateUpdateDescriptorSetWithTemplate(
VkDevice device,
VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const void* pData) const;
bool PreCallValidateGetPhysicalDeviceExternalBufferProperties(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo,
VkExternalBufferProperties* pExternalBufferProperties) const;
bool PreCallValidateGetPhysicalDeviceExternalFenceProperties(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo,
VkExternalFenceProperties* pExternalFenceProperties) const;
bool PreCallValidateGetPhysicalDeviceExternalSemaphoreProperties(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo,
VkExternalSemaphoreProperties* pExternalSemaphoreProperties) const;
bool PreCallValidateGetDescriptorSetLayoutSupport(
VkDevice device,
const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
VkDescriptorSetLayoutSupport* pSupport) const;
bool PreCallValidateCmdDrawIndirectCount(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) const;
bool PreCallValidateCmdDrawIndexedIndirectCount(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) const;
bool PreCallValidateCreateRenderPass2(
VkDevice device,
const VkRenderPassCreateInfo2* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass) const;
void PostCallRecordCreateRenderPass2(
VkDevice device,
const VkRenderPassCreateInfo2* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass,
VkResult result);
bool PreCallValidateCmdBeginRenderPass2(
VkCommandBuffer commandBuffer,
const VkRenderPassBeginInfo* pRenderPassBegin,
const VkSubpassBeginInfo* pSubpassBeginInfo) const;
bool PreCallValidateCmdNextSubpass2(
VkCommandBuffer commandBuffer,
const VkSubpassBeginInfo* pSubpassBeginInfo,
const VkSubpassEndInfo* pSubpassEndInfo) const;
bool PreCallValidateCmdEndRenderPass2(
VkCommandBuffer commandBuffer,
const VkSubpassEndInfo* pSubpassEndInfo) const;
bool PreCallValidateResetQueryPool(
VkDevice device,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount) const;
bool PreCallValidateGetSemaphoreCounterValue(
VkDevice device,
VkSemaphore semaphore,
uint64_t* pValue) const;
bool PreCallValidateWaitSemaphores(
VkDevice device,
const VkSemaphoreWaitInfo* pWaitInfo,
uint64_t timeout) const;
bool PreCallValidateSignalSemaphore(
VkDevice device,
const VkSemaphoreSignalInfo* pSignalInfo) const;
bool PreCallValidateGetBufferDeviceAddress(
VkDevice device,
const VkBufferDeviceAddressInfo* pInfo) const;
bool PreCallValidateGetBufferOpaqueCaptureAddress(
VkDevice device,
const VkBufferDeviceAddressInfo* pInfo) const;
bool PreCallValidateGetDeviceMemoryOpaqueCaptureAddress(
VkDevice device,
const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo) const;
bool PreCallValidateDestroySurfaceKHR(
VkInstance instance,
VkSurfaceKHR surface,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroySurfaceKHR(
VkInstance instance,
VkSurfaceKHR surface,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetPhysicalDeviceSurfaceSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
VkSurfaceKHR surface,
VkBool32* pSupported) const;
bool PreCallValidateGetPhysicalDeviceSurfaceCapabilitiesKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
VkSurfaceCapabilitiesKHR* pSurfaceCapabilities) const;
bool PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
uint32_t* pSurfaceFormatCount,
VkSurfaceFormatKHR* pSurfaceFormats) const;
bool PreCallValidateGetPhysicalDeviceSurfacePresentModesKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
uint32_t* pPresentModeCount,
VkPresentModeKHR* pPresentModes) const;
bool PreCallValidateCreateSwapchainKHR(
VkDevice device,
const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchain) const;
void PostCallRecordCreateSwapchainKHR(
VkDevice device,
const VkSwapchainCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchain,
VkResult result);
bool PreCallValidateDestroySwapchainKHR(
VkDevice device,
VkSwapchainKHR swapchain,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroySwapchainKHR(
VkDevice device,
VkSwapchainKHR swapchain,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetSwapchainImagesKHR(
VkDevice device,
VkSwapchainKHR swapchain,
uint32_t* pSwapchainImageCount,
VkImage* pSwapchainImages) const;
void PostCallRecordGetSwapchainImagesKHR(
VkDevice device,
VkSwapchainKHR swapchain,
uint32_t* pSwapchainImageCount,
VkImage* pSwapchainImages,
VkResult result);
bool PreCallValidateAcquireNextImageKHR(
VkDevice device,
VkSwapchainKHR swapchain,
uint64_t timeout,
VkSemaphore semaphore,
VkFence fence,
uint32_t* pImageIndex) const;
bool PreCallValidateQueuePresentKHR(
VkQueue queue,
const VkPresentInfoKHR* pPresentInfo) const;
bool PreCallValidateGetDeviceGroupPresentCapabilitiesKHR(
VkDevice device,
VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) const;
bool PreCallValidateGetDeviceGroupSurfacePresentModesKHR(
VkDevice device,
VkSurfaceKHR surface,
VkDeviceGroupPresentModeFlagsKHR* pModes) const;
bool PreCallValidateGetPhysicalDevicePresentRectanglesKHR(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
uint32_t* pRectCount,
VkRect2D* pRects) const;
bool PreCallValidateAcquireNextImage2KHR(
VkDevice device,
const VkAcquireNextImageInfoKHR* pAcquireInfo,
uint32_t* pImageIndex) const;
bool PreCallValidateGetPhysicalDeviceDisplayPropertiesKHR(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkDisplayPropertiesKHR* pProperties) const;
bool PreCallValidateGetPhysicalDeviceDisplayPlanePropertiesKHR(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkDisplayPlanePropertiesKHR* pProperties) const;
bool PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(
VkPhysicalDevice physicalDevice,
uint32_t planeIndex,
uint32_t* pDisplayCount,
VkDisplayKHR* pDisplays) const;
void PostCallRecordGetDisplayPlaneSupportedDisplaysKHR(
VkPhysicalDevice physicalDevice,
uint32_t planeIndex,
uint32_t* pDisplayCount,
VkDisplayKHR* pDisplays,
VkResult result);
bool PreCallValidateGetDisplayModePropertiesKHR(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display,
uint32_t* pPropertyCount,
VkDisplayModePropertiesKHR* pProperties) const;
bool PreCallValidateCreateDisplayModeKHR(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display,
const VkDisplayModeCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDisplayModeKHR* pMode) const;
void PostCallRecordCreateDisplayModeKHR(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display,
const VkDisplayModeCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDisplayModeKHR* pMode,
VkResult result);
bool PreCallValidateGetDisplayPlaneCapabilitiesKHR(
VkPhysicalDevice physicalDevice,
VkDisplayModeKHR mode,
uint32_t planeIndex,
VkDisplayPlaneCapabilitiesKHR* pCapabilities) const;
bool PreCallValidateCreateDisplayPlaneSurfaceKHR(
VkInstance instance,
const VkDisplaySurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateDisplayPlaneSurfaceKHR(
VkInstance instance,
const VkDisplaySurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
bool PreCallValidateCreateSharedSwapchainsKHR(
VkDevice device,
uint32_t swapchainCount,
const VkSwapchainCreateInfoKHR* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchains) const;
void PostCallRecordCreateSharedSwapchainsKHR(
VkDevice device,
uint32_t swapchainCount,
const VkSwapchainCreateInfoKHR* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkSwapchainKHR* pSwapchains,
VkResult result);
#ifdef VK_USE_PLATFORM_XLIB_KHR
bool PreCallValidateCreateXlibSurfaceKHR(
VkInstance instance,
const VkXlibSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateXlibSurfaceKHR(
VkInstance instance,
const VkXlibSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_XLIB_KHR
#ifdef VK_USE_PLATFORM_XLIB_KHR
bool PreCallValidateGetPhysicalDeviceXlibPresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
Display* dpy,
VisualID visualID) const;
#endif // VK_USE_PLATFORM_XLIB_KHR
#ifdef VK_USE_PLATFORM_XCB_KHR
bool PreCallValidateCreateXcbSurfaceKHR(
VkInstance instance,
const VkXcbSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateXcbSurfaceKHR(
VkInstance instance,
const VkXcbSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_XCB_KHR
#ifdef VK_USE_PLATFORM_XCB_KHR
bool PreCallValidateGetPhysicalDeviceXcbPresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
xcb_connection_t* connection,
xcb_visualid_t visual_id) const;
#endif // VK_USE_PLATFORM_XCB_KHR
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
bool PreCallValidateCreateWaylandSurfaceKHR(
VkInstance instance,
const VkWaylandSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateWaylandSurfaceKHR(
VkInstance instance,
const VkWaylandSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_WAYLAND_KHR
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
bool PreCallValidateGetPhysicalDeviceWaylandPresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
struct wl_display* display) const;
#endif // VK_USE_PLATFORM_WAYLAND_KHR
#ifdef VK_USE_PLATFORM_ANDROID_KHR
bool PreCallValidateCreateAndroidSurfaceKHR(
VkInstance instance,
const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateAndroidSurfaceKHR(
VkInstance instance,
const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_ANDROID_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateCreateWin32SurfaceKHR(
VkInstance instance,
const VkWin32SurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateWin32SurfaceKHR(
VkInstance instance,
const VkWin32SurfaceCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetPhysicalDeviceWin32PresentationSupportKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetPhysicalDeviceFeatures2KHR(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceFeatures2* pFeatures) const;
bool PreCallValidateGetPhysicalDeviceProperties2KHR(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties2* pProperties) const;
bool PreCallValidateGetPhysicalDeviceFormatProperties2KHR(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkFormatProperties2* pFormatProperties) const;
bool PreCallValidateGetPhysicalDeviceImageFormatProperties2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo,
VkImageFormatProperties2* pImageFormatProperties) const;
bool PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
VkPhysicalDevice physicalDevice,
uint32_t* pQueueFamilyPropertyCount,
VkQueueFamilyProperties2* pQueueFamilyProperties) const;
bool PreCallValidateGetPhysicalDeviceMemoryProperties2KHR(
VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties2* pMemoryProperties) const;
bool PreCallValidateGetPhysicalDeviceSparseImageFormatProperties2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo,
uint32_t* pPropertyCount,
VkSparseImageFormatProperties2* pProperties) const;
bool PreCallValidateGetDeviceGroupPeerMemoryFeaturesKHR(
VkDevice device,
uint32_t heapIndex,
uint32_t localDeviceIndex,
uint32_t remoteDeviceIndex,
VkPeerMemoryFeatureFlags* pPeerMemoryFeatures) const;
bool PreCallValidateCmdSetDeviceMaskKHR(
VkCommandBuffer commandBuffer,
uint32_t deviceMask) const;
bool PreCallValidateCmdDispatchBaseKHR(
VkCommandBuffer commandBuffer,
uint32_t baseGroupX,
uint32_t baseGroupY,
uint32_t baseGroupZ,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ) const;
bool PreCallValidateTrimCommandPoolKHR(
VkDevice device,
VkCommandPool commandPool,
VkCommandPoolTrimFlags flags) const;
bool PreCallValidateEnumeratePhysicalDeviceGroupsKHR(
VkInstance instance,
uint32_t* pPhysicalDeviceGroupCount,
VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties) const;
bool PreCallValidateGetPhysicalDeviceExternalBufferPropertiesKHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo,
VkExternalBufferProperties* pExternalBufferProperties) const;
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetMemoryWin32HandleKHR(
VkDevice device,
const VkMemoryGetWin32HandleInfoKHR* pGetWin32HandleInfo,
HANDLE* pHandle) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetMemoryWin32HandlePropertiesKHR(
VkDevice device,
VkExternalMemoryHandleTypeFlagBits handleType,
HANDLE handle,
VkMemoryWin32HandlePropertiesKHR* pMemoryWin32HandleProperties) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetMemoryFdKHR(
VkDevice device,
const VkMemoryGetFdInfoKHR* pGetFdInfo,
int* pFd) const;
bool PreCallValidateGetMemoryFdPropertiesKHR(
VkDevice device,
VkExternalMemoryHandleTypeFlagBits handleType,
int fd,
VkMemoryFdPropertiesKHR* pMemoryFdProperties) const;
bool PreCallValidateGetPhysicalDeviceExternalSemaphorePropertiesKHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo,
VkExternalSemaphoreProperties* pExternalSemaphoreProperties) const;
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateImportSemaphoreWin32HandleKHR(
VkDevice device,
const VkImportSemaphoreWin32HandleInfoKHR* pImportSemaphoreWin32HandleInfo) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetSemaphoreWin32HandleKHR(
VkDevice device,
const VkSemaphoreGetWin32HandleInfoKHR* pGetWin32HandleInfo,
HANDLE* pHandle) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateImportSemaphoreFdKHR(
VkDevice device,
const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo) const;
bool PreCallValidateGetSemaphoreFdKHR(
VkDevice device,
const VkSemaphoreGetFdInfoKHR* pGetFdInfo,
int* pFd) const;
bool PreCallValidateCmdPushDescriptorSetKHR(
VkCommandBuffer commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout,
uint32_t set,
uint32_t descriptorWriteCount,
const VkWriteDescriptorSet* pDescriptorWrites) const;
bool PreCallValidateCmdPushDescriptorSetWithTemplateKHR(
VkCommandBuffer commandBuffer,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
VkPipelineLayout layout,
uint32_t set,
const void* pData) const;
bool PreCallValidateCreateDescriptorUpdateTemplateKHR(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const;
void PostCallRecordCreateDescriptorUpdateTemplateKHR(
VkDevice device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate,
VkResult result);
bool PreCallValidateDestroyDescriptorUpdateTemplateKHR(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDescriptorUpdateTemplateKHR(
VkDevice device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateUpdateDescriptorSetWithTemplateKHR(
VkDevice device,
VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const void* pData) const;
bool PreCallValidateCreateRenderPass2KHR(
VkDevice device,
const VkRenderPassCreateInfo2* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass) const;
void PostCallRecordCreateRenderPass2KHR(
VkDevice device,
const VkRenderPassCreateInfo2* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkRenderPass* pRenderPass,
VkResult result);
bool PreCallValidateCmdBeginRenderPass2KHR(
VkCommandBuffer commandBuffer,
const VkRenderPassBeginInfo* pRenderPassBegin,
const VkSubpassBeginInfo* pSubpassBeginInfo) const;
bool PreCallValidateCmdNextSubpass2KHR(
VkCommandBuffer commandBuffer,
const VkSubpassBeginInfo* pSubpassBeginInfo,
const VkSubpassEndInfo* pSubpassEndInfo) const;
bool PreCallValidateCmdEndRenderPass2KHR(
VkCommandBuffer commandBuffer,
const VkSubpassEndInfo* pSubpassEndInfo) const;
bool PreCallValidateGetSwapchainStatusKHR(
VkDevice device,
VkSwapchainKHR swapchain) const;
bool PreCallValidateGetPhysicalDeviceExternalFencePropertiesKHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo,
VkExternalFenceProperties* pExternalFenceProperties) const;
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateImportFenceWin32HandleKHR(
VkDevice device,
const VkImportFenceWin32HandleInfoKHR* pImportFenceWin32HandleInfo) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetFenceWin32HandleKHR(
VkDevice device,
const VkFenceGetWin32HandleInfoKHR* pGetWin32HandleInfo,
HANDLE* pHandle) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateImportFenceFdKHR(
VkDevice device,
const VkImportFenceFdInfoKHR* pImportFenceFdInfo) const;
bool PreCallValidateGetFenceFdKHR(
VkDevice device,
const VkFenceGetFdInfoKHR* pGetFdInfo,
int* pFd) const;
bool PreCallValidateEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(
VkPhysicalDevice physicalDevice,
uint32_t queueFamilyIndex,
uint32_t* pCounterCount,
VkPerformanceCounterKHR* pCounters,
VkPerformanceCounterDescriptionKHR* pCounterDescriptions) const;
bool PreCallValidateGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR(
VkPhysicalDevice physicalDevice,
const VkQueryPoolPerformanceCreateInfoKHR* pPerformanceQueryCreateInfo,
uint32_t* pNumPasses) const;
bool PreCallValidateAcquireProfilingLockKHR(
VkDevice device,
const VkAcquireProfilingLockInfoKHR* pInfo) const;
bool PreCallValidateReleaseProfilingLockKHR(
VkDevice device) const;
bool PreCallValidateGetPhysicalDeviceSurfaceCapabilities2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
VkSurfaceCapabilities2KHR* pSurfaceCapabilities) const;
bool PreCallValidateGetPhysicalDeviceSurfaceFormats2KHR(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
uint32_t* pSurfaceFormatCount,
VkSurfaceFormat2KHR* pSurfaceFormats) const;
bool PreCallValidateGetPhysicalDeviceDisplayProperties2KHR(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkDisplayProperties2KHR* pProperties) const;
bool PreCallValidateGetPhysicalDeviceDisplayPlaneProperties2KHR(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkDisplayPlaneProperties2KHR* pProperties) const;
bool PreCallValidateGetDisplayModeProperties2KHR(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display,
uint32_t* pPropertyCount,
VkDisplayModeProperties2KHR* pProperties) const;
bool PreCallValidateGetDisplayPlaneCapabilities2KHR(
VkPhysicalDevice physicalDevice,
const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
VkDisplayPlaneCapabilities2KHR* pCapabilities) const;
bool PreCallValidateGetImageMemoryRequirements2KHR(
VkDevice device,
const VkImageMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) const;
bool PreCallValidateGetBufferMemoryRequirements2KHR(
VkDevice device,
const VkBufferMemoryRequirementsInfo2* pInfo,
VkMemoryRequirements2* pMemoryRequirements) const;
bool PreCallValidateGetImageSparseMemoryRequirements2KHR(
VkDevice device,
const VkImageSparseMemoryRequirementsInfo2* pInfo,
uint32_t* pSparseMemoryRequirementCount,
VkSparseImageMemoryRequirements2* pSparseMemoryRequirements) const;
bool PreCallValidateCreateSamplerYcbcrConversionKHR(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion) const;
void PostCallRecordCreateSamplerYcbcrConversionKHR(
VkDevice device,
const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSamplerYcbcrConversion* pYcbcrConversion,
VkResult result);
bool PreCallValidateDestroySamplerYcbcrConversionKHR(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroySamplerYcbcrConversionKHR(
VkDevice device,
VkSamplerYcbcrConversion ycbcrConversion,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateBindBufferMemory2KHR(
VkDevice device,
uint32_t bindInfoCount,
const VkBindBufferMemoryInfo* pBindInfos) const;
bool PreCallValidateBindImageMemory2KHR(
VkDevice device,
uint32_t bindInfoCount,
const VkBindImageMemoryInfo* pBindInfos) const;
bool PreCallValidateGetDescriptorSetLayoutSupportKHR(
VkDevice device,
const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
VkDescriptorSetLayoutSupport* pSupport) const;
bool PreCallValidateCmdDrawIndirectCountKHR(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) const;
bool PreCallValidateCmdDrawIndexedIndirectCountKHR(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) const;
bool PreCallValidateGetSemaphoreCounterValueKHR(
VkDevice device,
VkSemaphore semaphore,
uint64_t* pValue) const;
bool PreCallValidateWaitSemaphoresKHR(
VkDevice device,
const VkSemaphoreWaitInfo* pWaitInfo,
uint64_t timeout) const;
bool PreCallValidateSignalSemaphoreKHR(
VkDevice device,
const VkSemaphoreSignalInfo* pSignalInfo) const;
bool PreCallValidateGetBufferDeviceAddressKHR(
VkDevice device,
const VkBufferDeviceAddressInfo* pInfo) const;
bool PreCallValidateGetBufferOpaqueCaptureAddressKHR(
VkDevice device,
const VkBufferDeviceAddressInfo* pInfo) const;
bool PreCallValidateGetDeviceMemoryOpaqueCaptureAddressKHR(
VkDevice device,
const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo) const;
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCreateDeferredOperationKHR(
VkDevice device,
const VkAllocationCallbacks* pAllocator,
VkDeferredOperationKHR* pDeferredOperation) const;
void PostCallRecordCreateDeferredOperationKHR(
VkDevice device,
const VkAllocationCallbacks* pAllocator,
VkDeferredOperationKHR* pDeferredOperation,
VkResult result);
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateDestroyDeferredOperationKHR(
VkDevice device,
VkDeferredOperationKHR operation,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDeferredOperationKHR(
VkDevice device,
VkDeferredOperationKHR operation,
const VkAllocationCallbacks* pAllocator);
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateGetDeferredOperationMaxConcurrencyKHR(
VkDevice device,
VkDeferredOperationKHR operation) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateGetDeferredOperationResultKHR(
VkDevice device,
VkDeferredOperationKHR operation) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateDeferredOperationJoinKHR(
VkDevice device,
VkDeferredOperationKHR operation) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateGetPipelineExecutablePropertiesKHR(
VkDevice device,
const VkPipelineInfoKHR* pPipelineInfo,
uint32_t* pExecutableCount,
VkPipelineExecutablePropertiesKHR* pProperties) const;
bool PreCallValidateGetPipelineExecutableStatisticsKHR(
VkDevice device,
const VkPipelineExecutableInfoKHR* pExecutableInfo,
uint32_t* pStatisticCount,
VkPipelineExecutableStatisticKHR* pStatistics) const;
bool PreCallValidateGetPipelineExecutableInternalRepresentationsKHR(
VkDevice device,
const VkPipelineExecutableInfoKHR* pExecutableInfo,
uint32_t* pInternalRepresentationCount,
VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations) const;
bool PreCallValidateCreateDebugReportCallbackEXT(
VkInstance instance,
const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugReportCallbackEXT* pCallback) const;
void PostCallRecordCreateDebugReportCallbackEXT(
VkInstance instance,
const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugReportCallbackEXT* pCallback,
VkResult result);
bool PreCallValidateDestroyDebugReportCallbackEXT(
VkInstance instance,
VkDebugReportCallbackEXT callback,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDebugReportCallbackEXT(
VkInstance instance,
VkDebugReportCallbackEXT callback,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateDebugReportMessageEXT(
VkInstance instance,
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t object,
size_t location,
int32_t messageCode,
const char* pLayerPrefix,
const char* pMessage) const;
bool PreCallValidateDebugMarkerSetObjectTagEXT(
VkDevice device,
const VkDebugMarkerObjectTagInfoEXT* pTagInfo) const;
bool PreCallValidateDebugMarkerSetObjectNameEXT(
VkDevice device,
const VkDebugMarkerObjectNameInfoEXT* pNameInfo) const;
bool PreCallValidateCmdDebugMarkerBeginEXT(
VkCommandBuffer commandBuffer,
const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) const;
bool PreCallValidateCmdDebugMarkerEndEXT(
VkCommandBuffer commandBuffer) const;
bool PreCallValidateCmdDebugMarkerInsertEXT(
VkCommandBuffer commandBuffer,
const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) const;
bool PreCallValidateCmdBindTransformFeedbackBuffersEXT(
VkCommandBuffer commandBuffer,
uint32_t firstBinding,
uint32_t bindingCount,
const VkBuffer* pBuffers,
const VkDeviceSize* pOffsets,
const VkDeviceSize* pSizes) const;
bool PreCallValidateCmdBeginTransformFeedbackEXT(
VkCommandBuffer commandBuffer,
uint32_t firstCounterBuffer,
uint32_t counterBufferCount,
const VkBuffer* pCounterBuffers,
const VkDeviceSize* pCounterBufferOffsets) const;
bool PreCallValidateCmdEndTransformFeedbackEXT(
VkCommandBuffer commandBuffer,
uint32_t firstCounterBuffer,
uint32_t counterBufferCount,
const VkBuffer* pCounterBuffers,
const VkDeviceSize* pCounterBufferOffsets) const;
bool PreCallValidateCmdBeginQueryIndexedEXT(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query,
VkQueryControlFlags flags,
uint32_t index) const;
bool PreCallValidateCmdEndQueryIndexedEXT(
VkCommandBuffer commandBuffer,
VkQueryPool queryPool,
uint32_t query,
uint32_t index) const;
bool PreCallValidateCmdDrawIndirectByteCountEXT(
VkCommandBuffer commandBuffer,
uint32_t instanceCount,
uint32_t firstInstance,
VkBuffer counterBuffer,
VkDeviceSize counterBufferOffset,
uint32_t counterOffset,
uint32_t vertexStride) const;
bool PreCallValidateGetImageViewHandleNVX(
VkDevice device,
const VkImageViewHandleInfoNVX* pInfo) const;
bool PreCallValidateGetImageViewAddressNVX(
VkDevice device,
VkImageView imageView,
VkImageViewAddressPropertiesNVX* pProperties) const;
bool PreCallValidateCmdDrawIndirectCountAMD(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) const;
bool PreCallValidateCmdDrawIndexedIndirectCountAMD(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) const;
bool PreCallValidateGetShaderInfoAMD(
VkDevice device,
VkPipeline pipeline,
VkShaderStageFlagBits shaderStage,
VkShaderInfoTypeAMD infoType,
size_t* pInfoSize,
void* pInfo) const;
#ifdef VK_USE_PLATFORM_GGP
bool PreCallValidateCreateStreamDescriptorSurfaceGGP(
VkInstance instance,
const VkStreamDescriptorSurfaceCreateInfoGGP* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateStreamDescriptorSurfaceGGP(
VkInstance instance,
const VkStreamDescriptorSurfaceCreateInfoGGP* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_GGP
bool PreCallValidateGetPhysicalDeviceExternalImageFormatPropertiesNV(
VkPhysicalDevice physicalDevice,
VkFormat format,
VkImageType type,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkExternalMemoryHandleTypeFlagsNV externalHandleType,
VkExternalImageFormatPropertiesNV* pExternalImageFormatProperties) const;
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetMemoryWin32HandleNV(
VkDevice device,
VkDeviceMemory memory,
VkExternalMemoryHandleTypeFlagsNV handleType,
HANDLE* pHandle) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_VI_NN
bool PreCallValidateCreateViSurfaceNN(
VkInstance instance,
const VkViSurfaceCreateInfoNN* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateViSurfaceNN(
VkInstance instance,
const VkViSurfaceCreateInfoNN* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_VI_NN
bool PreCallValidateCmdBeginConditionalRenderingEXT(
VkCommandBuffer commandBuffer,
const VkConditionalRenderingBeginInfoEXT* pConditionalRenderingBegin) const;
bool PreCallValidateCmdEndConditionalRenderingEXT(
VkCommandBuffer commandBuffer) const;
bool PreCallValidateCmdSetViewportWScalingNV(
VkCommandBuffer commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const VkViewportWScalingNV* pViewportWScalings) const;
bool PreCallValidateReleaseDisplayEXT(
VkPhysicalDevice physicalDevice,
VkDisplayKHR display) const;
#ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT
bool PreCallValidateAcquireXlibDisplayEXT(
VkPhysicalDevice physicalDevice,
Display* dpy,
VkDisplayKHR display) const;
#endif // VK_USE_PLATFORM_XLIB_XRANDR_EXT
#ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT
bool PreCallValidateGetRandROutputDisplayEXT(
VkPhysicalDevice physicalDevice,
Display* dpy,
RROutput rrOutput,
VkDisplayKHR* pDisplay) const;
void PostCallRecordGetRandROutputDisplayEXT(
VkPhysicalDevice physicalDevice,
Display* dpy,
RROutput rrOutput,
VkDisplayKHR* pDisplay,
VkResult result);
#endif // VK_USE_PLATFORM_XLIB_XRANDR_EXT
bool PreCallValidateGetPhysicalDeviceSurfaceCapabilities2EXT(
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
VkSurfaceCapabilities2EXT* pSurfaceCapabilities) const;
bool PreCallValidateDisplayPowerControlEXT(
VkDevice device,
VkDisplayKHR display,
const VkDisplayPowerInfoEXT* pDisplayPowerInfo) const;
bool PreCallValidateRegisterDeviceEventEXT(
VkDevice device,
const VkDeviceEventInfoEXT* pDeviceEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence) const;
void PostCallRecordRegisterDeviceEventEXT(
VkDevice device,
const VkDeviceEventInfoEXT* pDeviceEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence,
VkResult result);
bool PreCallValidateRegisterDisplayEventEXT(
VkDevice device,
VkDisplayKHR display,
const VkDisplayEventInfoEXT* pDisplayEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence) const;
void PostCallRecordRegisterDisplayEventEXT(
VkDevice device,
VkDisplayKHR display,
const VkDisplayEventInfoEXT* pDisplayEventInfo,
const VkAllocationCallbacks* pAllocator,
VkFence* pFence,
VkResult result);
bool PreCallValidateGetSwapchainCounterEXT(
VkDevice device,
VkSwapchainKHR swapchain,
VkSurfaceCounterFlagBitsEXT counter,
uint64_t* pCounterValue) const;
bool PreCallValidateGetRefreshCycleDurationGOOGLE(
VkDevice device,
VkSwapchainKHR swapchain,
VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) const;
bool PreCallValidateGetPastPresentationTimingGOOGLE(
VkDevice device,
VkSwapchainKHR swapchain,
uint32_t* pPresentationTimingCount,
VkPastPresentationTimingGOOGLE* pPresentationTimings) const;
bool PreCallValidateCmdSetDiscardRectangleEXT(
VkCommandBuffer commandBuffer,
uint32_t firstDiscardRectangle,
uint32_t discardRectangleCount,
const VkRect2D* pDiscardRectangles) const;
bool PreCallValidateSetHdrMetadataEXT(
VkDevice device,
uint32_t swapchainCount,
const VkSwapchainKHR* pSwapchains,
const VkHdrMetadataEXT* pMetadata) const;
#ifdef VK_USE_PLATFORM_IOS_MVK
bool PreCallValidateCreateIOSSurfaceMVK(
VkInstance instance,
const VkIOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateIOSSurfaceMVK(
VkInstance instance,
const VkIOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_IOS_MVK
#ifdef VK_USE_PLATFORM_MACOS_MVK
bool PreCallValidateCreateMacOSSurfaceMVK(
VkInstance instance,
const VkMacOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateMacOSSurfaceMVK(
VkInstance instance,
const VkMacOSSurfaceCreateInfoMVK* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_MACOS_MVK
bool PreCallValidateSetDebugUtilsObjectNameEXT(
VkDevice device,
const VkDebugUtilsObjectNameInfoEXT* pNameInfo) const;
bool PreCallValidateSetDebugUtilsObjectTagEXT(
VkDevice device,
const VkDebugUtilsObjectTagInfoEXT* pTagInfo) const;
bool PreCallValidateQueueBeginDebugUtilsLabelEXT(
VkQueue queue,
const VkDebugUtilsLabelEXT* pLabelInfo) const;
bool PreCallValidateQueueEndDebugUtilsLabelEXT(
VkQueue queue) const;
bool PreCallValidateQueueInsertDebugUtilsLabelEXT(
VkQueue queue,
const VkDebugUtilsLabelEXT* pLabelInfo) const;
bool PreCallValidateCmdBeginDebugUtilsLabelEXT(
VkCommandBuffer commandBuffer,
const VkDebugUtilsLabelEXT* pLabelInfo) const;
bool PreCallValidateCmdEndDebugUtilsLabelEXT(
VkCommandBuffer commandBuffer) const;
bool PreCallValidateCmdInsertDebugUtilsLabelEXT(
VkCommandBuffer commandBuffer,
const VkDebugUtilsLabelEXT* pLabelInfo) const;
bool PreCallValidateCreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugUtilsMessengerEXT* pMessenger) const;
void PostCallRecordCreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugUtilsMessengerEXT* pMessenger,
VkResult result);
bool PreCallValidateDestroyDebugUtilsMessengerEXT(
VkInstance instance,
VkDebugUtilsMessengerEXT messenger,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyDebugUtilsMessengerEXT(
VkInstance instance,
VkDebugUtilsMessengerEXT messenger,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateSubmitDebugUtilsMessageEXT(
VkInstance instance,
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData) const;
#ifdef VK_USE_PLATFORM_ANDROID_KHR
bool PreCallValidateGetAndroidHardwareBufferPropertiesANDROID(
VkDevice device,
const struct AHardwareBuffer* buffer,
VkAndroidHardwareBufferPropertiesANDROID* pProperties) const;
#endif // VK_USE_PLATFORM_ANDROID_KHR
#ifdef VK_USE_PLATFORM_ANDROID_KHR
bool PreCallValidateGetMemoryAndroidHardwareBufferANDROID(
VkDevice device,
const VkMemoryGetAndroidHardwareBufferInfoANDROID* pInfo,
struct AHardwareBuffer** pBuffer) const;
#endif // VK_USE_PLATFORM_ANDROID_KHR
bool PreCallValidateCmdSetSampleLocationsEXT(
VkCommandBuffer commandBuffer,
const VkSampleLocationsInfoEXT* pSampleLocationsInfo) const;
bool PreCallValidateGetPhysicalDeviceMultisamplePropertiesEXT(
VkPhysicalDevice physicalDevice,
VkSampleCountFlagBits samples,
VkMultisamplePropertiesEXT* pMultisampleProperties) const;
bool PreCallValidateGetImageDrmFormatModifierPropertiesEXT(
VkDevice device,
VkImage image,
VkImageDrmFormatModifierPropertiesEXT* pProperties) const;
bool PreCallValidateCreateValidationCacheEXT(
VkDevice device,
const VkValidationCacheCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkValidationCacheEXT* pValidationCache) const;
void PostCallRecordCreateValidationCacheEXT(
VkDevice device,
const VkValidationCacheCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkValidationCacheEXT* pValidationCache,
VkResult result);
bool PreCallValidateDestroyValidationCacheEXT(
VkDevice device,
VkValidationCacheEXT validationCache,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyValidationCacheEXT(
VkDevice device,
VkValidationCacheEXT validationCache,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateMergeValidationCachesEXT(
VkDevice device,
VkValidationCacheEXT dstCache,
uint32_t srcCacheCount,
const VkValidationCacheEXT* pSrcCaches) const;
bool PreCallValidateGetValidationCacheDataEXT(
VkDevice device,
VkValidationCacheEXT validationCache,
size_t* pDataSize,
void* pData) const;
bool PreCallValidateCmdBindShadingRateImageNV(
VkCommandBuffer commandBuffer,
VkImageView imageView,
VkImageLayout imageLayout) const;
bool PreCallValidateCmdSetViewportShadingRatePaletteNV(
VkCommandBuffer commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const VkShadingRatePaletteNV* pShadingRatePalettes) const;
bool PreCallValidateCmdSetCoarseSampleOrderNV(
VkCommandBuffer commandBuffer,
VkCoarseSampleOrderTypeNV sampleOrderType,
uint32_t customSampleOrderCount,
const VkCoarseSampleOrderCustomNV* pCustomSampleOrders) const;
bool PreCallValidateCreateAccelerationStructureNV(
VkDevice device,
const VkAccelerationStructureCreateInfoNV* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkAccelerationStructureNV* pAccelerationStructure) const;
void PostCallRecordCreateAccelerationStructureNV(
VkDevice device,
const VkAccelerationStructureCreateInfoNV* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkAccelerationStructureNV* pAccelerationStructure,
VkResult result);
bool PreCallValidateDestroyAccelerationStructureKHR(
VkDevice device,
VkAccelerationStructureKHR accelerationStructure,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyAccelerationStructureKHR(
VkDevice device,
VkAccelerationStructureKHR accelerationStructure,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateDestroyAccelerationStructureNV(
VkDevice device,
VkAccelerationStructureKHR accelerationStructure,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyAccelerationStructureNV(
VkDevice device,
VkAccelerationStructureKHR accelerationStructure,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateGetAccelerationStructureMemoryRequirementsNV(
VkDevice device,
const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo,
VkMemoryRequirements2KHR* pMemoryRequirements) const;
bool PreCallValidateBindAccelerationStructureMemoryKHR(
VkDevice device,
uint32_t bindInfoCount,
const VkBindAccelerationStructureMemoryInfoKHR* pBindInfos) const;
bool PreCallValidateBindAccelerationStructureMemoryNV(
VkDevice device,
uint32_t bindInfoCount,
const VkBindAccelerationStructureMemoryInfoKHR* pBindInfos) const;
bool PreCallValidateCmdBuildAccelerationStructureNV(
VkCommandBuffer commandBuffer,
const VkAccelerationStructureInfoNV* pInfo,
VkBuffer instanceData,
VkDeviceSize instanceOffset,
VkBool32 update,
VkAccelerationStructureKHR dst,
VkAccelerationStructureKHR src,
VkBuffer scratch,
VkDeviceSize scratchOffset) const;
bool PreCallValidateCmdCopyAccelerationStructureNV(
VkCommandBuffer commandBuffer,
VkAccelerationStructureKHR dst,
VkAccelerationStructureKHR src,
VkCopyAccelerationStructureModeKHR mode) const;
bool PreCallValidateCmdTraceRaysNV(
VkCommandBuffer commandBuffer,
VkBuffer raygenShaderBindingTableBuffer,
VkDeviceSize raygenShaderBindingOffset,
VkBuffer missShaderBindingTableBuffer,
VkDeviceSize missShaderBindingOffset,
VkDeviceSize missShaderBindingStride,
VkBuffer hitShaderBindingTableBuffer,
VkDeviceSize hitShaderBindingOffset,
VkDeviceSize hitShaderBindingStride,
VkBuffer callableShaderBindingTableBuffer,
VkDeviceSize callableShaderBindingOffset,
VkDeviceSize callableShaderBindingStride,
uint32_t width,
uint32_t height,
uint32_t depth) const;
bool PreCallValidateCreateRayTracingPipelinesNV(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoNV* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) const;
void PostCallRecordCreateRayTracingPipelinesNV(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoNV* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines,
VkResult result);
bool PreCallValidateGetRayTracingShaderGroupHandlesKHR(
VkDevice device,
VkPipeline pipeline,
uint32_t firstGroup,
uint32_t groupCount,
size_t dataSize,
void* pData) const;
bool PreCallValidateGetRayTracingShaderGroupHandlesNV(
VkDevice device,
VkPipeline pipeline,
uint32_t firstGroup,
uint32_t groupCount,
size_t dataSize,
void* pData) const;
bool PreCallValidateGetAccelerationStructureHandleNV(
VkDevice device,
VkAccelerationStructureKHR accelerationStructure,
size_t dataSize,
void* pData) const;
bool PreCallValidateCmdWriteAccelerationStructuresPropertiesKHR(
VkCommandBuffer commandBuffer,
uint32_t accelerationStructureCount,
const VkAccelerationStructureKHR* pAccelerationStructures,
VkQueryType queryType,
VkQueryPool queryPool,
uint32_t firstQuery) const;
bool PreCallValidateCmdWriteAccelerationStructuresPropertiesNV(
VkCommandBuffer commandBuffer,
uint32_t accelerationStructureCount,
const VkAccelerationStructureKHR* pAccelerationStructures,
VkQueryType queryType,
VkQueryPool queryPool,
uint32_t firstQuery) const;
bool PreCallValidateCompileDeferredNV(
VkDevice device,
VkPipeline pipeline,
uint32_t shader) const;
bool PreCallValidateGetMemoryHostPointerPropertiesEXT(
VkDevice device,
VkExternalMemoryHandleTypeFlagBits handleType,
const void* pHostPointer,
VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties) const;
bool PreCallValidateCmdWriteBufferMarkerAMD(
VkCommandBuffer commandBuffer,
VkPipelineStageFlagBits pipelineStage,
VkBuffer dstBuffer,
VkDeviceSize dstOffset,
uint32_t marker) const;
bool PreCallValidateGetPhysicalDeviceCalibrateableTimeDomainsEXT(
VkPhysicalDevice physicalDevice,
uint32_t* pTimeDomainCount,
VkTimeDomainEXT* pTimeDomains) const;
bool PreCallValidateGetCalibratedTimestampsEXT(
VkDevice device,
uint32_t timestampCount,
const VkCalibratedTimestampInfoEXT* pTimestampInfos,
uint64_t* pTimestamps,
uint64_t* pMaxDeviation) const;
bool PreCallValidateCmdDrawMeshTasksNV(
VkCommandBuffer commandBuffer,
uint32_t taskCount,
uint32_t firstTask) const;
bool PreCallValidateCmdDrawMeshTasksIndirectNV(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride) const;
bool PreCallValidateCmdDrawMeshTasksIndirectCountNV(
VkCommandBuffer commandBuffer,
VkBuffer buffer,
VkDeviceSize offset,
VkBuffer countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride) const;
bool PreCallValidateCmdSetExclusiveScissorNV(
VkCommandBuffer commandBuffer,
uint32_t firstExclusiveScissor,
uint32_t exclusiveScissorCount,
const VkRect2D* pExclusiveScissors) const;
bool PreCallValidateCmdSetCheckpointNV(
VkCommandBuffer commandBuffer,
const void* pCheckpointMarker) const;
bool PreCallValidateGetQueueCheckpointDataNV(
VkQueue queue,
uint32_t* pCheckpointDataCount,
VkCheckpointDataNV* pCheckpointData) const;
bool PreCallValidateInitializePerformanceApiINTEL(
VkDevice device,
const VkInitializePerformanceApiInfoINTEL* pInitializeInfo) const;
bool PreCallValidateUninitializePerformanceApiINTEL(
VkDevice device) const;
bool PreCallValidateCmdSetPerformanceMarkerINTEL(
VkCommandBuffer commandBuffer,
const VkPerformanceMarkerInfoINTEL* pMarkerInfo) const;
bool PreCallValidateCmdSetPerformanceStreamMarkerINTEL(
VkCommandBuffer commandBuffer,
const VkPerformanceStreamMarkerInfoINTEL* pMarkerInfo) const;
bool PreCallValidateCmdSetPerformanceOverrideINTEL(
VkCommandBuffer commandBuffer,
const VkPerformanceOverrideInfoINTEL* pOverrideInfo) const;
bool PreCallValidateAcquirePerformanceConfigurationINTEL(
VkDevice device,
const VkPerformanceConfigurationAcquireInfoINTEL* pAcquireInfo,
VkPerformanceConfigurationINTEL* pConfiguration) const;
bool PreCallValidateReleasePerformanceConfigurationINTEL(
VkDevice device,
VkPerformanceConfigurationINTEL configuration) const;
bool PreCallValidateQueueSetPerformanceConfigurationINTEL(
VkQueue queue,
VkPerformanceConfigurationINTEL configuration) const;
bool PreCallValidateGetPerformanceParameterINTEL(
VkDevice device,
VkPerformanceParameterTypeINTEL parameter,
VkPerformanceValueINTEL* pValue) const;
bool PreCallValidateSetLocalDimmingAMD(
VkDevice device,
VkSwapchainKHR swapChain,
VkBool32 localDimmingEnable) const;
#ifdef VK_USE_PLATFORM_FUCHSIA
bool PreCallValidateCreateImagePipeSurfaceFUCHSIA(
VkInstance instance,
const VkImagePipeSurfaceCreateInfoFUCHSIA* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateImagePipeSurfaceFUCHSIA(
VkInstance instance,
const VkImagePipeSurfaceCreateInfoFUCHSIA* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_FUCHSIA
#ifdef VK_USE_PLATFORM_METAL_EXT
bool PreCallValidateCreateMetalSurfaceEXT(
VkInstance instance,
const VkMetalSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateMetalSurfaceEXT(
VkInstance instance,
const VkMetalSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
#endif // VK_USE_PLATFORM_METAL_EXT
bool PreCallValidateGetBufferDeviceAddressEXT(
VkDevice device,
const VkBufferDeviceAddressInfo* pInfo) const;
bool PreCallValidateGetPhysicalDeviceToolPropertiesEXT(
VkPhysicalDevice physicalDevice,
uint32_t* pToolCount,
VkPhysicalDeviceToolPropertiesEXT* pToolProperties) const;
bool PreCallValidateGetPhysicalDeviceCooperativeMatrixPropertiesNV(
VkPhysicalDevice physicalDevice,
uint32_t* pPropertyCount,
VkCooperativeMatrixPropertiesNV* pProperties) const;
bool PreCallValidateGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV(
VkPhysicalDevice physicalDevice,
uint32_t* pCombinationCount,
VkFramebufferMixedSamplesCombinationNV* pCombinations) const;
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetPhysicalDeviceSurfacePresentModes2EXT(
VkPhysicalDevice physicalDevice,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
uint32_t* pPresentModeCount,
VkPresentModeKHR* pPresentModes) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateAcquireFullScreenExclusiveModeEXT(
VkDevice device,
VkSwapchainKHR swapchain) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateReleaseFullScreenExclusiveModeEXT(
VkDevice device,
VkSwapchainKHR swapchain) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
#ifdef VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateGetDeviceGroupSurfacePresentModes2EXT(
VkDevice device,
const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
VkDeviceGroupPresentModeFlagsKHR* pModes) const;
#endif // VK_USE_PLATFORM_WIN32_KHR
bool PreCallValidateCreateHeadlessSurfaceEXT(
VkInstance instance,
const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface) const;
void PostCallRecordCreateHeadlessSurfaceEXT(
VkInstance instance,
const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkSurfaceKHR* pSurface,
VkResult result);
bool PreCallValidateCmdSetLineStippleEXT(
VkCommandBuffer commandBuffer,
uint32_t lineStippleFactor,
uint16_t lineStipplePattern) const;
bool PreCallValidateResetQueryPoolEXT(
VkDevice device,
VkQueryPool queryPool,
uint32_t firstQuery,
uint32_t queryCount) const;
bool PreCallValidateGetGeneratedCommandsMemoryRequirementsNV(
VkDevice device,
const VkGeneratedCommandsMemoryRequirementsInfoNV* pInfo,
VkMemoryRequirements2* pMemoryRequirements) const;
bool PreCallValidateCmdPreprocessGeneratedCommandsNV(
VkCommandBuffer commandBuffer,
const VkGeneratedCommandsInfoNV* pGeneratedCommandsInfo) const;
bool PreCallValidateCmdExecuteGeneratedCommandsNV(
VkCommandBuffer commandBuffer,
VkBool32 isPreprocessed,
const VkGeneratedCommandsInfoNV* pGeneratedCommandsInfo) const;
bool PreCallValidateCmdBindPipelineShaderGroupNV(
VkCommandBuffer commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
VkPipeline pipeline,
uint32_t groupIndex) const;
bool PreCallValidateCreateIndirectCommandsLayoutNV(
VkDevice device,
const VkIndirectCommandsLayoutCreateInfoNV* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkIndirectCommandsLayoutNV* pIndirectCommandsLayout) const;
void PostCallRecordCreateIndirectCommandsLayoutNV(
VkDevice device,
const VkIndirectCommandsLayoutCreateInfoNV* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkIndirectCommandsLayoutNV* pIndirectCommandsLayout,
VkResult result);
bool PreCallValidateDestroyIndirectCommandsLayoutNV(
VkDevice device,
VkIndirectCommandsLayoutNV indirectCommandsLayout,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyIndirectCommandsLayoutNV(
VkDevice device,
VkIndirectCommandsLayoutNV indirectCommandsLayout,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateCreatePrivateDataSlotEXT(
VkDevice device,
const VkPrivateDataSlotCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPrivateDataSlotEXT* pPrivateDataSlot) const;
void PostCallRecordCreatePrivateDataSlotEXT(
VkDevice device,
const VkPrivateDataSlotCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPrivateDataSlotEXT* pPrivateDataSlot,
VkResult result);
bool PreCallValidateDestroyPrivateDataSlotEXT(
VkDevice device,
VkPrivateDataSlotEXT privateDataSlot,
const VkAllocationCallbacks* pAllocator) const;
void PreCallRecordDestroyPrivateDataSlotEXT(
VkDevice device,
VkPrivateDataSlotEXT privateDataSlot,
const VkAllocationCallbacks* pAllocator);
bool PreCallValidateSetPrivateDataEXT(
VkDevice device,
VkObjectType objectType,
uint64_t objectHandle,
VkPrivateDataSlotEXT privateDataSlot,
uint64_t data) const;
bool PreCallValidateGetPrivateDataEXT(
VkDevice device,
VkObjectType objectType,
uint64_t objectHandle,
VkPrivateDataSlotEXT privateDataSlot,
uint64_t* pData) const;
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCreateAccelerationStructureKHR(
VkDevice device,
const VkAccelerationStructureCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkAccelerationStructureKHR* pAccelerationStructure) const;
void PostCallRecordCreateAccelerationStructureKHR(
VkDevice device,
const VkAccelerationStructureCreateInfoKHR* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkAccelerationStructureKHR* pAccelerationStructure,
VkResult result);
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateGetAccelerationStructureMemoryRequirementsKHR(
VkDevice device,
const VkAccelerationStructureMemoryRequirementsInfoKHR* pInfo,
VkMemoryRequirements2* pMemoryRequirements) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCmdBuildAccelerationStructureKHR(
VkCommandBuffer commandBuffer,
uint32_t infoCount,
const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
const VkAccelerationStructureBuildOffsetInfoKHR* const* ppOffsetInfos) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCmdBuildAccelerationStructureIndirectKHR(
VkCommandBuffer commandBuffer,
const VkAccelerationStructureBuildGeometryInfoKHR* pInfo,
VkBuffer indirectBuffer,
VkDeviceSize indirectOffset,
uint32_t indirectStride) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateBuildAccelerationStructureKHR(
VkDevice device,
uint32_t infoCount,
const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
const VkAccelerationStructureBuildOffsetInfoKHR* const* ppOffsetInfos) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCopyAccelerationStructureKHR(
VkDevice device,
const VkCopyAccelerationStructureInfoKHR* pInfo) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCopyAccelerationStructureToMemoryKHR(
VkDevice device,
const VkCopyAccelerationStructureToMemoryInfoKHR* pInfo) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCopyMemoryToAccelerationStructureKHR(
VkDevice device,
const VkCopyMemoryToAccelerationStructureInfoKHR* pInfo) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateWriteAccelerationStructuresPropertiesKHR(
VkDevice device,
uint32_t accelerationStructureCount,
const VkAccelerationStructureKHR* pAccelerationStructures,
VkQueryType queryType,
size_t dataSize,
void* pData,
size_t stride) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCmdCopyAccelerationStructureKHR(
VkCommandBuffer commandBuffer,
const VkCopyAccelerationStructureInfoKHR* pInfo) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCmdCopyAccelerationStructureToMemoryKHR(
VkCommandBuffer commandBuffer,
const VkCopyAccelerationStructureToMemoryInfoKHR* pInfo) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCmdCopyMemoryToAccelerationStructureKHR(
VkCommandBuffer commandBuffer,
const VkCopyMemoryToAccelerationStructureInfoKHR* pInfo) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCmdTraceRaysKHR(
VkCommandBuffer commandBuffer,
const VkStridedBufferRegionKHR* pRaygenShaderBindingTable,
const VkStridedBufferRegionKHR* pMissShaderBindingTable,
const VkStridedBufferRegionKHR* pHitShaderBindingTable,
const VkStridedBufferRegionKHR* pCallableShaderBindingTable,
uint32_t width,
uint32_t height,
uint32_t depth) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCreateRayTracingPipelinesKHR(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoKHR* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines) const;
void PostCallRecordCreateRayTracingPipelinesKHR(
VkDevice device,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoKHR* pCreateInfos,
const VkAllocationCallbacks* pAllocator,
VkPipeline* pPipelines,
VkResult result);
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateGetAccelerationStructureDeviceAddressKHR(
VkDevice device,
const VkAccelerationStructureDeviceAddressInfoKHR* pInfo) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateGetRayTracingCaptureReplayShaderGroupHandlesKHR(
VkDevice device,
VkPipeline pipeline,
uint32_t firstGroup,
uint32_t groupCount,
size_t dataSize,
void* pData) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateCmdTraceRaysIndirectKHR(
VkCommandBuffer commandBuffer,
const VkStridedBufferRegionKHR* pRaygenShaderBindingTable,
const VkStridedBufferRegionKHR* pMissShaderBindingTable,
const VkStridedBufferRegionKHR* pHitShaderBindingTable,
const VkStridedBufferRegionKHR* pCallableShaderBindingTable,
VkBuffer buffer,
VkDeviceSize offset) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
#ifdef VK_ENABLE_BETA_EXTENSIONS
bool PreCallValidateGetDeviceAccelerationStructureCompatibilityKHR(
VkDevice device,
const VkAccelerationStructureVersionKHR* version) const;
#endif // VK_ENABLE_BETA_EXTENSIONS
void PostCallRecordDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator);
void PreCallRecordResetDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags);
void PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties *pQueueFamilyProperties);
void PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers);
void PreCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount, const VkDescriptorSet *pDescriptorSets);
void PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR *pQueueFamilyProperties);
void PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR *pQueueFamilyProperties);
void PostCallRecordGetPhysicalDeviceDisplayPropertiesKHR(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, VkDisplayPropertiesKHR *pProperties, VkResult result);
void PostCallRecordGetDisplayModePropertiesKHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t *pPropertyCount, VkDisplayModePropertiesKHR *pProperties, VkResult result);
void PostCallRecordGetPhysicalDeviceDisplayProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, VkDisplayProperties2KHR *pProperties, VkResult result);
void PostCallRecordGetDisplayModeProperties2KHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t *pPropertyCount, VkDisplayModeProperties2KHR *pProperties, VkResult result);
|
{
"content_hash": "1113d4fd16c848332ff43dfd68c60b0c",
"timestamp": "",
"source": "github",
"line_count": 2628,
"max_line_length": 188,
"avg_line_length": 56.93455098934551,
"alnum_prop": 0.5355557931882585,
"repo_name": "endlessm/chromium-browser",
"id": "78834b4e19a0cd4c9d32f56a0f455707021e51c0",
"size": "150609",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third_party/angle/third_party/vulkan-validation-layers/src/layers/generated/object_tracker.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
package com.github.mdr.mash.subprocesses
import java.io.{ IOException, PrintStream }
import java.lang.ProcessBuilder.Redirect
import java.nio.charset.StandardCharsets
import java.nio.file.Path
import java.time.Instant
import com.github.mdr.mash.Singletons
import com.github.mdr.mash.evaluator.{ EvaluatorException, ToStringifier }
import com.github.mdr.mash.runtime.MashValue
import com.github.mdr.mash.terminal.ansi.EscapeSequence
import org.apache.commons.io.IOUtils
object ProcessRunner {
private val terminalControl = Singletons.terminalControl
private val output: PrintStream = System.out
def runProcess(args: Seq[MashValue],
captureProcess: Boolean = false,
stdinRedirectOpt: Option[Path] = None,
stdinImmediateOpt: Option[String] = None,
stdoutRedirectOpt: Option[Path] = None): ProcessResult = {
val stringArgs = args.map(ToStringifier.stringify)
val outputRedirect = getOutputRedirect(captureProcess, stdoutRedirectOpt)
val inputRedirect = getInputRedirect(stdinRedirectOpt, stdinImmediateOpt)
terminalControl.externalProcess {
val builder = new ProcessBuilder(stringArgs: _*)
.redirectInput(inputRedirect)
.redirectOutput(outputRedirect)
.redirectError(ProcessBuilder.Redirect.INHERIT)
setEnvironment(builder.environment())
val start = Instant.now
val process =
try
builder.start()
catch {
case e: IOException ⇒ throw EvaluatorException(e.getMessage)
}
for (stdinImmediate ← stdinImmediateOpt)
writeStdinImmediate(process, stdinImmediate)
val stdout = if (captureProcess) IOUtils.toString(process.getInputStream, StandardCharsets.UTF_8) else ""
val statusCode = process.waitFor()
val stop = Instant.now
clearPartialOutput()
ProcessResult(statusCode, stdout, start, stop)
}
}
// Clear out any partial output
def clearPartialOutput() {
output.write(("\r" + EscapeSequence.EraseLineFromCursor).getBytes)
output.flush()
}
def writeStdinImmediate(process: Process, stdinImmediate: String): Unit = {
IOUtils.write(stdinImmediate, process.getOutputStream, StandardCharsets.UTF_8)
process.getOutputStream.close()
}
def getOutputRedirect(captureProcess: Boolean, stdoutRedirectOpt: Option[Path]): Redirect = {
stdoutRedirectOpt match {
case Some(path) ⇒ ProcessBuilder.Redirect.to(path.toFile)
case _ if captureProcess ⇒ ProcessBuilder.Redirect.PIPE
case _ ⇒ ProcessBuilder.Redirect.INHERIT
}
}
def getInputRedirect(stdinRedirectOpt: Option[Path], stdinImmediateOpt: Option[String]): Redirect = {
stdinRedirectOpt match {
case Some(path) ⇒ ProcessBuilder.Redirect.from(path.toFile)
case _ ⇒
stdinImmediateOpt match {
case Some(_) ⇒ ProcessBuilder.Redirect.PIPE
case _ ⇒ ProcessBuilder.Redirect.INHERIT
}
}
}
private def setEnvironment(env: java.util.Map[String, String]) = {
env.clear()
for ((k, v) ← Singletons.environment.immutableFields)
env.put(ToStringifier.stringify(k), ToStringifier.stringify(v))
}
}
case class ProcessResult(exitStatus: Int, stdout: String, start: Instant, stop: Instant)
|
{
"content_hash": "1182930bc9ed640b338e96f3641ecbd7",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 111,
"avg_line_length": 35.72043010752688,
"alnum_prop": 0.7034918723660446,
"repo_name": "mdr/mash",
"id": "8b418452736792f4c691e48acdda78a12f0dbad2",
"size": "3342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/github/mdr/mash/subprocesses/ProcessRunner.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "1632923"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
{
"content_hash": "1ab2d37044550cc0b1babdb04b5ecb26",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "68c0e37a0ce432edaa5938cb897535154054a9ec",
"size": "161",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Araliaceae/Ginsen/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
<?php defined('BASEPATH') OR exit('No direct script access allowed');
// Files
// Titles
$lang['files.files_title'] = 'Files';
$lang['files.upload_title'] = 'Upload Files';
$lang['files.edit_title'] = 'Edit file "%s"';
$lang['files.check-all'] = 'All ';
// Labels
$lang['files.download_label'] = 'Download ';
$lang['files.upload_label'] = 'Upload';
$lang['files.description_label'] = 'Description';
$lang['files.type_label'] = 'Type';
$lang['files.file_label'] = 'File';
$lang['files.filename_label'] = 'File Name';
$lang['files.filter_label'] = 'Filter';
$lang['files.loading_label'] = 'Loading...';
$lang['files.name_label'] = 'Name';
$lang['files.folder_label'] = 'Folder';
$lang['files.dropdown_select'] = '-- Select Folder For Upload --';
$lang['files.dropdown_no_subfolders'] = '-- None --';
$lang['files.dropdown_select_all'] = '-- All --';
$lang['files.dropdown_root'] = '-- Root --';
$lang['files.type_a'] = 'Audio';
$lang['files.type_v'] = 'Video';
$lang['files.type_d'] = 'Document';
$lang['files.type_i'] = 'Image';
$lang['files.type_o'] = 'Other';
$lang['files.display_grid'] = 'Grid';
$lang['files.display_list'] = 'List';
// Messages
$lang['files.create_success'] = '"%s" has been uploaded successfully.';
$lang['files.create_error'] = 'An error as occourred.';
$lang['files.edit_success'] = 'The file was successfully saved.';
$lang['files.edit_error'] = 'An error occurred while trying to save the file.';
$lang['files.delete_success'] = 'The file was deleted.';
$lang['files.delete_error'] = 'The file could not be deleted.';
$lang['files.mass_delete_success'] = '%d of %d files were successfully deleted. They were "%s and %s"';
$lang['files.mass_delete_error'] = 'An error occurred while trying to delete %d of %d files, they are "%s and %s".';
$lang['files.upload_error'] = 'A file must be uploaded.';
$lang['files.invalid_extension'] = 'File must have a valid extension.';
$lang['files.not_exists'] = 'An invalid folder has been selected.';
$lang['files.no_files'] = 'There are currently no files.';
$lang['files.no_permissions'] = 'You do not have permissions to see the files module.';
$lang['files.no_select_error'] = 'You must select a file first, his request was interrupted.';
// File folders
// Titles
$lang['file_folders.folders_title'] = 'File Folders';
$lang['file_folders.manage_title'] = 'Manage Folders';
$lang['file_folders.create_title'] = 'New Folder';
$lang['file_folders.delete_title'] = 'Confirm Delete';
$lang['file_folders.edit_title'] = 'Edit folder "%s"';
// Labels
$lang['file_folders.folders_label'] = 'Folders';
$lang['file_folders.folder_label'] = 'Folder';
$lang['file_folders.subfolders_label'] = 'Sub-Folders';
$lang['file_folders.parent_label'] = 'Parent';
$lang['file_folders.name_label'] = 'Name';
$lang['file_folders.slug_label'] = 'URL Slug';
$lang['file_folders.created_label'] = 'Created On';
// Messages
$lang['file_folders.create_success'] = 'The folder has now been saved.';
$lang['file_folders.create_error'] = 'An error occurred while attempting to create your folder.';
$lang['file_folders.duplicate_error'] = 'A folder named "%s" already exists.';
$lang['file_folders.edit_success'] = 'The folder was successfully saved.';
$lang['file_folders.edit_error'] = 'An error occurred while trying to save the changes.';
$lang['file_folders.confirm_delete'] = 'Are you sure you want to delete the folders below, including all files and subfolders inside them?';
$lang['file_folders.delete_mass_success'] = '%d of %d folders have been successfully deleted, they were %s and %s.';
$lang['file_folders.delete_mass_error'] = 'An error occurred while trying to delete %d of %d folders, they are "%s and %s".';
$lang['file_folders.delete_success'] = 'The folder "%s" was deleted.';
$lang['file_folders.delete_error'] = 'An error occurred while trying to delete the folder "%s".';
$lang['file_folders.not_exists'] = 'An invalid folder has been selected.';
$lang['file_folders.no_subfolders'] = 'None';
$lang['file_folders.no_folders'] = 'Your files are sorted by folders, currently you do not have any folders setup.';
$lang['file_folders.mkdir_error'] = 'Could not make the uploads/files directory';
$lang['file_folders.chmod_error'] = 'Could not chmod the uploads/files directory';
$lang['file_folders.no_select_error'] = 'An invalid folder has been selected.';
$lang['file_folders.edit'] = 'Edit ';
$lang['file_folders.delete'] = 'Delete ';
$lang['file_folders.cancel'] = 'Cancel';
$lang['file_folders.yes'] = 'Yes';
$lang['file_folders.no'] = 'No';
// Activity
$lang['files.upload_record'] = 'Upload File';
$lang['files.edit_record'] = 'Edit File';
$lang['files.delete_record'] = 'Delete File';
$lang['file_folders.create_record'] = 'Create File Folder';
$lang['file_folders.edit_record'] = 'Edit File Folder';
$lang['file_folders.delete_record'] = 'Delete File Folder';
// Nav
$lang['files.list_file'] = 'List Folder';
$lang['files.list_file_description'] = 'List Folder Description';
$lang['files.upload_file'] = 'Upload File';
$lang['files.upload_file_description'] = 'Upload File Description';
$lang['files.create_folder'] = 'Create Folder';
$lang['files.create_folder_description'] = 'Create Folder Description';
// wysiwyg
$lang['files.button_close'] = 'Close';
/* End of file files_lang.php */
|
{
"content_hash": "c4aee64b3a124ed19ecf76e142946a6e",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 141,
"avg_line_length": 47.73275862068966,
"alnum_prop": 0.6501715730540003,
"repo_name": "theRexxar/browns",
"id": "2801616d80530b73ebb7dd2f1e1c6b528a2e8678",
"size": "5537",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "system/modules/files/language/english/files_lang.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "410040"
},
{
"name": "CoffeeScript",
"bytes": "4600"
},
{
"name": "JavaScript",
"bytes": "1290791"
},
{
"name": "PHP",
"bytes": "3968553"
},
{
"name": "Shell",
"bytes": "401"
}
],
"symlink_target": ""
}
|
package examples.generated.always.mybatis;
import java.sql.JDBCType;
import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable;
public final class PersonDynamicSqlSupport {
public static final Person person = new Person();
public static final SqlColumn<Integer> id = person.id;
public static final SqlColumn<String> firstName = person.firstName;
public static final SqlColumn<String> lastName = person.lastName;
public static final class Person extends SqlTable {
public final SqlColumn<Integer> id = column("id", JDBCType.INTEGER);
public final SqlColumn<String> firstName = column("first_name", JDBCType.VARCHAR);
public final SqlColumn<String> lastName = column("last_name", JDBCType.VARCHAR);
public Person() {
super("Person");
}
}
}
|
{
"content_hash": "e054ac07fcd7f9574248b64f5f617e92",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 90,
"avg_line_length": 35.166666666666664,
"alnum_prop": 0.7144549763033176,
"repo_name": "jeffgbutler/mybatis-dynamic-sql",
"id": "ec68a3404713a143d298219bcb2c7cc80ba5d6a6",
"size": "1493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/examples/generated/always/mybatis/PersonDynamicSqlSupport.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "683"
},
{
"name": "Java",
"bytes": "1864631"
},
{
"name": "Kotlin",
"bytes": "579039"
}
],
"symlink_target": ""
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.vector_ar.svar_model.SVAR.y" href="statsmodels.tsa.vector_ar.svar_model.SVAR.y.html" />
<link rel="prev" title="statsmodels.tsa.vector_ar.svar_model.SVAR.endog_names" href="statsmodels.tsa.vector_ar.svar_model.SVAR.endog_names.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.1</span>
<span class="md-header-nav__topic"> statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../vector_ar.html" class="md-tabs__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.vector_ar.svar_model.SVAR.html" class="md-tabs__link">statsmodels.tsa.vector_ar.svar_model.SVAR</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.1</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-vector-ar-svar-model-svar-exog-names--page-root">statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names<a class="headerlink" href="#generated-statsmodels-tsa-vector-ar-svar-model-svar-exog-names--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt id="statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names">
<em class="property">property </em><code class="sig-prename descclassname">SVAR.</code><code class="sig-name descname">exog_names</code><a class="headerlink" href="#statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names" title="Permalink to this definition">¶</a></dt>
<dd><p>The names of the exogenous variables.</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.vector_ar.svar_model.SVAR.endog_names.html" title="statsmodels.tsa.vector_ar.svar_model.SVAR.endog_names"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.vector_ar.svar_model.SVAR.endog_names </span>
</div>
</a>
<a href="statsmodels.tsa.vector_ar.svar_model.SVAR.y.html" title="statsmodels.tsa.vector_ar.svar_model.SVAR.y"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.vector_ar.svar_model.SVAR.y </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 29, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
{
"content_hash": "45c4d3dcaf57463eed05800599998fc3",
"timestamp": "",
"source": "github",
"line_count": 449,
"max_line_length": 999,
"avg_line_length": 39.43207126948775,
"alnum_prop": 0.5976277887602373,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "50fba5986e21b50cbbc55ef01e919b28c66dcf42",
"size": "17709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.12.1/generated/statsmodels.tsa.vector_ar.svar_model.SVAR.exog_names.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
<?php
namespace Magento\Sales\Test\TestCase;
use Magento\Sales\Test\Constraint\AssertOrderStatusSuccessAssignMessage;
use Magento\Sales\Test\Fixture\OrderInjectable;
use Magento\Sales\Test\Fixture\OrderStatus;
use Magento\Sales\Test\Page\Adminhtml\OrderIndex;
use Magento\Sales\Test\Page\Adminhtml\OrderStatusAssign;
use Magento\Sales\Test\Page\Adminhtml\OrderStatusIndex;
use Magento\Mtf\Fixture\FixtureFactory;
use Magento\Mtf\TestCase\Injectable;
/**
* Preconditions:
* 1. Custom Order Status is created.
*
* Steps:
* 1. Log in as admin.
* 2. Navigate to the Stores > Settings > Order Status.
* 3. Click on "Assign Status to State.
* 4. Fill in all data according to data set.
* 5. Save Status Assignment.
* 6. Call assert assertOrderStatusSuccessAssignMessage.
* 7. Create Order.
* 8. Perform all assertions from dataset.
*
* @group Order_Management_(CS)
* @ZephyrId MAGETWO-29382
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AssignCustomOrderStatusTest extends Injectable
{
/* tags */
const MVP = 'yes';
const DOMAIN = 'CS';
/* end tags */
/**
* Order Status Index page.
*
* @var OrderStatusIndex
*/
protected $orderStatusIndex;
/**
* Order Status Assign page.
*
* @var OrderStatusAssign
*/
protected $orderStatusAssign;
/**
* Order Index page.
*
* @var OrderIndex
*/
protected $orderIndex;
/**
* OrderStatus Fixture.
*
* @var OrderStatus
*/
protected $orderStatus;
/**
* OrderInjectable Fixture.
*
* @var OrderInjectable
*/
protected $order;
/**
* Fixture factory.
*
* @var FixtureFactory
*/
protected $fixtureFactory;
/**
* Prepare data.
*
* @param FixtureFactory $fixtureFactory
* @return void
*/
public function __prepare(FixtureFactory $fixtureFactory)
{
$this->fixtureFactory = $fixtureFactory;
}
/**
* Inject pages.
*
* @param OrderStatusIndex $orderStatusIndex
* @param OrderStatusAssign $orderStatusAssign
* @param OrderIndex $orderIndex
* @return void
*/
public function __inject(
OrderStatusIndex $orderStatusIndex,
OrderStatusAssign $orderStatusAssign,
OrderIndex $orderIndex
) {
$this->orderStatusIndex = $orderStatusIndex;
$this->orderStatusAssign = $orderStatusAssign;
$this->orderIndex = $orderIndex;
}
/**
* Run Assign Custom OrderStatus.
*
* @param OrderStatus $orderStatus
* @param OrderInjectable $order
* @param array $orderStatusState
* @param AssertOrderStatusSuccessAssignMessage $assertion
* @return array
*/
public function test(
OrderStatus $orderStatus,
OrderInjectable $order,
array $orderStatusState,
AssertOrderStatusSuccessAssignMessage $assertion
) {
// Preconditions:
$orderStatus->persist();
/** @var OrderStatus $orderStatus */
$orderStatus = $this->fixtureFactory->createByCode(
'orderStatus',
['data' => array_merge($orderStatus->getData(), $orderStatusState)]
);
$this->orderStatus = $orderStatus;
// Steps:
$this->orderStatusIndex->open();
$this->orderStatusIndex->getGridPageActions()->assignStatusToState();
$this->orderStatusAssign->getAssignForm()->fill($orderStatus);
$this->orderStatusAssign->getPageActionsBlock()->save();
$assertion->processAssert($this->orderStatusIndex);
// Prepare data for constraints
$config = $this->fixtureFactory->createByCode('configData', [
'dataset' => 'checkmo_custom_new_order_status',
'data' => ['payment/checkmo/order_status' => ['value' => $orderStatus->getStatus()]]
]);
$config->persist();
$order->persist();
$this->order = $order;
return [
'orderId' => $order->getId(),
'customer' => $order->getDataFieldConfig('customer_id')['source']->getCustomer(),
'status' => $orderStatus->getLabel()
];
}
/**
* Change created order status and unassign custom order status.
*
* @return void
*/
public function tearDown()
{
if ($this->order) {
$this->orderIndex->open()->getSalesOrderGrid()->massaction([['id' => $this->order->getId()]], 'Cancel');
}
if ($this->orderStatus) {
$filter = ['label' => $this->orderStatus->getLabel()];
$this->orderStatusIndex->open()->getOrderStatusGrid()->searchAndUnassign($filter);
$this->orderStatusIndex->getMessagesBlock()->waitSuccessMessage();
$this->objectManager->create(
'Magento\Config\Test\TestStep\SetupConfigurationStep',
['configData' => 'checkmo_custom_new_order_status_rollback']
)->run();
}
}
}
|
{
"content_hash": "8ee48816480f92c439f970ecc39215f4",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 116,
"avg_line_length": 28.1123595505618,
"alnum_prop": 0.6135091926458833,
"repo_name": "enettolima/magento-training",
"id": "84fe74fb7fd1d34f9ea2d899a0f4c4b0c1e86f8f",
"size": "5102",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "magento2ce/dev/tests/functional/tests/app/Magento/Sales/Test/TestCase/AssignCustomOrderStatusTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "22648"
},
{
"name": "CSS",
"bytes": "3382928"
},
{
"name": "HTML",
"bytes": "8749335"
},
{
"name": "JavaScript",
"bytes": "7355635"
},
{
"name": "PHP",
"bytes": "58607662"
},
{
"name": "Perl",
"bytes": "10258"
},
{
"name": "Shell",
"bytes": "41887"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
}
|
'use strict';
var fs = require('fs');
var fsutil = require('fs-utils');
var gutil = require('gulp-util');
var es = require('event-stream');
var pkgcloud = require('pkgcloud');
var PluginError = gutil.PluginError;
var PLUGIN = 'gulp-highwinds';
module.exports = function (highwinds, options) {
var options = options || {};
var container = highwinds.container || options.container
if (!highwinds) { new gutil.PluginError(TAG, "No Highwinds configuration"); return false; }
if (!container) { new gutil.PluginError(TAG, "No container specified"); return false; }
if (!options.delay) { options.delay = 0; }
var client = pkgcloud.storage.createClient({
provider: "openstack",
username: highwinds.username,
password: highwinds.password,
authUrl: highwinds.authUrl,
version: 1
});
return es.mapSync(function (file, cb) {
var isFile = fs.lstatSync(file.path).isFile();
if (!isFile) { return false; }
var uploadPath = file.path.replace(file.base, fsutil.addSlash(options.uploadPath || '')).replace(/\\/g,'/');
var headers = { 'x-amz-acl': 'public-read' };
if (options.headers) {
for (var key in options.headers) {
headers[key] = options.headers[key];
}
}
var readStream = fs.createReadStream(file.path);
var writeStream = client.upload({
container: container,
remote: uploadPath,
headers: headers
});
writeStream.on('error', function(err) {
new gutil.PluginError(TAG, err);
});
writeStream.on('success', function(file) {
gutil.log(TAG, gutil.colors.green('[SUCCESS]', file.name));
});
readStream.pipe(writeStream);
});
};
|
{
"content_hash": "243c0a249c3827e1001b747dc1206731",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 110,
"avg_line_length": 30.09259259259259,
"alnum_prop": 0.6652307692307692,
"repo_name": "kollegorna/gulp-highwinds",
"id": "7bba0f632234ee6f73f8c9232cfa1062d1ed05a4",
"size": "1625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1846"
}
],
"symlink_target": ""
}
|
void protobuf_AddDesc_test_5fmsg_2eproto();
void protobuf_AssignDesc_test_5fmsg_2eproto();
void protobuf_ShutdownFile_test_5fmsg_2eproto();
class Triplet;
class Duplet;
// ===================================================================
class Triplet : public ::google::protobuf::Message {
public:
Triplet();
virtual ~Triplet();
Triplet(const Triplet& from);
inline Triplet& operator=(const Triplet& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Triplet& default_instance();
void Swap(Triplet* other);
// implements Message ----------------------------------------------
Triplet* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Triplet& from);
void MergeFrom(const Triplet& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required int32 a = 1;
inline bool has_a() const;
inline void clear_a();
static const int kAFieldNumber = 1;
inline ::google::protobuf::int32 a() const;
inline void set_a(::google::protobuf::int32 value);
// required int32 b = 2;
inline bool has_b() const;
inline void clear_b();
static const int kBFieldNumber = 2;
inline ::google::protobuf::int32 b() const;
inline void set_b(::google::protobuf::int32 value);
// required int32 c = 3;
inline bool has_c() const;
inline void clear_c();
static const int kCFieldNumber = 3;
inline ::google::protobuf::int32 c() const;
inline void set_c(::google::protobuf::int32 value);
// @@protoc_insertion_point(class_scope:Triplet)
private:
inline void set_has_a();
inline void clear_has_a();
inline void set_has_b();
inline void clear_has_b();
inline void set_has_c();
inline void clear_has_c();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::int32 a_;
::google::protobuf::int32 b_;
::google::protobuf::int32 c_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(3 + 31) / 32];
friend void protobuf_AddDesc_test_5fmsg_2eproto();
friend void protobuf_AssignDesc_test_5fmsg_2eproto();
friend void protobuf_ShutdownFile_test_5fmsg_2eproto();
void InitAsDefaultInstance();
static Triplet* default_instance_;
};
// -------------------------------------------------------------------
class Duplet : public ::google::protobuf::Message {
public:
Duplet();
virtual ~Duplet();
Duplet(const Duplet& from);
inline Duplet& operator=(const Duplet& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Duplet& default_instance();
void Swap(Duplet* other);
// implements Message ----------------------------------------------
Duplet* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Duplet& from);
void MergeFrom(const Duplet& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required int32 a = 1;
inline bool has_a() const;
inline void clear_a();
static const int kAFieldNumber = 1;
inline ::google::protobuf::int32 a() const;
inline void set_a(::google::protobuf::int32 value);
// required int32 b = 2;
inline bool has_b() const;
inline void clear_b();
static const int kBFieldNumber = 2;
inline ::google::protobuf::int32 b() const;
inline void set_b(::google::protobuf::int32 value);
// @@protoc_insertion_point(class_scope:Duplet)
private:
inline void set_has_a();
inline void clear_has_a();
inline void set_has_b();
inline void clear_has_b();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::int32 a_;
::google::protobuf::int32 b_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(2 + 31) / 32];
friend void protobuf_AddDesc_test_5fmsg_2eproto();
friend void protobuf_AssignDesc_test_5fmsg_2eproto();
friend void protobuf_ShutdownFile_test_5fmsg_2eproto();
void InitAsDefaultInstance();
static Duplet* default_instance_;
};
// ===================================================================
// ===================================================================
// Triplet
// required int32 a = 1;
inline bool Triplet::has_a() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Triplet::set_has_a() {
_has_bits_[0] |= 0x00000001u;
}
inline void Triplet::clear_has_a() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Triplet::clear_a() {
a_ = 0;
clear_has_a();
}
inline ::google::protobuf::int32 Triplet::a() const {
return a_;
}
inline void Triplet::set_a(::google::protobuf::int32 value) {
set_has_a();
a_ = value;
}
// required int32 b = 2;
inline bool Triplet::has_b() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Triplet::set_has_b() {
_has_bits_[0] |= 0x00000002u;
}
inline void Triplet::clear_has_b() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Triplet::clear_b() {
b_ = 0;
clear_has_b();
}
inline ::google::protobuf::int32 Triplet::b() const {
return b_;
}
inline void Triplet::set_b(::google::protobuf::int32 value) {
set_has_b();
b_ = value;
}
// required int32 c = 3;
inline bool Triplet::has_c() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void Triplet::set_has_c() {
_has_bits_[0] |= 0x00000004u;
}
inline void Triplet::clear_has_c() {
_has_bits_[0] &= ~0x00000004u;
}
inline void Triplet::clear_c() {
c_ = 0;
clear_has_c();
}
inline ::google::protobuf::int32 Triplet::c() const {
return c_;
}
inline void Triplet::set_c(::google::protobuf::int32 value) {
set_has_c();
c_ = value;
}
// -------------------------------------------------------------------
// Duplet
// required int32 a = 1;
inline bool Duplet::has_a() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Duplet::set_has_a() {
_has_bits_[0] |= 0x00000001u;
}
inline void Duplet::clear_has_a() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Duplet::clear_a() {
a_ = 0;
clear_has_a();
}
inline ::google::protobuf::int32 Duplet::a() const {
return a_;
}
inline void Duplet::set_a(::google::protobuf::int32 value) {
set_has_a();
a_ = value;
}
// required int32 b = 2;
inline bool Duplet::has_b() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Duplet::set_has_b() {
_has_bits_[0] |= 0x00000002u;
}
inline void Duplet::clear_has_b() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Duplet::clear_b() {
b_ = 0;
clear_has_b();
}
inline ::google::protobuf::int32 Duplet::b() const {
return b_;
}
inline void Duplet::set_b(::google::protobuf::int32 value) {
set_has_b();
b_ = value;
}
// @@protoc_insertion_point(namespace_scope)
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_test_5fmsg_2eproto__INCLUDED
|
{
"content_hash": "19b4278f8da245c093bebb4fb4b97211",
"timestamp": "",
"source": "github",
"line_count": 337,
"max_line_length": 102,
"avg_line_length": 26.26706231454006,
"alnum_prop": 0.6137596023497515,
"repo_name": "riba1122/google_protobuf_testing",
"id": "49d41bd5744d6c52cfbbf9f7b7df93e2fda1a039",
"size": "9841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test_msg.pb.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "0"
},
{
"name": "Python",
"bytes": "0"
}
],
"symlink_target": ""
}
|
namespace ui {
class AXFragmentRootWin;
class AXSystemCaretWin;
class WindowEventTarget;
} // namespace ui
namespace content {
class DirectManipulationBrowserTestBase;
class DirectManipulationHelper;
class RenderWidgetHostViewAura;
// Reasons for the existence of this class outlined below:-
// 1. Some screen readers expect every tab / every unique web content container
// to be in its own HWND with class name Chrome_RenderWidgetHostHWND.
// With Aura there is one main HWND which comprises the whole browser window
// or the whole desktop. So, we need a fake HWND with the window class as
// Chrome_RenderWidgetHostHWND as the root of the accessibility tree for
// each tab.
// 2. There are legacy drivers for trackpads/trackpoints which have special
// code for sending mouse wheel and scroll events to the
// Chrome_RenderWidgetHostHWND window.
// 3. Windowless NPAPI plugins like Flash and Silverlight which expect the
// container window to have the same bounds as the web page. In Aura, the
// default container window is the whole window which includes the web page
// WebContents, etc. This causes the plugin mouse event calculations to
// fail.
// We should look to get rid of this code when all of the above are fixed.
// This class implements a child HWND with the same size as the content area,
// that delegates its accessibility implementation to the root of the
// BrowserAccessibilityManager tree. This HWND is hooked up as the parent of
// the root object in the BrowserAccessibilityManager tree, so when any
// accessibility client calls ::WindowFromAccessibleObject, they get this
// HWND instead of the DesktopWindowTreeHostWin.
class CONTENT_EXPORT LegacyRenderWidgetHostHWND
: public ATL::CWindowImpl<LegacyRenderWidgetHostHWND,
ATL::CWindow,
ATL::CWinTraits<WS_CHILD>>,
public ui::AXFragmentRootDelegateWin {
public:
DECLARE_WND_CLASS_EX(ui::kLegacyRenderWidgetHostHwnd, CS_DBLCLKS, 0)
typedef ATL::CWindowImpl<LegacyRenderWidgetHostHWND,
ATL::CWindow,
ATL::CWinTraits<WS_CHILD>>
Base;
// Creates and returns an instance of the LegacyRenderWidgetHostHWND class on
// successful creation of a child window parented to the parent window passed
// in.
static LegacyRenderWidgetHostHWND* Create(HWND parent);
LegacyRenderWidgetHostHWND(const LegacyRenderWidgetHostHWND&) = delete;
LegacyRenderWidgetHostHWND& operator=(const LegacyRenderWidgetHostHWND&) =
delete;
// Destroys the HWND managed by this class.
void Destroy();
BEGIN_MSG_MAP_EX(LegacyRenderWidgetHostHWND)
MESSAGE_HANDLER_EX(WM_GETOBJECT, OnGetObject)
MESSAGE_RANGE_HANDLER(WM_KEYFIRST, WM_KEYLAST, OnKeyboardRange)
MESSAGE_HANDLER_EX(WM_PAINT, OnPaint)
MESSAGE_HANDLER_EX(WM_NCPAINT, OnNCPaint)
MESSAGE_HANDLER_EX(WM_ERASEBKGND, OnEraseBkGnd)
MESSAGE_HANDLER_EX(WM_INPUT, OnInput)
MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseRange)
MESSAGE_HANDLER_EX(WM_MOUSELEAVE, OnMouseLeave)
MESSAGE_HANDLER_EX(WM_MOUSEACTIVATE, OnMouseActivate)
MESSAGE_HANDLER_EX(WM_SETCURSOR, OnSetCursor)
MESSAGE_HANDLER_EX(WM_TOUCH, OnTouch)
MESSAGE_HANDLER_EX(WM_POINTERDOWN, OnPointer)
MESSAGE_HANDLER_EX(WM_POINTERUPDATE, OnPointer)
MESSAGE_HANDLER_EX(WM_POINTERUP, OnPointer)
MESSAGE_HANDLER_EX(WM_POINTERENTER, OnPointer)
MESSAGE_HANDLER_EX(WM_POINTERLEAVE, OnPointer)
MESSAGE_HANDLER_EX(WM_HSCROLL, OnScroll)
MESSAGE_HANDLER_EX(WM_VSCROLL, OnScroll)
MESSAGE_HANDLER_EX(WM_NCHITTEST, OnNCHitTest)
MESSAGE_RANGE_HANDLER(WM_NCMOUSEMOVE, WM_NCXBUTTONDBLCLK,
OnMouseRange)
MESSAGE_HANDLER_EX(WM_NCCALCSIZE, OnNCCalcSize)
MESSAGE_HANDLER_EX(WM_SIZE, OnSize)
MESSAGE_HANDLER_EX(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER_EX(DM_POINTERHITTEST, OnPointerHitTest)
END_MSG_MAP()
HWND hwnd() { return m_hWnd; }
// Called when the child window is to be reparented to a new window.
// The |parent| parameter contains the new parent window.
void UpdateParent(HWND parent);
HWND GetParent();
IAccessible* window_accessible() { return window_accessible_.Get(); }
// Functions to show and hide the window.
void Show();
void Hide();
// Resizes the window to the bounds passed in.
void SetBounds(const gfx::Rect& bounds);
// The pointer to the containing RenderWidgetHostViewAura instance is passed
// here.
void set_host(RenderWidgetHostViewAura* host) {
host_ = host;
}
// Return the root accessible object for either MSAA or UI Automation.
gfx::NativeViewAccessible GetOrCreateWindowRootAccessible(
bool is_uia_request);
protected:
void OnFinalMessage(HWND hwnd) override;
private:
friend class AccessibilityObjectLifetimeWinBrowserTest;
friend class DirectManipulationBrowserTestBase;
LegacyRenderWidgetHostHWND();
~LegacyRenderWidgetHostHWND() override;
// If initialization fails, deletes `this` and returns false.
bool InitOrDeleteSelf(HWND parent);
// Returns the target to which the windows input events are forwarded.
static ui::WindowEventTarget* GetWindowEventTarget(HWND parent);
LRESULT OnEraseBkGnd(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnGetObject(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnInput(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnKeyboardRange(UINT message, WPARAM w_param, LPARAM l_param,
BOOL& handled);
LRESULT OnMouseLeave(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnMouseRange(UINT message, WPARAM w_param, LPARAM l_param,
BOOL& handled);
LRESULT OnMouseActivate(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnPointer(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnTouch(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnScroll(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnNCHitTest(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnNCPaint(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnPaint(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnSetCursor(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnNCCalcSize(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnSize(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnDestroy(UINT message, WPARAM w_param, LPARAM l_param);
LRESULT OnPointerHitTest(UINT message, WPARAM w_param, LPARAM l_param);
// Overridden from AXFragmentRootDelegateWin.
gfx::NativeViewAccessible GetChildOfAXFragmentRoot() override;
gfx::NativeViewAccessible GetParentOfAXFragmentRoot() override;
bool IsAXFragmentRootAControlElement() override;
gfx::NativeViewAccessible GetOrCreateBrowserAccessibilityRoot();
Microsoft::WRL::ComPtr<IAccessible> window_accessible_;
// Set to true if we turned on mouse tracking.
bool mouse_tracking_enabled_;
raw_ptr<RenderWidgetHostViewAura> host_;
// Some assistive software need to track the location of the caret.
std::unique_ptr<ui::AXSystemCaretWin> ax_system_caret_;
// Implements IRawElementProviderFragmentRoot when UIA is enabled.
std::unique_ptr<ui::AXFragmentRootWin> ax_fragment_root_;
// Set to true when we return a UIA object. Determines whether we need to
// call UIA to clean up object references on window destruction.
// This is important to avoid triggering a cross-thread COM call which could
// cause re-entrancy during teardown. https://crbug.com/1087553
bool did_return_uia_object_;
// This class provides functionality to register the legacy window as a
// Direct Manipulation consumer. This allows us to support smooth scroll
// in Chrome on Windows 10.
std::unique_ptr<DirectManipulationHelper> direct_manipulation_helper_;
base::WeakPtrFactory<LegacyRenderWidgetHostHWND> weak_factory_{this};
};
} // namespace content
#endif // CONTENT_BROWSER_RENDERER_HOST_LEGACY_RENDER_WIDGET_HOST_WIN_H_
|
{
"content_hash": "66c2a6a8ab0c50ce39299105901e7e4f",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 79,
"avg_line_length": 42.21989528795812,
"alnum_prop": 0.7472718253968254,
"repo_name": "chromium/chromium",
"id": "11ae0ec65f8b3eab782e9f660ba21bc6fccdc7e2",
"size": "8855",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "content/browser/renderer_host/legacy_render_widget_host_win.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
<component name="libraryTable">
<library name="espresso-idling-resource-2.2.2">
<CLASSES>
<root url="jar://$USER_HOME$/.android/build-cache/fe9482c51875251e64d8630d954addf2a6aab908/output/jars/classes.jar!/" />
<root url="file://$USER_HOME$/.android/build-cache/fe9482c51875251e64d8630d954addf2a6aab908/output/res" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/test/espresso/espresso-idling-resource/2.2.2/espresso-idling-resource-2.2.2-sources.jar!/" />
</SOURCES>
</library>
</component>
|
{
"content_hash": "f6d5ab80db205cdbbc2bfb480b9932c4",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 202,
"avg_line_length": 52,
"alnum_prop": 0.7147435897435898,
"repo_name": "Kuruchy/and_mymovies",
"id": "7fd0c252157cef3af844f96b249c1ca41fb0df0b",
"size": "624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/espresso_idling_resource_2_2_2.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "91488"
}
],
"symlink_target": ""
}
|
// Copyright 1997-2001 Association for Universities for Research in Astronomy, Inc.,
// Observatory Control System, Gemini Telescopes Project.
// See the file LICENSE for complete details.
//
// $Id: SciAreaFeature.java 21635 2009-08-24 01:08:24Z swalker $
//
package jsky.app.ot.gemini.inst;
import edu.gemini.shared.util.immutable.None;
import edu.gemini.shared.util.immutable.Option;
import edu.gemini.spModel.core.Offset;
import edu.gemini.spModel.gemini.acqcam.InstAcqCam;
import edu.gemini.spModel.gemini.bhros.InstBHROS;
import edu.gemini.spModel.gemini.flamingos2.F2ScienceAreaGeometry$;
import edu.gemini.spModel.gemini.flamingos2.Flamingos2;
import edu.gemini.spModel.gemini.gmos.InstGmosCommon;
import edu.gemini.spModel.gemini.gnirs.InstGNIRS;
import edu.gemini.spModel.gemini.gpi.Gpi;
import edu.gemini.spModel.gemini.gsaoi.Gsaoi;
import edu.gemini.spModel.gemini.michelle.InstMichelle;
import edu.gemini.spModel.gemini.nici.InstNICI;
import edu.gemini.spModel.gemini.nifs.InstNIFS;
import edu.gemini.spModel.gemini.niri.InstNIRI;
import edu.gemini.spModel.gemini.phoenix.InstPhoenix;
import edu.gemini.spModel.gemini.texes.InstTexes;
import edu.gemini.spModel.gemini.trecs.InstTReCS;
import edu.gemini.spModel.obscomp.SPInstObsComp;
import jsky.app.ot.gemini.acqcam.AcqCam_SciAreaFeature;
import jsky.app.ot.gemini.bhros.BHROS_SciAreaFeature;
import jsky.app.ot.gemini.gnirs.GNIRS_SciAreaFeature;
import jsky.app.ot.gemini.gpi.Gpi_SciAreaFeature;
import jsky.app.ot.gemini.gsaoi.GsaoiDetectorArrayFeature;
import jsky.app.ot.gemini.michelle.Michelle_SciAreaFeature;
import jsky.app.ot.gemini.nici.NICI_SciAreaFeature;
import jsky.app.ot.gemini.nifs.NIFS_SciAreaFeature;
import jsky.app.ot.gemini.niri.NIRI_SciAreaFeature;
import jsky.app.ot.gemini.phoenix.Phoenix_SciAreaFeature;
import jsky.app.ot.gemini.texes.Texes_SciAreaFeature;
import jsky.app.ot.gemini.trecs.TReCS_SciAreaFeature;
import jsky.app.ot.tpe.*;
import jsky.app.ot.util.BasicPropertyList;
import jsky.app.ot.util.PropertyWatcher;
import java.awt.*;
import java.awt.geom.Point2D;
/**
* Draws the science area.
* <p>
* This class is a wrapper for one of the instrument specific classes:
* NIRI_SciAreaFeature, NIFS_SciAreaFeature, GMOS_SciAreaFeature,AcqCam_SciAreaFeature,
* TReCS_SciAreaFeature, Michelle_SciAreaFeature,Phoenix_SciAreaFeature.
* The class used depends on the instrument being used.
*/
public class SciAreaFeature extends TpeImageFeature
implements TpeDraggableFeature, PropertyWatcher {
// The instrument OIWFS feature
private TpeImageFeature _feat;
// The instrument specific subclasses
private NIRI_SciAreaFeature _niriFeat;
private NIFS_SciAreaFeature _nifsFeat;
private BHROS_SciAreaFeature _bhrosFeat;
private AcqCam_SciAreaFeature _acqCamFeat;
private Phoenix_SciAreaFeature _phoenixFeat;
private TReCS_SciAreaFeature _trecsFeat;
private Michelle_SciAreaFeature _michelleFeat;
private GNIRS_SciAreaFeature _gnirsFeat;
private SciAreaPlotFeature _flamingos2Feat;
private NICI_SciAreaFeature _niciFeat;
private Texes_SciAreaFeature _texesFeat;
private Gpi_SciAreaFeature _gpiFeat;
private GsaoiDetectorArrayFeature _gsaoiFeat;
// properties (items are displayed in the OT View menu)
private static final BasicPropertyList _props = new BasicPropertyList(SciAreaFeature.class.getName());
private static final String PROP_DISPLAY_CHOP_BEAMS = "Display Chop Beams";
private static final String PROP_SHOW_TAGS = "Show Tags";
private static final String PROP_SCI_AREA_DISPLAY = "Display Science FOV at";
static {
// Initialize the properties supported by this feature.
_props.registerBooleanProperty(PROP_SHOW_TAGS, true);
_props.registerBooleanProperty(PROP_DISPLAY_CHOP_BEAMS, true);
_props.registerChoiceProperty(PROP_SCI_AREA_DISPLAY,
new String[]{"Selected Position", "All Positions", "None"},
0);
}
/**
* The mode that indicates that the science area should be drawn around
* the selected offset position.
*/
public static final int SCI_AREA_SELECTED = 0;
/**
* The mode that indicates that the science area should be drawn around
* all the selected offset positions.
*/
public static final int SCI_AREA_ALL = 1;
/**
* The mode that indicates that the science area should not be drawn
* at any offset positions.
*/
public static final int SCI_AREA_NONE = 2;
/**
* Construct the feature with its name and description.
*/
public SciAreaFeature() {
super("Science", "Show the science FOV.");
_props.addWatcher(this);
}
/**
* A property has changed.
*
* @see PropertyWatcher
*/
public void propertyChange(String propName) {
if (_iw != null) _iw.repaint();
}
/**
* Override getProperties to return the properties supported by this
* feature.
*/
public BasicPropertyList getProperties() {
return _props;
}
/** Static version of getProperties() */
public static BasicPropertyList getProps() {
return _props;
}
/**
* Turn the display of the chop beams on or off.
*/
public static void setDisplayChopBeams(boolean show) {
_props.setBoolean(PROP_DISPLAY_CHOP_BEAMS, show);
}
/**
* Get the "Display Chop Beams" property.
*/
public static boolean getDisplayChopBeams() {
return _props.getBoolean(PROP_DISPLAY_CHOP_BEAMS, true);
}
/**
* Turn on/off the drawing of the offset index.
*/
public static void setDrawIndex(boolean drawIndex) {
_props.setBoolean(PROP_SHOW_TAGS, drawIndex);
}
/**
* Get the state of the drawing of the offset index.
*/
public static boolean getDrawIndex() {
return _props.getBoolean(PROP_SHOW_TAGS, true);
}
/**
* Set the science area draw mode. Must be one of SCI_AREA_NONE,
* SCI_AREA_SELECTED, or SCI_AREA_ALL.
*/
public static void setSciAreaMode(int mode) {
_props.setChoice(PROP_SCI_AREA_DISPLAY, mode);
}
/**
* Get the mode. One of SCI_AREA_SELECTED, SCI_AREA_ALL, or SCI_AREA_NONE.
*/
public static int getSciAreaMode() {
return _props.getChoice(PROP_SCI_AREA_DISPLAY, SCI_AREA_SELECTED);
}
/**
* Return the current Nod/Chop offset in screen pixels.
*
* @see jsky.app.ot.gemini.trecs.TReCS_SciAreaFeature
*/
public Point2D.Double getNodChopOffset() {
return (_feat instanceof SciAreaFeatureBase) ?
((SciAreaFeatureBase) _feat).getNodChopOffset() :
new Point2D.Double();
}
/**
* Reinitialize the feature.
*/
public void reinit(TpeImageWidget iw, TpeImageInfo tii) {
super.reinit(iw, tii);
TpeContext ctx = iw.getContext();
if (ctx.isEmpty()) return;
SPInstObsComp inst = iw.getInstObsComp();
if (inst instanceof InstNIRI) {
if (_niriFeat == null) {
_niriFeat = new NIRI_SciAreaFeature();
}
_feat = _niriFeat;
} else if (inst instanceof InstNIFS) {
if (_nifsFeat == null) {
_nifsFeat = new NIFS_SciAreaFeature();
}
_feat = _nifsFeat;
} else if (inst instanceof InstBHROS) {
if (_bhrosFeat == null) {
_bhrosFeat = new BHROS_SciAreaFeature();
}
_feat = _bhrosFeat;
} else if (inst instanceof InstGmosCommon) {
_feat = GmosSciAreaPlotFeature$.MODULE$;
} else if (inst instanceof InstAcqCam) {
if (_acqCamFeat == null) {
_acqCamFeat = new AcqCam_SciAreaFeature();
}
_feat = _acqCamFeat;
} else if (inst instanceof InstPhoenix) {
if (_phoenixFeat == null) {
_phoenixFeat = new Phoenix_SciAreaFeature();
}
_feat = _phoenixFeat;
} else if (inst instanceof InstTReCS) {
if (_trecsFeat == null) {
_trecsFeat = new TReCS_SciAreaFeature();
}
_feat = _trecsFeat;
} else if (inst instanceof InstMichelle) {
if (_michelleFeat == null) {
_michelleFeat = new Michelle_SciAreaFeature();
}
_feat = _michelleFeat;
} else if (inst instanceof InstGNIRS) {
if (_gnirsFeat == null) {
_gnirsFeat = new GNIRS_SciAreaFeature();
}
_feat = _gnirsFeat;
} else if (inst instanceof Flamingos2) {
if (_flamingos2Feat == null) {
_flamingos2Feat = new SciAreaPlotFeature(F2ScienceAreaGeometry$.MODULE$);
}
_feat = _flamingos2Feat;
} else if (inst instanceof InstNICI) {
if (_niciFeat == null) {
_niciFeat = new NICI_SciAreaFeature();
}
_feat = _niciFeat;
} else if (inst instanceof InstTexes) {
if (_texesFeat == null) {
_texesFeat = new Texes_SciAreaFeature();
}
_feat = _texesFeat;
} else if (inst instanceof Gpi) {
if (_gpiFeat == null) {
_gpiFeat = new Gpi_SciAreaFeature();
}
_feat = _gpiFeat;
} else if (inst instanceof Gsaoi) {
if (_gsaoiFeat == null) {
_gsaoiFeat = new GsaoiDetectorArrayFeature();
}
_feat = _gsaoiFeat;
} else {
_feat = null;
}
if (_feat != null) {
_feat.reinit(iw, tii);
}
}
/**
* Unload the feature.
*/
public void unloaded() {
super.unloaded();
if (_feat != null) _feat.unloaded();
}
/**
* Draw the feature.
*/
public void draw(Graphics g, TpeImageInfo tii) {
if (_feat != null) _feat.draw(g, tii);
}
/**
* Draw the science area at the given offset. The x/y coordinates are the
* screen coordinates and are used by the old SciAreaFeatureBase-based
* delegates.
*/
public void drawAtOffsetPos(Graphics g, TpeImageInfo tii, Offset offset, double x, double y) {
if (_feat instanceof SciAreaFeatureBase) {
((SciAreaFeatureBase) _feat).drawAtOffsetPos(g, tii, x, y);
} else if (_feat instanceof SciAreaPlotFeature) {
((SciAreaPlotFeature) _feat).drawAtOffset(g, tii, offset);
}
}
/**
* The position angle has changed.
*/
public void posAngleUpdate(TpeImageInfo tii) {
if (_feat != null) _feat.posAngleUpdate(tii);
}
/**
* Start dragging the object.
*/
public Option<Object> dragStart(TpeMouseEvent tme, TpeImageInfo tii) {
if (_feat instanceof TpeDraggableFeature) {
return ((TpeDraggableFeature) _feat).dragStart(tme, tii);
} else {
return None.instance();
}
}
/**
* Drag to a new location.
*/
public void drag(TpeMouseEvent tme) {
if (_feat instanceof TpeDraggableFeature) {
((TpeDraggableFeature) _feat).drag(tme);
}
}
/**
* Stop dragging.
*/
public void dragStop(TpeMouseEvent tme) {
if (_feat instanceof TpeDraggableFeature) {
((TpeDraggableFeature) _feat).dragStop(tme);
}
}
/**
* Return true if the mouse is over an active part of this image feature
* (so that dragging can begin there).
*/
public boolean isMouseOver(TpeMouseEvent tme) {
return (_feat != null) && _feat.isMouseOver(tme);
}
@Override
public boolean isEnabledByDefault() {
return true;
}
public TpeImageFeatureCategory getCategory() {
return TpeImageFeatureCategory.fieldOfView;
}
}
|
{
"content_hash": "feb440ec4e295b53d8e68356bbaeb120",
"timestamp": "",
"source": "github",
"line_count": 366,
"max_line_length": 106,
"avg_line_length": 32.71857923497268,
"alnum_prop": 0.6295615866388309,
"repo_name": "fnussber/ocs",
"id": "519a7c44f6010a219e95f1e653c1d05e8d402928",
"size": "11975",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "bundle/jsky.app.ot/src/main/java/jsky/app/ot/gemini/inst/SciAreaFeature.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "7919"
},
{
"name": "HTML",
"bytes": "491513"
},
{
"name": "Java",
"bytes": "14373815"
},
{
"name": "JavaScript",
"bytes": "7962"
},
{
"name": "Scala",
"bytes": "5075673"
},
{
"name": "Shell",
"bytes": "4989"
},
{
"name": "Tcl",
"bytes": "2841"
}
],
"symlink_target": ""
}
|
package com.github.javaparser.symbolsolver.reflectionmodel;
import com.github.javaparser.ast.Node;
import com.github.javaparser.symbolsolver.core.resolution.Context;
import com.github.javaparser.symbolsolver.javaparsermodel.LambdaArgumentTypePlaceholder;
import com.github.javaparser.symbolsolver.javaparsermodel.contexts.ContextHelper;
import com.github.javaparser.symbolsolver.logic.AbstractClassDeclaration;
import com.github.javaparser.symbolsolver.model.declarations.*;
import com.github.javaparser.symbolsolver.model.methods.MethodUsage;
import com.github.javaparser.symbolsolver.model.resolution.SymbolReference;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.model.typesystem.ReferenceType;
import com.github.javaparser.symbolsolver.model.typesystem.ReferenceTypeImpl;
import com.github.javaparser.symbolsolver.model.typesystem.Type;
import com.github.javaparser.symbolsolver.reflectionmodel.comparators.MethodComparator;
import com.github.javaparser.symbolsolver.resolution.MethodResolutionLogic;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* @author Federico Tomassetti
*/
public class ReflectionClassDeclaration extends AbstractClassDeclaration {
///
/// Fields
///
private Class<?> clazz;
private TypeSolver typeSolver;
private ReflectionClassAdapter reflectionClassAdapter;
///
/// Constructors
///
public ReflectionClassDeclaration(Class<?> clazz, TypeSolver typeSolver) {
if (clazz == null) {
throw new IllegalArgumentException("Class should not be null");
}
if (clazz.isInterface()) {
throw new IllegalArgumentException("Class should not be an interface");
}
if (clazz.isPrimitive()) {
throw new IllegalArgumentException("Class should not represent a primitive class");
}
if (clazz.isArray()) {
throw new IllegalArgumentException("Class should not be an array");
}
if (clazz.isEnum()) {
throw new IllegalArgumentException("Class should not be an enum");
}
this.clazz = clazz;
this.typeSolver = typeSolver;
this.reflectionClassAdapter = new ReflectionClassAdapter(clazz, typeSolver, this);
}
///
/// Public methods
///
@Override
public Set<MethodDeclaration> getDeclaredMethods() {
return reflectionClassAdapter.getDeclaredMethods();
}
@Override
public List<ReferenceType> getAncestors() {
return reflectionClassAdapter.getAncestors();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReflectionClassDeclaration that = (ReflectionClassDeclaration) o;
if (!clazz.getCanonicalName().equals(that.clazz.getCanonicalName())) return false;
return true;
}
@Override
public int hashCode() {
return clazz.hashCode();
}
@Override
public String getPackageName() {
if (clazz.getPackage() != null) {
return clazz.getPackage().getName();
}
return null;
}
@Override
public String getClassName() {
String canonicalName = clazz.getCanonicalName();
if (canonicalName != null && getPackageName() != null) {
return canonicalName.substring(getPackageName().length() + 1, canonicalName.length());
}
return null;
}
@Override
public String getQualifiedName() {
return clazz.getCanonicalName();
}
@Deprecated
public SymbolReference<MethodDeclaration> solveMethod(String name, List<Type> argumentsTypes, boolean staticOnly) {
List<MethodDeclaration> methods = new ArrayList<>();
Predicate<Method> staticFilter = m -> !staticOnly || (staticOnly && Modifier.isStatic(m.getModifiers()));
for (Method method : Arrays.stream(clazz.getDeclaredMethods()).filter((m) -> m.getName().equals(name)).filter(staticFilter)
.sorted(new MethodComparator()).collect(Collectors.toList())) {
if (method.isBridge() || method.isSynthetic()) continue;
MethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
methods.add(methodDeclaration);
}
if (getSuperClass() != null) {
ClassDeclaration superClass = (ClassDeclaration) getSuperClass().getTypeDeclaration();
SymbolReference<MethodDeclaration> ref = MethodResolutionLogic.solveMethodInType(superClass, name, argumentsTypes, staticOnly, typeSolver);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
}
for (ReferenceType interfaceDeclaration : getInterfaces()) {
SymbolReference<MethodDeclaration> ref = MethodResolutionLogic.solveMethodInType(interfaceDeclaration.getTypeDeclaration(), name, argumentsTypes, staticOnly, typeSolver);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
}
return MethodResolutionLogic.findMostApplicable(methods, name, argumentsTypes, typeSolver);
}
@Override
public String toString() {
return "ReflectionClassDeclaration{" +
"clazz=" + getId() +
'}';
}
public Type getUsage(Node node) {
return new ReferenceTypeImpl(this, typeSolver);
}
public Optional<MethodUsage> solveMethodAsUsage(String name, List<Type> argumentsTypes, TypeSolver typeSolver, Context invokationContext, List<Type> typeParameterValues) {
List<MethodUsage> methods = new ArrayList<>();
for (Method method : Arrays.stream(clazz.getDeclaredMethods()).filter((m) -> m.getName().equals(name)).sorted(new MethodComparator()).collect(Collectors.toList())) {
if (method.isBridge() || method.isSynthetic()) continue;
MethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
MethodUsage methodUsage = new MethodUsage(methodDeclaration);
for (int i = 0; i < getTypeParameters().size() && i < typeParameterValues.size(); i++) {
TypeParameterDeclaration tpToReplace = getTypeParameters().get(i);
Type newValue = typeParameterValues.get(i);
methodUsage = methodUsage.replaceTypeParameter(tpToReplace, newValue);
}
methods.add(methodUsage);
}
if (getSuperClass() != null) {
ClassDeclaration superClass = (ClassDeclaration) getSuperClass().getTypeDeclaration();
Optional<MethodUsage> ref = ContextHelper.solveMethodAsUsage(superClass, name, argumentsTypes, typeSolver, invokationContext, typeParameterValues);
if (ref.isPresent()) {
methods.add(ref.get());
}
}
for (ReferenceType interfaceDeclaration : getInterfaces()) {
Optional<MethodUsage> ref = ContextHelper.solveMethodAsUsage(interfaceDeclaration.getTypeDeclaration(), name, argumentsTypes, typeSolver, invokationContext, typeParameterValues);
if (ref.isPresent()) {
methods.add(ref.get());
}
}
Optional<MethodUsage> ref = MethodResolutionLogic.findMostApplicableUsage(methods, name, argumentsTypes, typeSolver);
return ref;
}
@Override
public boolean canBeAssignedTo(ReferenceTypeDeclaration other) {
if (other instanceof LambdaArgumentTypePlaceholder) {
return isFunctionalInterface();
}
if (other.getQualifiedName().equals(getQualifiedName())) {
return true;
}
if (this.clazz.getSuperclass() != null
&& new ReflectionClassDeclaration(clazz.getSuperclass(), typeSolver).canBeAssignedTo(other)) {
return true;
}
for (Class<?> interfaze : clazz.getInterfaces()) {
if (new ReflectionInterfaceDeclaration(interfaze, typeSolver).canBeAssignedTo(other)) {
return true;
}
}
return false;
}
@Override
public boolean isAssignableBy(Type type) {
return reflectionClassAdapter.isAssignableBy(type);
}
@Override
public boolean isTypeParameter() {
return false;
}
@Override
public FieldDeclaration getField(String name) {
return reflectionClassAdapter.getField(name);
}
@Override
public List<FieldDeclaration> getAllFields() {
return reflectionClassAdapter.getAllFields();
}
@Deprecated
public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
for (Field field : clazz.getFields()) {
if (field.getName().equals(name)) {
return SymbolReference.solved(new ReflectionFieldDeclaration(field, typeSolver));
}
}
return SymbolReference.unsolved(ValueDeclaration.class);
}
@Override
public boolean hasDirectlyAnnotation(String canonicalName) {
return reflectionClassAdapter.hasDirectlyAnnotation(canonicalName);
}
@Override
public boolean hasField(String name) {
return reflectionClassAdapter.hasField(name);
}
@Override
public boolean isAssignableBy(ReferenceTypeDeclaration other) {
return isAssignableBy(new ReferenceTypeImpl(other, typeSolver));
}
@Override
public String getName() {
return clazz.getSimpleName();
}
@Override
public boolean isField() {
return false;
}
@Override
public boolean isParameter() {
return false;
}
@Override
public boolean isType() {
return true;
}
@Override
public boolean isClass() {
return !clazz.isInterface();
}
@Override
public ReferenceTypeImpl getSuperClass() {
return reflectionClassAdapter.getSuperClass();
}
@Override
public List<ReferenceType> getInterfaces() {
return reflectionClassAdapter.getInterfaces();
}
@Override
public boolean isInterface() {
return clazz.isInterface();
}
@Override
public List<TypeParameterDeclaration> getTypeParameters() {
return reflectionClassAdapter.getTypeParameters();
}
@Override
public AccessLevel accessLevel() {
return ReflectionFactory.modifiersToAccessLevel(this.clazz.getModifiers());
}
@Override
public List<ConstructorDeclaration> getConstructors() {
return reflectionClassAdapter.getConstructors();
}
@Override
public Optional<ReferenceTypeDeclaration> containerType() {
return reflectionClassAdapter.containerType();
}
@Override
public Set<ReferenceTypeDeclaration> internalTypes() {
return Arrays.stream(this.clazz.getDeclaredClasses())
.map(ic -> ReflectionFactory.typeDeclarationFor(ic, typeSolver))
.collect(Collectors.toSet());
}
///
/// Protected methods
///
@Override
protected ReferenceType object() {
return new ReferenceTypeImpl(typeSolver.solveType(Object.class.getCanonicalName()), typeSolver);
}
}
|
{
"content_hash": "34993b1b8337c6ad8f974495b32cdc5d",
"timestamp": "",
"source": "github",
"line_count": 329,
"max_line_length": 190,
"avg_line_length": 34.91489361702128,
"alnum_prop": 0.6680595455732568,
"repo_name": "rpau/java-symbol-solver",
"id": "c8d920e52f3c405a8e4d1010031e642b6b4e00c3",
"size": "12085",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "java-symbol-solver-testing/src/test/resources/javasymbolsolver_0_6_0/src/java-symbol-solver-core/com/github/javaparser/symbolsolver/reflectionmodel/ReflectionClassDeclaration.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1523041"
},
{
"name": "Shell",
"bytes": "44"
}
],
"symlink_target": ""
}
|
@implementation RegisterParam
@end
|
{
"content_hash": "c58b52e740688d9d0093f5ec96041940",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 29,
"avg_line_length": 12,
"alnum_prop": 0.8333333333333334,
"repo_name": "yellowwing/yueshenglicai",
"id": "e37cf86257795e48186eca8ecd21c3216113bcb8",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "YueSheng/YueSheng/Login(登录)/Model/Param/RegisterParam.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "1288918"
}
],
"symlink_target": ""
}
|
/**
* @module BgProcess
* @submodule models/Toolbar
*/
define(['backbone'], function (BB) {
/**
* Region toolbar for buttons
* @class Toolbar
* @constructor
* @extends Backbone.Model
*/
var Toolbar = BB.Model.extend({
defaults: {
/**
* @attribute region
* @type String
* @default feeds
*/
region: 'feeds',
/**
* @attribute position
* @type String
* @default top
*/
position: 'top',
/**
* List of actions. Each action = one button/search on toolbar
* @attribute actions
* @type Array
* @default []
*/
actions: [],
/**
* Version of toolbar (if any default changes are made -> version++)
* @attribute actions
* @type Array
* @default []
*/
version: 1
},
/**
* @method initialize
*/
initialize: function() {
// ...
}
});
return Toolbar;
});
|
{
"content_hash": "f5666236f33e7f76be0d0a1badae53fc",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 71,
"avg_line_length": 16.89090909090909,
"alnum_prop": 0.5123789020452099,
"repo_name": "BS-Harou/Smart-RSS",
"id": "d04d5aab7f1b85eef11c5a87dc05123167e83110",
"size": "929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/bgprocess/models/Toolbar.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "35320"
},
{
"name": "HTML",
"bytes": "22620"
},
{
"name": "JavaScript",
"bytes": "300951"
}
],
"symlink_target": ""
}
|
class FakeBrickLVM(object):
"""Logs and records calls, for unit tests."""
def __init__(self, vg_name, create, pv_list, vtype, execute=None):
super(FakeBrickLVM, self).__init__()
self.vg_size = '5.00'
self.vg_free_space = '5.00'
self.vg_name = vg_name
def supports_thin_provisioning():
return False
def get_volumes(self):
return ['fake-volume']
def get_volume(self, name):
return ['name']
def get_all_physical_volumes(vg_name=None):
return []
def get_physical_volumes(self):
return []
def update_volume_group_info(self):
pass
def create_thin_pool(self, name=None, size_str=0):
pass
def create_volume(self, name, size_str, lv_type='default', mirror_count=0):
pass
def create_lv_snapshot(self, name, source_lv_name, lv_type='default'):
pass
def delete(self, name):
pass
def revert(self, snapshot_name):
pass
def lv_has_snapshot(self, name):
return False
def activate_lv(self, lv, is_snapshot=False, permanent=False):
pass
def rename_volume(self, lv_name, new_name):
pass
|
{
"content_hash": "6d8baffb5232cc408b16b5278bfc4cb0",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 79,
"avg_line_length": 23.82,
"alnum_prop": 0.5910999160369438,
"repo_name": "openstack/os-brick",
"id": "4f47c5483a0139cf27765d4b9224816fbc0cd814",
"size": "1765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "os_brick/tests/local_dev/fake_lvm.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "1136394"
},
{
"name": "Shell",
"bytes": "3226"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_36) on Tue Dec 29 00:09:29 CST 2015 -->
<title>Processor</title>
<meta name="date" content="2015-12-29">
<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="Processor";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../io/gearpump/streaming/LifeTime$.html" title="class in io.gearpump.streaming"><span class="strong">PREV CLASS</span></a></li>
<li><a href="../../../io/gearpump/streaming/Processor.DefaultProcessor.html" title="class in io.gearpump.streaming"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?io/gearpump/streaming/Processor.html" target="_top">FRAMES</a></li>
<li><a href="Processor.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>
<div>
<ul class="subNavList">
<li>SUMMARY: </li>
<li><a href="#nested_class_summary">NESTED</a> | </li>
<li>FIELD | </li>
<li>CONSTR | </li>
<li><a href="#method_summary">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li>CONSTR | </li>
<li><a href="#method_detail">METHOD</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<p class="subTitle">io.gearpump.streaming</p>
<h2 title="Interface Processor" class="title">Interface Processor<T extends <a href="../../../io/gearpump/streaming/task/Task.html" title="class in io.gearpump.streaming.task">Task</a>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd>io.gearpump.util.ReferenceEqual</dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../io/gearpump/streaming/javaapi/Processor.html" title="class in io.gearpump.streaming.javaapi">Processor</a>, <a href="../../../io/gearpump/streaming/Processor.DefaultProcessor.html" title="class in io.gearpump.streaming">Processor.DefaultProcessor</a></dd>
</dl>
<hr>
<br>
<pre>public interface <strong>Processor<T extends <a href="../../../io/gearpump/streaming/task/Task.html" title="class in io.gearpump.streaming.task">Task</a>></strong>
extends io.gearpump.util.ReferenceEqual</pre>
<div class="block">Processor is the blueprint for tasks.
<p></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Interface and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../io/gearpump/streaming/Processor.DefaultProcessor.html" title="class in io.gearpump.streaming">Processor.DefaultProcessor</a><<a href="../../../io/gearpump/streaming/Processor.DefaultProcessor.html" title="type parameter in Processor.DefaultProcessor">T</a> extends <a href="../../../io/gearpump/streaming/task/Task.html" title="class in io.gearpump.streaming.task">Task</a>></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../io/gearpump/streaming/Processor.DefaultProcessor$.html" title="class in io.gearpump.streaming">Processor.DefaultProcessor$</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../io/gearpump/streaming/Processor.html#description()">description</a></strong>()</code>
<div class="block">Some description text for this processor.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../io/gearpump/streaming/Processor.html#parallelism()">parallelism</a></strong>()</code>
<div class="block">How many tasks you want to use for this processor.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Class<? extends <a href="../../../io/gearpump/streaming/task/Task.html" title="class in io.gearpump.streaming.task">Task</a>></code></td>
<td class="colLast"><code><strong><a href="../../../io/gearpump/streaming/Processor.html#taskClass()">taskClass</a></strong>()</code>
<div class="block">The task class, should be a subtype of Task.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>io.gearpump.cluster.UserConfig</code></td>
<td class="colLast"><code><strong><a href="../../../io/gearpump/streaming/Processor.html#taskConf()">taskConf</a></strong>()</code>
<div class="block">The custom <code>UserConfig</code>, it is used to initialize a task in runtime.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_io.gearpump.util.ReferenceEqual">
<!-- -->
</a>
<h3>Methods inherited from interface io.gearpump.util.ReferenceEqual</h3>
<code>equals</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="parallelism()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>parallelism</h4>
<pre>int parallelism()</pre>
<div class="block">How many tasks you want to use for this processor.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>(undocumented)</dd></dl>
</li>
</ul>
<a name="taskConf()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>taskConf</h4>
<pre>io.gearpump.cluster.UserConfig taskConf()</pre>
<div class="block">The custom <code>UserConfig</code>, it is used to initialize a task in runtime.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>(undocumented)</dd></dl>
</li>
</ul>
<a name="description()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>description</h4>
<pre>java.lang.String description()</pre>
<div class="block">Some description text for this processor.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>(undocumented)</dd></dl>
</li>
</ul>
<a name="taskClass()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>taskClass</h4>
<pre>java.lang.Class<? extends <a href="../../../io/gearpump/streaming/task/Task.html" title="class in io.gearpump.streaming.task">Task</a>> taskClass()</pre>
<div class="block">The task class, should be a subtype of Task.
<p>
Each runtime instance of this class is a task.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>(undocumented)</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../io/gearpump/streaming/LifeTime$.html" title="class in io.gearpump.streaming"><span class="strong">PREV CLASS</span></a></li>
<li><a href="../../../io/gearpump/streaming/Processor.DefaultProcessor.html" title="class in io.gearpump.streaming"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?io/gearpump/streaming/Processor.html" target="_top">FRAMES</a></li>
<li><a href="Processor.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>
<div>
<ul class="subNavList">
<li>SUMMARY: </li>
<li><a href="#nested_class_summary">NESTED</a> | </li>
<li>FIELD | </li>
<li>CONSTR | </li>
<li><a href="#method_summary">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li>CONSTR | </li>
<li><a href="#method_detail">METHOD</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"content_hash": "d90c8d1ebc643b3d000ef7a837ba44b7",
"timestamp": "",
"source": "github",
"line_count": 302,
"max_line_length": 459,
"avg_line_length": 37.354304635761586,
"alnum_prop": 0.6504742487368141,
"repo_name": "gearpump/gearpump.github.io",
"id": "4a7693bc2a8d5f9ff710e277d826e2ab58016e28",
"size": "11281",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "releases/0.7.1/api/java/io/gearpump/streaming/Processor.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "386903"
},
{
"name": "HTML",
"bytes": "236673589"
},
{
"name": "JavaScript",
"bytes": "2196377"
},
{
"name": "Shell",
"bytes": "213"
}
],
"symlink_target": ""
}
|
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :event_type
t.date :date
t.belongs_to :user
t.string :title
t.timestamps null: false
end
end
end
|
{
"content_hash": "92a791f6a0f01198f0de6b4f2bd19453",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 44,
"avg_line_length": 19.416666666666668,
"alnum_prop": 0.630901287553648,
"repo_name": "JLWolfe1990/blast",
"id": "6af18e423c5e5ae1891ddf2163e32a5a840aada7",
"size": "233",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20160203014420_create_events.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13864"
},
{
"name": "HTML",
"bytes": "8877"
},
{
"name": "JavaScript",
"bytes": "7939"
},
{
"name": "Ruby",
"bytes": "71571"
}
],
"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 org.jruyi.core.internal;
import java.util.HashMap;
import java.util.Map;
import org.jruyi.common.StrUtil;
import org.jruyi.core.INioService;
import org.jruyi.core.IUdpClientBuilder;
import org.jruyi.core.IUdpClientConfiguration;
import org.jruyi.io.IoConstants;
final class UdpClientBuilder implements IUdpClientBuilder {
private final Map<String, Object> m_properties = new HashMap<>(8);
@Override
public UdpClientBuilder serviceId(String serviceId) {
if (serviceId != null && !(serviceId = serviceId.trim()).isEmpty())
m_properties.put(IoConstants.SERVICE_ID, serviceId);
return this;
}
@Override
public UdpClientBuilder host(String host) {
if (host == null || (host = host.trim()).isEmpty())
throw new IllegalArgumentException("host cannot be null or empty");
m_properties.put("addr", host);
return this;
}
@Override
public UdpClientBuilder port(int port) {
if (port < 0 || port > 65535)
throw new IllegalArgumentException(StrUtil.join("Illegal port: 0 <= ", port, " <= 65535"));
m_properties.put("port", port);
return this;
}
@Override
public <I, O> INioService<I, O, ? extends IUdpClientConfiguration> build() {
final Map<String, Object> properties = m_properties;
if (!properties.containsKey("addr"))
throw new RuntimeException("Missing host");
if (!properties.containsKey("port"))
throw new RuntimeException("Missing port");
return new UdpClientWrapper<>(properties);
}
}
|
{
"content_hash": "2685a6803b8a5855d6dcd9958e5b69a0",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 94,
"avg_line_length": 32.41935483870968,
"alnum_prop": 0.7313432835820896,
"repo_name": "jruyi/jruyi",
"id": "bbc67cabe885432c724cf8b58aa2443df1e85ae8",
"size": "2010",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "core/src/main/java/org/jruyi/core/internal/UdpClientBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3222"
},
{
"name": "Groovy",
"bytes": "22993"
},
{
"name": "Java",
"bytes": "834266"
},
{
"name": "Shell",
"bytes": "2730"
}
],
"symlink_target": ""
}
|
using std::cout;
using std::endl;
using std::multimap;
using std::vector;
using std::string;
void AddChild(multimap<string, string> &families, const string &family, const string &child) {
families.insert({family, child});
}
int main()
{
multimap<string, string> families;
AddChild(families, "A", "aa");
AddChild(families, "A", "aaa");
AddChild(families, "A", "aaaa");
AddChild(families, "B", "bb");
AddChild(families, "B", "bbbbb");
AddChild(families, "C", "cccc");
for(const auto &f : families)
cout << f.first << " " << f.second << endl;;
return 0;
}
|
{
"content_hash": "c069f566e55a494cad8dec6b02ec4566",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 94,
"avg_line_length": 25.217391304347824,
"alnum_prop": 0.6413793103448275,
"repo_name": "bashell/Cpp-Primer",
"id": "38546a351d831b9daf81e5f92bfe09e8b6ba0444",
"size": "652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ch11/ex11_23.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "78"
},
{
"name": "C++",
"bytes": "183807"
}
],
"symlink_target": ""
}
|
/*$ preserve start $*/
/* ============================================================================================ */
/* FMOD Ex - Main C/C++ header file. Copyright (c), Firelight Technologies Pty, Ltd. 2004-2011. */
/* */
/* This header is the base header for all other FMOD headers. If you are programming in C */
/* use this exclusively, or if you are programming C++ use this in conjunction with FMOD.HPP */
/* */
/* ============================================================================================ */
#ifndef _FMOD_H
#define _FMOD_H
/*
FMOD version number. Check this against FMOD::System::getVersion.
0xaaaabbcc -> aaaa = major version number. bb = minor version number. cc = development version number.
*/
#define FMOD_VERSION 0x00044403
/*
Compiler specific settings.
*/
#if defined(__CYGWIN32__)
#define F_CDECL __cdecl
#define F_STDCALL __stdcall
#define F_DECLSPEC __declspec
#define F_DLLEXPORT ( dllexport )
#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64)
#define F_CDECL _cdecl
#define F_STDCALL _stdcall
#define F_DECLSPEC __declspec
#define F_DLLEXPORT ( dllexport )
#elif defined(__MACH__) || defined(__ANDROID__) || defined(__linux__) || defined(__QNX__)
#define F_CDECL
#define F_STDCALL
#define F_DECLSPEC
#define F_DLLEXPORT __attribute__ ((visibility("default")))
#else
#define F_CDECL
#define F_STDCALL
#define F_DECLSPEC
#define F_DLLEXPORT
#endif
#ifdef DLL_EXPORTS
#if defined(__MACH__) || defined(__ANDROID__) || defined(__linux__) || defined(__QNX__)
#define F_API __attribute__ ((visibility("default")))
#else
#define F_API __declspec(dllexport) F_STDCALL
#endif
#else
#define F_API F_STDCALL
#endif
#define F_CALLBACK F_STDCALL
/*
FMOD types.
*/
typedef int FMOD_BOOL;
typedef struct FMOD_SYSTEM FMOD_SYSTEM;
typedef struct FMOD_SOUND FMOD_SOUND;
typedef struct FMOD_CHANNEL FMOD_CHANNEL;
typedef struct FMOD_CHANNELGROUP FMOD_CHANNELGROUP;
typedef struct FMOD_SOUNDGROUP FMOD_SOUNDGROUP;
typedef struct FMOD_REVERB FMOD_REVERB;
typedef struct FMOD_DSP FMOD_DSP;
typedef struct FMOD_DSPCONNECTION FMOD_DSPCONNECTION;
typedef struct FMOD_POLYGON FMOD_POLYGON;
typedef struct FMOD_GEOMETRY FMOD_GEOMETRY;
typedef struct FMOD_SYNCPOINT FMOD_SYNCPOINT;
typedef unsigned int FMOD_MODE;
typedef unsigned int FMOD_TIMEUNIT;
typedef unsigned int FMOD_INITFLAGS;
typedef unsigned int FMOD_CAPS;
typedef unsigned int FMOD_DEBUGLEVEL;
typedef unsigned int FMOD_MEMORY_TYPE;
/*$ fmod result start $*/
/*
[ENUM]
[
[DESCRIPTION]
error codes. Returned from every function.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
]
*/
typedef enum
{
FMOD_OK, /* No errors. */
FMOD_ERR_ALREADYLOCKED, /* Tried to call lock a second time before unlock was called. */
FMOD_ERR_BADCOMMAND, /* Tried to call a function on a data type that does not allow this type of functionality (ie calling Sound::lock on a streaming sound). */
FMOD_ERR_CDDA_DRIVERS, /* Neither NTSCSI nor ASPI could be initialised. */
FMOD_ERR_CDDA_INIT, /* An error occurred while initialising the CDDA subsystem. */
FMOD_ERR_CDDA_INVALID_DEVICE, /* Couldn't find the specified device. */
FMOD_ERR_CDDA_NOAUDIO, /* No audio tracks on the specified disc. */
FMOD_ERR_CDDA_NODEVICES, /* No CD/DVD devices were found. */
FMOD_ERR_CDDA_NODISC, /* No disc present in the specified drive. */
FMOD_ERR_CDDA_READ, /* A CDDA read error occurred. */
FMOD_ERR_CHANNEL_ALLOC, /* Error trying to allocate a channel. */
FMOD_ERR_CHANNEL_STOLEN, /* The specified channel has been reused to play another sound. */
FMOD_ERR_COM, /* A Win32 COM related error occured. COM failed to initialize or a QueryInterface failed meaning a Windows codec or driver was not installed properly. */
FMOD_ERR_DMA, /* DMA Failure. See debug output for more information. */
FMOD_ERR_DSP_CONNECTION, /* DSP connection error. Connection possibly caused a cyclic dependancy. Or tried to connect a tree too many units deep (more than 128). */
FMOD_ERR_DSP_FORMAT, /* DSP Format error. A DSP unit may have attempted to connect to this network with the wrong format. */
FMOD_ERR_DSP_NOTFOUND, /* DSP connection error. Couldn't find the DSP unit specified. */
FMOD_ERR_DSP_RUNNING, /* DSP error. Cannot perform this operation while the network is in the middle of running. This will most likely happen if a connection or disconnection is attempted in a DSP callback. */
FMOD_ERR_DSP_TOOMANYCONNECTIONS,/* DSP connection error. The unit being connected to or disconnected should only have 1 input or output. */
FMOD_ERR_FILE_BAD, /* Error loading file. */
FMOD_ERR_FILE_COULDNOTSEEK, /* Couldn't perform seek operation. This is a limitation of the medium (ie netstreams) or the file format. */
FMOD_ERR_FILE_DISKEJECTED, /* Media was ejected while reading. */
FMOD_ERR_FILE_EOF, /* End of file unexpectedly reached while trying to read essential data (truncated data?). */
FMOD_ERR_FILE_NOTFOUND, /* File not found. */
FMOD_ERR_FILE_UNWANTED, /* Unwanted file access occured. */
FMOD_ERR_FORMAT, /* Unsupported file or audio format. */
FMOD_ERR_HTTP, /* A HTTP error occurred. This is a catch-all for HTTP errors not listed elsewhere. */
FMOD_ERR_HTTP_ACCESS, /* The specified resource requires authentication or is forbidden. */
FMOD_ERR_HTTP_PROXY_AUTH, /* Proxy authentication is required to access the specified resource. */
FMOD_ERR_HTTP_SERVER_ERROR, /* A HTTP server error occurred. */
FMOD_ERR_HTTP_TIMEOUT, /* The HTTP request timed out. */
FMOD_ERR_INITIALIZATION, /* FMOD was not initialized correctly to support this function. */
FMOD_ERR_INITIALIZED, /* Cannot call this command after System::init. */
FMOD_ERR_INTERNAL, /* An error occured that wasn't supposed to. Contact support. */
FMOD_ERR_INVALID_ADDRESS, /* On Xbox 360, this memory address passed to FMOD must be physical, (ie allocated with XPhysicalAlloc.) */
FMOD_ERR_INVALID_FLOAT, /* Value passed in was a NaN, Inf or denormalized float. */
FMOD_ERR_INVALID_HANDLE, /* An invalid object handle was used. */
FMOD_ERR_INVALID_PARAM, /* An invalid parameter was passed to this function. */
FMOD_ERR_INVALID_POSITION, /* An invalid seek position was passed to this function. */
FMOD_ERR_INVALID_SPEAKER, /* An invalid speaker was passed to this function based on the current speaker mode. */
FMOD_ERR_INVALID_SYNCPOINT, /* The syncpoint did not come from this sound handle. */
FMOD_ERR_INVALID_VECTOR, /* The vectors passed in are not unit length, or perpendicular. */
FMOD_ERR_MAXAUDIBLE, /* Reached maximum audible playback count for this sound's soundgroup. */
FMOD_ERR_MEMORY, /* Not enough memory or resources. */
FMOD_ERR_MEMORY_CANTPOINT, /* Can't use FMOD_OPENMEMORY_POINT on non PCM source data, or non mp3/xma/adpcm data if FMOD_CREATECOMPRESSEDSAMPLE was used. */
FMOD_ERR_MEMORY_SRAM, /* Not enough memory or resources on console sound ram. */
FMOD_ERR_NEEDS2D, /* Tried to call a command on a 3d sound when the command was meant for 2d sound. */
FMOD_ERR_NEEDS3D, /* Tried to call a command on a 2d sound when the command was meant for 3d sound. */
FMOD_ERR_NEEDSHARDWARE, /* Tried to use a feature that requires hardware support. (ie trying to play a GCADPCM compressed sound in software on Wii). */
FMOD_ERR_NEEDSSOFTWARE, /* Tried to use a feature that requires the software engine. Software engine has either been turned off, or command was executed on a hardware channel which does not support this feature. */
FMOD_ERR_NET_CONNECT, /* Couldn't connect to the specified host. */
FMOD_ERR_NET_SOCKET_ERROR, /* A socket error occurred. This is a catch-all for socket-related errors not listed elsewhere. */
FMOD_ERR_NET_URL, /* The specified URL couldn't be resolved. */
FMOD_ERR_NET_WOULD_BLOCK, /* Operation on a non-blocking socket could not complete immediately. */
FMOD_ERR_NOTREADY, /* Operation could not be performed because specified sound/DSP connection is not ready. */
FMOD_ERR_OUTPUT_ALLOCATED, /* Error initializing output device, but more specifically, the output device is already in use and cannot be reused. */
FMOD_ERR_OUTPUT_CREATEBUFFER, /* Error creating hardware sound buffer. */
FMOD_ERR_OUTPUT_DRIVERCALL, /* A call to a standard soundcard driver failed, which could possibly mean a bug in the driver or resources were missing or exhausted. */
FMOD_ERR_OUTPUT_ENUMERATION, /* Error enumerating the available driver list. List may be inconsistent due to a recent device addition or removal. */
FMOD_ERR_OUTPUT_FORMAT, /* Soundcard does not support the minimum features needed for this soundsystem (16bit stereo output). */
FMOD_ERR_OUTPUT_INIT, /* Error initializing output device. */
FMOD_ERR_OUTPUT_NOHARDWARE, /* FMOD_HARDWARE was specified but the sound card does not have the resources necessary to play it. */
FMOD_ERR_OUTPUT_NOSOFTWARE, /* Attempted to create a software sound but no software channels were specified in System::init. */
FMOD_ERR_PAN, /* Panning only works with mono or stereo sound sources. */
FMOD_ERR_PLUGIN, /* An unspecified error has been returned from a 3rd party plugin. */
FMOD_ERR_PLUGIN_INSTANCES, /* The number of allowed instances of a plugin has been exceeded. */
FMOD_ERR_PLUGIN_MISSING, /* A requested output, dsp unit type or codec was not available. */
FMOD_ERR_PLUGIN_RESOURCE, /* A resource that the plugin requires cannot be found. (ie the DLS file for MIDI playback) */
FMOD_ERR_PRELOADED, /* The specified sound is still in use by the event system, call EventSystem::unloadFSB before trying to release it. */
FMOD_ERR_PROGRAMMERSOUND, /* The specified sound is still in use by the event system, wait for the event which is using it finish with it. */
FMOD_ERR_RECORD, /* An error occured trying to initialize the recording device. */
FMOD_ERR_REVERB_INSTANCE, /* Specified instance in FMOD_REVERB_PROPERTIES couldn't be set. Most likely because it is an invalid instance number or the reverb doesnt exist. */
FMOD_ERR_SUBSOUND_ALLOCATED, /* This subsound is already being used by another sound, you cannot have more than one parent to a sound. Null out the other parent's entry first. */
FMOD_ERR_SUBSOUND_CANTMOVE, /* Shared subsounds cannot be replaced or moved from their parent stream, such as when the parent stream is an FSB file. */
FMOD_ERR_SUBSOUND_MODE, /* The subsound's mode bits do not match with the parent sound's mode bits. See documentation for function that it was called with. */
FMOD_ERR_SUBSOUNDS, /* The error occured because the sound referenced contains subsounds when it shouldn't have, or it doesn't contain subsounds when it should have. The operation may also not be able to be performed on a parent sound, or a parent sound was played without setting up a sentence first. */
FMOD_ERR_TAGNOTFOUND, /* The specified tag could not be found or there are no tags. */
FMOD_ERR_TOOMANYCHANNELS, /* The sound created exceeds the allowable input channel count. This can be increased using the maxinputchannels parameter in System::setSoftwareFormat. */
FMOD_ERR_UNIMPLEMENTED, /* Something in FMOD hasn't been implemented when it should be! contact support! */
FMOD_ERR_UNINITIALIZED, /* This command failed because System::init or System::setDriver was not called. */
FMOD_ERR_UNSUPPORTED, /* A command issued was not supported by this object. Possibly a plugin without certain callbacks specified. */
FMOD_ERR_UPDATE, /* An error caused by System::update occured. */
FMOD_ERR_VERSION, /* The version number of this file format is not supported. */
FMOD_ERR_EVENT_FAILED, /* An Event failed to be retrieved, most likely due to 'just fail' being specified as the max playbacks behavior. */
FMOD_ERR_EVENT_INFOONLY, /* Can't execute this command on an EVENT_INFOONLY event. */
FMOD_ERR_EVENT_INTERNAL, /* An error occured that wasn't supposed to. See debug log for reason. */
FMOD_ERR_EVENT_MAXSTREAMS, /* Event failed because 'Max streams' was hit when FMOD_EVENT_INIT_FAIL_ON_MAXSTREAMS was specified. */
FMOD_ERR_EVENT_MISMATCH, /* FSB mismatches the FEV it was compiled with, the stream/sample mode it was meant to be created with was different, or the FEV was built for a different platform. */
FMOD_ERR_EVENT_NAMECONFLICT, /* A category with the same name already exists. */
FMOD_ERR_EVENT_NOTFOUND, /* The requested event, event group, event category or event property could not be found. */
FMOD_ERR_EVENT_NEEDSSIMPLE, /* Tried to call a function on a complex event that's only supported by simple events. */
FMOD_ERR_EVENT_GUIDCONFLICT, /* An event with the same GUID already exists. */
FMOD_ERR_EVENT_ALREADY_LOADED, /* The specified project or bank has already been loaded. Having multiple copies of the same project loaded simultaneously is forbidden. */
FMOD_ERR_MUSIC_UNINITIALIZED, /* Music system is not initialized probably because no music data is loaded. */
FMOD_ERR_MUSIC_NOTFOUND, /* The requested music entity could not be found. */
FMOD_ERR_MUSIC_NOCALLBACK, /* The music callback is required, but it has not been set. */
FMOD_RESULT_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_RESULT;
/*$ fmod result end $*/
/*
[STRUCTURE]
[
[DESCRIPTION]
Structure describing a point in 3D space.
[REMARKS]
FMOD uses a left handed co-ordinate system by default.<br>
To use a right handed co-ordinate system specify FMOD_INIT_3D_RIGHTHANDED from FMOD_INITFLAGS in System::init.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::set3DListenerAttributes
System::get3DListenerAttributes
Channel::set3DAttributes
Channel::get3DAttributes
Channel::set3DCustomRolloff
Channel::get3DCustomRolloff
Sound::set3DCustomRolloff
Sound::get3DCustomRolloff
Geometry::addPolygon
Geometry::setPolygonVertex
Geometry::getPolygonVertex
Geometry::setRotation
Geometry::getRotation
Geometry::setPosition
Geometry::getPosition
Geometry::setScale
Geometry::getScale
FMOD_INITFLAGS
]
*/
typedef struct
{
float x; /* X co-ordinate in 3D space. */
float y; /* Y co-ordinate in 3D space. */
float z; /* Z co-ordinate in 3D space. */
} FMOD_VECTOR;
/*
[STRUCTURE]
[
[DESCRIPTION]
Structure describing a globally unique identifier.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::getDriverInfo
]
*/
typedef struct
{
unsigned int Data1; /* Specifies the first 8 hexadecimal digits of the GUID */
unsigned short Data2; /* Specifies the first group of 4 hexadecimal digits. */
unsigned short Data3; /* Specifies the second group of 4 hexadecimal digits. */
unsigned char Data4[8]; /* Array of 8 bytes. The first 2 bytes contain the third group of 4 hexadecimal digits. The remaining 6 bytes contain the final 12 hexadecimal digits. */
} FMOD_GUID;
/*
[STRUCTURE]
[
[DESCRIPTION]
Structure that is passed into FMOD_FILE_ASYNCREADCALLBACK. Use the information in this structure to perform
[REMARKS]
Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
Members marked with [w] mean the variable can be written to. The user can set the value.<br>
<br>
Instructions: write to 'buffer', and 'bytesread' <b>BEFORE</b> setting 'result'.<br>
As soon as result is set, FMOD will asynchronously continue internally using the data provided in this structure.<br>
<br>
Set 'result' to the result expected from a normal file read callback.<br>
If the read was successful, set it to FMOD_OK.<br>
If it read some data but hit the end of the file, set it to FMOD_ERR_FILE_EOF.<br>
If a bad error occurred, return FMOD_ERR_FILE_BAD<br>
If a disk was ejected, return FMOD_ERR_FILE_DISKEJECTED.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
FMOD_FILE_ASYNCREADCALLBACK
FMOD_FILE_ASYNCCANCELCALLBACK
]
*/
typedef struct
{
void *handle; /* [r] The file handle that was filled out in the open callback. */
unsigned int offset; /* [r] Seek position, make sure you read from this file offset. */
unsigned int sizebytes; /* [r] how many bytes requested for read. */
int priority; /* [r] 0 = low importance. 100 = extremely important (ie 'must read now or stuttering may occur') */
void *buffer; /* [w] Buffer to read file data into. */
unsigned int bytesread; /* [w] Fill this in before setting result code to tell FMOD how many bytes were read. */
FMOD_RESULT result; /* [r/w] Result code, FMOD_OK tells the system it is ready to consume the data. Set this last! Default value = FMOD_ERR_NOTREADY. */
void *userdata; /* [r] User data pointer. */
} FMOD_ASYNCREADINFO;
/*
[ENUM]
[
[DESCRIPTION]
These output types are used with System::setOutput / System::getOutput, to choose which output method to use.
[REMARKS]
To pass information to the driver when initializing fmod use the extradriverdata parameter in System::init for the following reasons.<br>
<li>FMOD_OUTPUTTYPE_WAVWRITER - extradriverdata is a pointer to a char * filename that the wav writer will output to.
<li>FMOD_OUTPUTTYPE_WAVWRITER_NRT - extradriverdata is a pointer to a char * filename that the wav writer will output to.
<li>FMOD_OUTPUTTYPE_DSOUND - extradriverdata is a pointer to a HWND so that FMOD can set the focus on the audio for a particular window.
<li>FMOD_OUTPUTTYPE_PS3 - extradriverdata is a pointer to a FMOD_PS3_EXTRADRIVERDATA struct. This can be found in fmodps3.h.
<li>FMOD_OUTPUTTYPE_GC - extradriverdata is a pointer to a FMOD_GC_INFO struct. This can be found in fmodgc.h.
<li>FMOD_OUTPUTTYPE_WII - extradriverdata is a pointer to a FMOD_WII_INFO struct. This can be found in fmodwii.h.
<li>FMOD_OUTPUTTYPE_ALSA - extradriverdata is a pointer to a FMOD_LINUX_EXTRADRIVERDATA struct. This can be found in fmodlinux.h.<br>
<br>
Currently these are the only FMOD drivers that take extra information. Other unknown plugins may have different requirements.
<br><br>
Note! If FMOD_OUTPUTTYPE_WAVWRITER_NRT or FMOD_OUTPUTTYPE_NOSOUND_NRT are used, and if the System::update function is being called
very quickly (ie for a non realtime decode) it may be being called too quickly for the FMOD streamer thread to respond to.
The result will be a skipping/stuttering output in the captured audio.<br>
<br>
To remedy this, disable the FMOD Ex streamer thread, and use FMOD_INIT_STREAM_FROM_UPDATE to avoid skipping in the output stream,
as it will lock the mixer and the streamer together in the same thread.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::setOutput
System::getOutput
System::setSoftwareFormat
System::getSoftwareFormat
System::init
System::update
FMOD_INITFLAGS
]
*/
typedef enum
{
FMOD_OUTPUTTYPE_AUTODETECT, /* Picks the best output mode for the platform. This is the default. */
FMOD_OUTPUTTYPE_UNKNOWN, /* All - 3rd party plugin, unknown. This is for use with System::getOutput only. */
FMOD_OUTPUTTYPE_NOSOUND, /* All - All calls in this mode succeed but make no sound. */
FMOD_OUTPUTTYPE_WAVWRITER, /* All - Writes output to fmodoutput.wav by default. Use the 'extradriverdata' parameter in System::init, by simply passing the filename as a string, to set the wav filename. */
FMOD_OUTPUTTYPE_NOSOUND_NRT, /* All - Non-realtime version of FMOD_OUTPUTTYPE_NOSOUND. User can drive mixer with System::update at whatever rate they want. */
FMOD_OUTPUTTYPE_WAVWRITER_NRT, /* All - Non-realtime version of FMOD_OUTPUTTYPE_WAVWRITER. User can drive mixer with System::update at whatever rate they want. */
FMOD_OUTPUTTYPE_DSOUND, /* Win32/Win64 - DirectSound output. (Default on Windows XP and below) */
FMOD_OUTPUTTYPE_WINMM, /* Win32/Win64 - Windows Multimedia output. */
FMOD_OUTPUTTYPE_WASAPI, /* Win32 - Windows Audio Session API. (Default on Windows Vista and above) */
FMOD_OUTPUTTYPE_ASIO, /* Win32 - Low latency ASIO 2.0 driver. */
FMOD_OUTPUTTYPE_OSS, /* Linux/Linux64 - Open Sound System output. (Default on Linux, third preference) */
FMOD_OUTPUTTYPE_ALSA, /* Linux/Linux64 - Advanced Linux Sound Architecture output. (Default on Linux, second preference if available) */
FMOD_OUTPUTTYPE_ESD, /* Linux/Linux64 - Enlightment Sound Daemon output. */
FMOD_OUTPUTTYPE_PULSEAUDIO, /* Linux/Linux64 - PulseAudio output. (Default on Linux, first preference if available) */
FMOD_OUTPUTTYPE_COREAUDIO, /* Mac - Macintosh CoreAudio output. (Default on Mac) */
FMOD_OUTPUTTYPE_XBOX360, /* Xbox 360 - Native Xbox360 output. (Default on Xbox 360) */
FMOD_OUTPUTTYPE_PSP, /* PSP - Native PSP output. (Default on PSP) */
FMOD_OUTPUTTYPE_PS3, /* PS3 - Native PS3 output. (Default on PS3) */
FMOD_OUTPUTTYPE_NGP, /* NGP - Native NGP output. (Default on NGP) */
FMOD_OUTPUTTYPE_WII, /* Wii - Native Wii output. (Default on Wii) */
FMOD_OUTPUTTYPE_3DS, /* 3DS - Native 3DS output (Default on 3DS) */
FMOD_OUTPUTTYPE_AUDIOTRACK, /* Android - Java Audio Track output. (Default on Android 2.2 and below) */
FMOD_OUTPUTTYPE_OPENSL, /* Android - OpenSL ES output. (Default on Android 2.3 and above) */
FMOD_OUTPUTTYPE_NACL, /* Native Client - Native Client output. (Default on Native Client) */
FMOD_OUTPUTTYPE_WIIU, /* Wii U - Native Wii U output. (Default on Wii U) */
FMOD_OUTPUTTYPE_ASOUND, /* BlackBerry - Native BlackBerry asound output. (Default on BlackBerry) */
FMOD_OUTPUTTYPE_MAX, /* Maximum number of output types supported. */
FMOD_OUTPUTTYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_OUTPUTTYPE;
/*
[DEFINE]
[
[NAME]
FMOD_CAPS
[DESCRIPTION]
Bit fields to use with System::getDriverCaps to determine the capabilities of a card / output device.
[REMARKS]
It is important to check FMOD_CAPS_HARDWARE_EMULATED on windows machines, to then adjust System::setDSPBufferSize to (1024, 10) to compensate for the higher latency.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::getDriverCaps
System::setDSPBufferSize
]
*/
#define FMOD_CAPS_NONE 0x00000000 /* Device has no special capabilities. */
#define FMOD_CAPS_HARDWARE 0x00000001 /* Device supports hardware mixing. */
#define FMOD_CAPS_HARDWARE_EMULATED 0x00000002 /* User has device set to 'Hardware acceleration = off' in control panel, and now extra 200ms latency is incurred. */
#define FMOD_CAPS_OUTPUT_MULTICHANNEL 0x00000004 /* Device can do multichannel output, ie greater than 2 channels. */
#define FMOD_CAPS_OUTPUT_FORMAT_PCM8 0x00000008 /* Device can output to 8bit integer PCM. */
#define FMOD_CAPS_OUTPUT_FORMAT_PCM16 0x00000010 /* Device can output to 16bit integer PCM. */
#define FMOD_CAPS_OUTPUT_FORMAT_PCM24 0x00000020 /* Device can output to 24bit integer PCM. */
#define FMOD_CAPS_OUTPUT_FORMAT_PCM32 0x00000040 /* Device can output to 32bit integer PCM. */
#define FMOD_CAPS_OUTPUT_FORMAT_PCMFLOAT 0x00000080 /* Device can output to 32bit floating point PCM. */
#define FMOD_CAPS_REVERB_LIMITED 0x00002000 /* Device supports some form of limited hardware reverb, maybe parameterless and only selectable by environment. */
#define FMOD_CAPS_LOOPBACK 0x00004000 /* Device is a loopback recording device */
/* [DEFINE_END] */
/*
[DEFINE]
[
[NAME]
FMOD_DEBUGLEVEL
[DESCRIPTION]
Bit fields to use with FMOD::Debug_SetLevel / FMOD::Debug_GetLevel to control the level of tty debug output with logging versions of FMOD (fmodL).
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Debug_SetLevel
Debug_GetLevel
]
*/
#define FMOD_DEBUG_LEVEL_NONE 0x00000000
#define FMOD_DEBUG_LEVEL_LOG 0x00000001 /* Will display generic logging messages. */
#define FMOD_DEBUG_LEVEL_ERROR 0x00000002 /* Will display errors. */
#define FMOD_DEBUG_LEVEL_WARNING 0x00000004 /* Will display warnings that are not fatal. */
#define FMOD_DEBUG_LEVEL_HINT 0x00000008 /* Will hint to you if there is something possibly better you could be doing. */
#define FMOD_DEBUG_LEVEL_ALL 0x000000FF
#define FMOD_DEBUG_TYPE_MEMORY 0x00000100 /* Show FMOD memory related logging messages. */
#define FMOD_DEBUG_TYPE_THREAD 0x00000200 /* Show FMOD thread related logging messages. */
#define FMOD_DEBUG_TYPE_FILE 0x00000400 /* Show FMOD file system related logging messages. */
#define FMOD_DEBUG_TYPE_NET 0x00000800 /* Show FMOD network related logging messages. */
#define FMOD_DEBUG_TYPE_EVENT 0x00001000 /* Show FMOD Event related logging messages. */
#define FMOD_DEBUG_TYPE_ALL 0x0000FFFF
#define FMOD_DEBUG_DISPLAY_TIMESTAMPS 0x01000000 /* Display the timestamp of the log entry in milliseconds. */
#define FMOD_DEBUG_DISPLAY_LINENUMBERS 0x02000000 /* Display the FMOD Ex source code line numbers, for debugging purposes. */
#define FMOD_DEBUG_DISPLAY_COMPRESS 0x04000000 /* If a message is repeated more than 5 times it will stop displaying it and instead display the number of times the message was logged. */
#define FMOD_DEBUG_DISPLAY_THREAD 0x08000000 /* Display the thread ID of the calling function that caused this log entry to appear. */
#define FMOD_DEBUG_DISPLAY_ALL 0x0F000000
#define FMOD_DEBUG_ALL 0xFFFFFFFF
/* [DEFINE_END] */
/*
[DEFINE]
[
[NAME]
FMOD_MEMORY_TYPE
[DESCRIPTION]
Bit fields for memory allocation type being passed into FMOD memory callbacks.
[REMARKS]
Remember this is a bitfield. You may get more than 1 bit set (ie physical + persistent) so do not simply switch on the types! You must check each bit individually or clear out the bits that you do not want within the callback.<br>
Bits can be excluded if you want during Memory_Initialize so that you never get them.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
FMOD_MEMORY_ALLOCCALLBACK
FMOD_MEMORY_REALLOCCALLBACK
FMOD_MEMORY_FREECALLBACK
Memory_Initialize
]
*/
#define FMOD_MEMORY_NORMAL 0x00000000 /* Standard memory. */
#define FMOD_MEMORY_STREAM_FILE 0x00000001 /* Stream file buffer, size controllable with System::setStreamBufferSize. */
#define FMOD_MEMORY_STREAM_DECODE 0x00000002 /* Stream decode buffer, size controllable with FMOD_CREATESOUNDEXINFO::decodebuffersize. */
#define FMOD_MEMORY_SAMPLEDATA 0x00000004 /* Sample data buffer. Raw audio data, usually PCM/MPEG/ADPCM/XMA data. */
#define FMOD_MEMORY_DSP_OUTPUTBUFFER 0x00000008 /* DSP memory block allocated when more than 1 output exists on a DSP node. */
#define FMOD_MEMORY_XBOX360_PHYSICAL 0x00100000 /* Requires XPhysicalAlloc / XPhysicalFree. */
#define FMOD_MEMORY_PERSISTENT 0x00200000 /* Persistent memory. Memory will be freed when System::release is called. */
#define FMOD_MEMORY_SECONDARY 0x00400000 /* Secondary memory. Allocation should be in secondary memory. For example RSX on the PS3. */
#define FMOD_MEMORY_ALL 0xFFFFFFFF
/* [DEFINE_END] */
/*
[ENUM]
[
[DESCRIPTION]
These are speaker types defined for use with the System::setSpeakerMode or System::getSpeakerMode command.
[REMARKS]
These are important notes on speaker modes in regards to sounds created with FMOD_SOFTWARE.<br>
Note below the phrase 'sound channels' is used. These are the subchannels inside a sound, they are not related and
have nothing to do with the FMOD class "Channel".<br>
For example a mono sound has 1 sound channel, a stereo sound has 2 sound channels, and an AC3 or 6 channel wav file have 6 "sound channels".<br>
<br>
FMOD_SPEAKERMODE_RAW<br>
---------------------<br>
This mode is for output devices that are not specifically mono/stereo/quad/surround/5.1 or 7.1, but are multichannel.<br>
Use System::setSoftwareFormat to specify the number of speakers you want to address, otherwise it will default to 2 (stereo).<br>
Sound channels map to speakers sequentially, so a mono sound maps to output speaker 0, stereo sound maps to output speaker 0 & 1.<br>
The user assumes knowledge of the speaker order. FMOD_SPEAKER enumerations may not apply, so raw channel indices should be used.<br>
Multichannel sounds map input channels to output channels 1:1. <br>
Channel::setPan and Channel::setSpeakerMix do not work.<br>
Speaker levels must be manually set with Channel::setSpeakerLevels.<br>
<br>
FMOD_SPEAKERMODE_MONO<br>
---------------------<br>
This mode is for a 1 speaker arrangement.<br>
Panning does not work in this speaker mode.<br>
Mono, stereo and multichannel sounds have each sound channel played on the one speaker unity.<br>
Mix behavior for multichannel sounds can be set with Channel::setSpeakerLevels.<br>
Channel::setSpeakerMix does not work.<br>
<br>
FMOD_SPEAKERMODE_STEREO<br>
-----------------------<br>
This mode is for 2 speaker arrangements that have a left and right speaker.<br>
<li>Mono sounds default to an even distribution between left and right. They can be panned with Channel::setPan.<br>
<li>Stereo sounds default to the middle, or full left in the left speaker and full right in the right speaker.
<li>They can be cross faded with Channel::setPan.<br>
<li>Multichannel sounds have each sound channel played on each speaker at unity.<br>
<li>Mix behavior for multichannel sounds can be set with Channel::setSpeakerLevels.<br>
<li>Channel::setSpeakerMix works but only front left and right parameters are used, the rest are ignored.<br>
<br>
FMOD_SPEAKERMODE_QUAD<br>
------------------------<br>
This mode is for 4 speaker arrangements that have a front left, front right, rear left and a rear right speaker.<br>
<li>Mono sounds default to an even distribution between front left and front right. They can be panned with Channel::setPan.<br>
<li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right.<br>
<li>They can be cross faded with Channel::setPan.<br>
<li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input.<br>
<li>Mix behavior for multichannel sounds can be set with Channel::setSpeakerLevels.<br>
<li>Channel::setSpeakerMix works but side left, side right, center and lfe are ignored.<br>
<br>
FMOD_SPEAKERMODE_SURROUND<br>
------------------------<br>
This mode is for 5 speaker arrangements that have a left/right/center/rear left/rear right.<br>
<li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br>
<li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right.
<li>They can be cross faded with Channel::setPan.<br>
<li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input.
<li>Mix behavior for multichannel sounds can be set with Channel::setSpeakerLevels.<br>
<li>Channel::setSpeakerMix works but side left / side right are ignored.<br>
<br>
FMOD_SPEAKERMODE_5POINT1<br>
------------------------<br>
This mode is for 5.1 speaker arrangements that have a left/right/center/rear left/rear right and a subwoofer speaker.<br>
<li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br>
<li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right.
<li>They can be cross faded with Channel::setPan.<br>
<li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input.
<li>Mix behavior for multichannel sounds can be set with Channel::setSpeakerLevels.<br>
<li>Channel::setSpeakerMix works but side left / side right are ignored.<br>
<br>
FMOD_SPEAKERMODE_7POINT1<br>
------------------------<br>
This mode is for 7.1 speaker arrangements that have a left/right/center/rear left/rear right/side left/side right
and a subwoofer speaker.<br>
<li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br>
<li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right.
<li>They can be cross faded with Channel::setPan.<br>
<li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input.
<li>Mix behavior for multichannel sounds can be set with Channel::setSpeakerLevels.<br>
<li>Channel::setSpeakerMix works and every parameter is used to set the balance of a sound in any speaker.<br>
<br>
FMOD_SPEAKERMODE_SRS5_1_MATRIX<br>
------------------------------------------------------<br>
This mode is for mono, stereo, 5.1 and 6.1 speaker arrangements, as it is backwards and forwards compatible with
stereo, but to get a surround effect a SRS 5.1, Prologic or Prologic 2 hardware decoder / amplifier is needed or
a compatible SRS equipped device (e.g., laptop, TV, etc.) or accessory (e.g., headphone).<br>
Pan behavior is the same as FMOD_SPEAKERMODE_5POINT1.<br>
<br>
If this function is called the numoutputchannels setting in System::setSoftwareFormat is overwritten.<br>
<br>
Output rate must be 44100, 48000 or 96000 for this to work otherwise FMOD_ERR_OUTPUT_INIT will be returned.<br>
FMOD_SPEAKERMODE_MYEARS<br>
------------------------------------------------------<br>
This mode is for headphones. This will attempt to load a MyEars profile (see myears.net.au) and use it to generate
surround sound on headphones using a personalized HRTF algorithm, for realistic 3d sound.<br>
Pan behavior is the same as FMOD_SPEAKERMODE_7POINT1.<br>
MyEars speaker mode will automatically be set if the speakermode is FMOD_SPEAKERMODE_STEREO and the MyEars profile exists.<br>
If this mode is set explicitly, FMOD_INIT_DISABLE_MYEARS_AUTODETECT has no effect.<br>
If this mode is set explicitly and the MyEars profile does not exist, FMOD_ERR_OUTPUT_DRIVERCALL will be returned.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::setSpeakerMode
System::getSpeakerMode
System::getDriverCaps
System::setSoftwareFormat
Channel::setSpeakerLevels
]
*/
typedef enum
{
FMOD_SPEAKERMODE_RAW, /* There is no specific speakermode. Sound channels are mapped in order of input to output. Use System::setSoftwareFormat to specify speaker count. See remarks for more information. */
FMOD_SPEAKERMODE_MONO, /* The speakers are monaural. */
FMOD_SPEAKERMODE_STEREO, /* The speakers are stereo (DEFAULT). */
FMOD_SPEAKERMODE_QUAD, /* 4 speaker setup. This includes front left, front right, rear left, rear right. */
FMOD_SPEAKERMODE_SURROUND, /* 5 speaker setup. This includes front left, front right, center, rear left, rear right. */
FMOD_SPEAKERMODE_5POINT1, /* 5.1 speaker setup. This includes front left, front right, center, rear left, rear right and a subwoofer. */
FMOD_SPEAKERMODE_7POINT1, /* 7.1 speaker setup. This includes front left, front right, center, rear left, rear right, side left, side right and a subwoofer. */
FMOD_SPEAKERMODE_SRS5_1_MATRIX, /* Stereo compatible output, embedded with surround information. SRS 5.1/Prologic/Prologic2 decoders will split the signal into a 5.1 speaker set-up or SRS virtual surround will decode into a 2-speaker/headphone setup. See remarks about limitations.*/
FMOD_SPEAKERMODE_MYEARS, /* Stereo output, but data is encoded using personalized HRTF algorithms. See myears.net.au */
FMOD_SPEAKERMODE_MAX, /* Maximum number of speaker modes supported. */
FMOD_SPEAKERMODE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_SPEAKERMODE;
/*
[ENUM]
[
[DESCRIPTION]
These are speaker types defined for use with the Channel::setSpeakerLevels command.
It can also be used for speaker placement in the System::set3DSpeakerPosition command.
[REMARKS]
If you are using FMOD_SPEAKERMODE_RAW and speaker assignments are meaningless, just cast a raw integer value to this type.<br>
For example (FMOD_SPEAKER)7 would use the 7th speaker (also the same as FMOD_SPEAKER_SIDE_RIGHT).<br>
Values higher than this can be used if an output system has more than 8 speaker types / output channels. 15 is the current maximum.<br>
<br>
NOTE: On Playstation 3 in 7.1, the extra 2 speakers are not side left/side right, they are 'surround back left'/'surround back right' which
locate the speakers behind the listener instead of to the sides like on PC. FMOD_SPEAKER_SBL/FMOD_SPEAKER_SBR are provided to make it
clearer what speaker is being addressed on that platform.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
FMOD_SPEAKERMODE
Channel::setSpeakerLevels
Channel::getSpeakerLevels
System::set3DSpeakerPosition
System::get3DSpeakerPosition
]
*/
typedef enum
{
FMOD_SPEAKER_FRONT_LEFT,
FMOD_SPEAKER_FRONT_RIGHT,
FMOD_SPEAKER_FRONT_CENTER,
FMOD_SPEAKER_LOW_FREQUENCY,
FMOD_SPEAKER_BACK_LEFT,
FMOD_SPEAKER_BACK_RIGHT,
FMOD_SPEAKER_SIDE_LEFT,
FMOD_SPEAKER_SIDE_RIGHT,
FMOD_SPEAKER_MAX, /* Maximum number of speaker types supported. */
FMOD_SPEAKER_MONO = FMOD_SPEAKER_FRONT_LEFT, /* For use with FMOD_SPEAKERMODE_MONO and Channel::SetSpeakerLevels. Mapped to same value as FMOD_SPEAKER_FRONT_LEFT. */
FMOD_SPEAKER_NULL = 65535, /* A non speaker. Use this with ASIO mapping to ignore a speaker. */
FMOD_SPEAKER_SBL = FMOD_SPEAKER_SIDE_LEFT, /* For use with FMOD_SPEAKERMODE_7POINT1 on PS3 where the extra speakers are surround back inside of side speakers. */
FMOD_SPEAKER_SBR = FMOD_SPEAKER_SIDE_RIGHT, /* For use with FMOD_SPEAKERMODE_7POINT1 on PS3 where the extra speakers are surround back inside of side speakers. */
FMOD_SPEAKER_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_SPEAKER;
/*
[ENUM]
[
[DESCRIPTION]
These are plugin types defined for use with the System::getNumPlugins,
System::getPluginInfo and System::unloadPlugin functions.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::getNumPlugins
System::getPluginInfo
System::unloadPlugin
]
*/
typedef enum
{
FMOD_PLUGINTYPE_OUTPUT, /* The plugin type is an output module. FMOD mixed audio will play through one of these devices */
FMOD_PLUGINTYPE_CODEC, /* The plugin type is a file format codec. FMOD will use these codecs to load file formats for playback. */
FMOD_PLUGINTYPE_DSP, /* The plugin type is a DSP unit. FMOD will use these plugins as part of its DSP network to apply effects to output or generate sound in realtime. */
FMOD_PLUGINTYPE_MAX, /* Maximum number of plugin types supported. */
FMOD_PLUGINTYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_PLUGINTYPE;
/*
[DEFINE]
[
[NAME]
FMOD_INITFLAGS
[DESCRIPTION]
Initialization flags. Use them with System::init in the flags parameter to change various behavior.
[REMARKS]
Use System::setAdvancedSettings to adjust settings for some of the features that are enabled by these flags.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::init
System::update
System::setAdvancedSettings
Channel::set3DOcclusion
]
*/
#define FMOD_INIT_NORMAL 0x00000000 /* All platforms - Initialize normally */
#define FMOD_INIT_STREAM_FROM_UPDATE 0x00000001 /* All platforms - No stream thread is created internally. Streams are driven from System::update. Mainly used with non-realtime outputs. */
#define FMOD_INIT_3D_RIGHTHANDED 0x00000002 /* All platforms - FMOD will treat +X as right, +Y as up and +Z as backwards (towards you). */
#define FMOD_INIT_SOFTWARE_DISABLE 0x00000004 /* All platforms - Disable software mixer to save memory. Anything created with FMOD_SOFTWARE will fail and DSP will not work. */
#define FMOD_INIT_OCCLUSION_LOWPASS 0x00000008 /* All platforms - All FMOD_SOFTWARE (and FMOD_HARDWARE on 3DS and NGP) with FMOD_3D based voices will add a software lowpass filter effect into the DSP chain which is automatically used when Channel::set3DOcclusion is used or the geometry API. */
#define FMOD_INIT_HRTF_LOWPASS 0x00000010 /* All platforms - All FMOD_SOFTWARE (and FMOD_HARDWARE on 3DS and NGP) with FMOD_3D based voices will add a software lowpass filter effect into the DSP chain which causes sounds to sound duller when the sound goes behind the listener. Use System::setAdvancedSettings to adjust cutoff frequency. */
#define FMOD_INIT_DISTANCE_FILTERING 0x00000200 /* All platforms - All FMOD_SOFTWARE with FMOD_3D based voices will add a software lowpass and highpass filter effect into the DSP chain which will act as a distance-automated bandpass filter. Use System::setAdvancedSettings to adjust the center frequency. */
#define FMOD_INIT_SOFTWARE_REVERB_LOWMEM 0x00000040 /* All platforms - SFX reverb is run using 22/24khz delay buffers, halving the memory required. */
#define FMOD_INIT_ENABLE_PROFILE 0x00000020 /* All platforms - Enable TCP/IP based host which allows FMOD Designer or FMOD Profiler to connect to it, and view memory, CPU and the DSP network graph in real-time. */
#define FMOD_INIT_VOL0_BECOMES_VIRTUAL 0x00000080 /* All platforms - Any sounds that are 0 volume will go virtual and not be processed except for having their positions updated virtually. Use System::setAdvancedSettings to adjust what volume besides zero to switch to virtual at. */
#define FMOD_INIT_WASAPI_EXCLUSIVE 0x00000100 /* Win32 Vista only - for WASAPI output - Enable exclusive access to hardware, lower latency at the expense of excluding other applications from accessing the audio hardware. */
#define FMOD_INIT_PS3_PREFERDTS 0x00800000 /* PS3 only - Prefer DTS over Dolby Digital if both are supported. Note: 8 and 6 channel LPCM is always preferred over both DTS and Dolby Digital. */
#define FMOD_INIT_PS3_FORCE2CHLPCM 0x01000000 /* PS3 only - Force PS3 system output mode to 2 channel LPCM. */
#define FMOD_INIT_DISABLEDOLBY 0x00100000 /* Wii / 3DS - Disable Dolby Pro Logic surround. Speakermode will be set to STEREO even if user has selected surround in the system settings. */
#define FMOD_INIT_SYSTEM_MUSICMUTENOTPAUSE 0x00200000 /* Xbox 360 / PS3 - The "music" channelgroup which by default pauses when custom 360 dashboard / PS3 BGM music is played, can be changed to mute (therefore continues playing) instead of pausing, by using this flag. */
#define FMOD_INIT_SYNCMIXERWITHUPDATE 0x00400000 /* Win32/Wii/PS3/Xbox/Xbox 360 - FMOD Mixer thread is woken up to do a mix when System::update is called rather than waking periodically on its own timer. */
#define FMOD_INIT_GEOMETRY_USECLOSEST 0x04000000 /* All platforms - With the geometry engine, only process the closest polygon rather than accumulating all polygons the sound to listener line intersects. */
#define FMOD_INIT_DISABLE_MYEARS_AUTODETECT 0x08000000 /* Win32 - Disables automatic setting of FMOD_SPEAKERMODE_STEREO to FMOD_SPEAKERMODE_MYEARS if the MyEars profile exists on the PC. MyEars is HRTF 7.1 downmixing through headphones. */
#define FMOD_INIT_PS3_DISABLEDTS 0x10000000 /* PS3 only - Disable DTS output mode selection */
#define FMOD_INIT_PS3_DISABLEDOLBYDIGITAL 0x20000000 /* PS3 only - Disable Dolby Digital output mode selection */
/* [DEFINE_END] */
/*
[ENUM]
[
[DESCRIPTION]
These definitions describe the type of song being played.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Sound::getFormat
]
*/
typedef enum
{
FMOD_SOUND_TYPE_UNKNOWN, /* 3rd party / unknown plugin format. */
FMOD_SOUND_TYPE_AIFF, /* AIFF. */
FMOD_SOUND_TYPE_ASF, /* Microsoft Advanced Systems Format (ie WMA/ASF/WMV). */
FMOD_SOUND_TYPE_AT3, /* Sony ATRAC 3 format */
FMOD_SOUND_TYPE_CDDA, /* Digital CD audio. */
FMOD_SOUND_TYPE_DLS, /* Sound font / downloadable sound bank. */
FMOD_SOUND_TYPE_FLAC, /* FLAC lossless codec. */
FMOD_SOUND_TYPE_FSB, /* FMOD Sample Bank. */
FMOD_SOUND_TYPE_GCADPCM, /* Nintendo GameCube/Wii ADPCM */
FMOD_SOUND_TYPE_IT, /* Impulse Tracker. */
FMOD_SOUND_TYPE_MIDI, /* MIDI. extracodecdata is a pointer to an FMOD_MIDI_EXTRACODECDATA structure. */
FMOD_SOUND_TYPE_MOD, /* Protracker / Fasttracker MOD. */
FMOD_SOUND_TYPE_MPEG, /* MP2/MP3 MPEG. */
FMOD_SOUND_TYPE_OGGVORBIS, /* Ogg vorbis. */
FMOD_SOUND_TYPE_PLAYLIST, /* Information only from ASX/PLS/M3U/WAX playlists */
FMOD_SOUND_TYPE_RAW, /* Raw PCM data. */
FMOD_SOUND_TYPE_S3M, /* ScreamTracker 3. */
FMOD_SOUND_TYPE_SF2, /* Sound font 2 format. */
FMOD_SOUND_TYPE_USER, /* User created sound. */
FMOD_SOUND_TYPE_WAV, /* Microsoft WAV. */
FMOD_SOUND_TYPE_XM, /* FastTracker 2 XM. */
FMOD_SOUND_TYPE_XMA, /* Xbox360 XMA */
FMOD_SOUND_TYPE_VAG, /* PlayStation Portable ADPCM VAG format. */
FMOD_SOUND_TYPE_AUDIOQUEUE, /* iPhone hardware decoder, supports AAC, ALAC and MP3. extracodecdata is a pointer to an FMOD_AUDIOQUEUE_EXTRACODECDATA structure. */
FMOD_SOUND_TYPE_XWMA, /* Xbox360 XWMA */
FMOD_SOUND_TYPE_BCWAV, /* 3DS BCWAV container format for DSP ADPCM and PCM */
FMOD_SOUND_TYPE_AT9, /* NGP ATRAC 9 format */
FMOD_SOUND_TYPE_VORBIS, /* Raw vorbis */
FMOD_SOUND_TYPE_MEDIA_FOUNDATION,/* Microsoft Media Foundation wrappers, supports ASF/WMA */
FMOD_SOUND_TYPE_MAX, /* Maximum number of sound types supported. */
FMOD_SOUND_TYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_SOUND_TYPE;
/*
[ENUM]
[
[DESCRIPTION]
These definitions describe the native format of the hardware or software buffer that will be used.
[REMARKS]
This is the format the native hardware or software buffer will be or is created in.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::createSound
Sound::getFormat
]
*/
typedef enum
{
FMOD_SOUND_FORMAT_NONE, /* Unitialized / unknown. */
FMOD_SOUND_FORMAT_PCM8, /* 8bit integer PCM data. */
FMOD_SOUND_FORMAT_PCM16, /* 16bit integer PCM data. */
FMOD_SOUND_FORMAT_PCM24, /* 24bit integer PCM data. */
FMOD_SOUND_FORMAT_PCM32, /* 32bit integer PCM data. */
FMOD_SOUND_FORMAT_PCMFLOAT, /* 32bit floating point PCM data. */
FMOD_SOUND_FORMAT_GCADPCM, /* Compressed Nintendo 3DS/Wii DSP data. */
FMOD_SOUND_FORMAT_IMAADPCM, /* Compressed IMA ADPCM data. */
FMOD_SOUND_FORMAT_VAG, /* Compressed PlayStation Portable ADPCM data. */
FMOD_SOUND_FORMAT_HEVAG, /* Compressed PSVita ADPCM data. */
FMOD_SOUND_FORMAT_XMA, /* Compressed Xbox360 XMA data. */
FMOD_SOUND_FORMAT_MPEG, /* Compressed MPEG layer 2 or 3 data. */
FMOD_SOUND_FORMAT_CELT, /* Compressed CELT data. */
FMOD_SOUND_FORMAT_AT9, /* Compressed PSVita ATRAC9 data. */
FMOD_SOUND_FORMAT_XWMA, /* Compressed Xbox360 xWMA data. */
FMOD_SOUND_FORMAT_VORBIS, /* Compressed Vorbis data. */
FMOD_SOUND_FORMAT_MAX, /* Maximum number of sound formats supported. */
FMOD_SOUND_FORMAT_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_SOUND_FORMAT;
/*
[DEFINE]
[
[NAME]
FMOD_MODE
[DESCRIPTION]
Sound description bitfields, bitwise OR them together for loading and describing sounds.
[REMARKS]
By default a sound will open as a static sound that is decompressed fully into memory to PCM. (ie equivalent of FMOD_CREATESAMPLE)<br>
To have a sound stream instead, use FMOD_CREATESTREAM, or use the wrapper function System::createStream.<br>
Some opening modes (ie FMOD_OPENUSER, FMOD_OPENMEMORY, FMOD_OPENMEMORY_POINT, FMOD_OPENRAW) will need extra information.<br>
This can be provided using the FMOD_CREATESOUNDEXINFO structure.
<br>
Specifying FMOD_OPENMEMORY_POINT will POINT to your memory rather allocating its own sound buffers and duplicating it internally.<br>
<b><u>This means you cannot free the memory while FMOD is using it, until after Sound::release is called.</b></u>
With FMOD_OPENMEMORY_POINT, for PCM formats, only WAV, FSB, and RAW are supported. For compressed formats, only those formats supported by FMOD_CREATECOMPRESSEDSAMPLE are supported.<br>
With FMOD_OPENMEMORY_POINT and FMOD_OPENRAW or PCM, if using them together, note that you must pad the data on each side by 16 bytes. This is so fmod can modify the ends of the data for looping/interpolation/mixing purposes. If a wav file, you will need to insert silence, and then reset loop points to stop the playback from playing that silence.<br>
With FMOD_OPENMEMORY_POINT, For Wii/PSP FMOD_HARDWARE supports this flag for the GCADPCM/VAG formats. On other platforms FMOD_SOFTWARE must be used.<br>
<br>
<b>Xbox 360 memory</b> On Xbox 360 Specifying FMOD_OPENMEMORY_POINT to a virtual memory address will cause FMOD_ERR_INVALID_ADDRESS
to be returned. Use physical memory only for this functionality.<br>
<br>
FMOD_LOWMEM is used on a sound if you want to minimize the memory overhead, by having FMOD not allocate memory for certain
features that are not likely to be used in a game environment. These are :<br>
1. Sound::getName functionality is removed. 256 bytes per sound is saved.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::createSound
System::createStream
Sound::setMode
Sound::getMode
Channel::setMode
Channel::getMode
Sound::set3DCustomRolloff
Channel::set3DCustomRolloff
Sound::getOpenState
]
*/
#define FMOD_DEFAULT 0x00000000 /* Default for all modes listed below. FMOD_LOOP_OFF, FMOD_2D, FMOD_HARDWARE */
#define FMOD_LOOP_OFF 0x00000001 /* For non looping sounds. (DEFAULT). Overrides FMOD_LOOP_NORMAL / FMOD_LOOP_BIDI. */
#define FMOD_LOOP_NORMAL 0x00000002 /* For forward looping sounds. */
#define FMOD_LOOP_BIDI 0x00000004 /* For bidirectional looping sounds. (only works on software mixed static sounds). */
#define FMOD_2D 0x00000008 /* Ignores any 3d processing. (DEFAULT). */
#define FMOD_3D 0x00000010 /* Makes the sound positionable in 3D. Overrides FMOD_2D. */
#define FMOD_HARDWARE 0x00000020 /* Attempts to make sounds use hardware acceleration. (DEFAULT). Note on platforms that don't support FMOD_HARDWARE (only 3DS, PS Vita, PSP, Wii and Wii U support FMOD_HARDWARE), this will be internally treated as FMOD_SOFTWARE. */
#define FMOD_SOFTWARE 0x00000040 /* Makes the sound be mixed by the FMOD CPU based software mixer. Overrides FMOD_HARDWARE. Use this for FFT, DSP, compressed sample support, 2D multi-speaker support and other software related features. */
#define FMOD_CREATESTREAM 0x00000080 /* Decompress at runtime, streaming from the source provided (ie from disk). Overrides FMOD_CREATESAMPLE and FMOD_CREATECOMPRESSEDSAMPLE. Note a stream can only be played once at a time due to a stream only having 1 stream buffer and file handle. Open multiple streams to have them play concurrently. */
#define FMOD_CREATESAMPLE 0x00000100 /* Decompress at loadtime, decompressing or decoding whole file into memory as the target sample format (ie PCM). Fastest for FMOD_SOFTWARE based playback and most flexible. */
#define FMOD_CREATECOMPRESSEDSAMPLE 0x00000200 /* Load MP2, MP3, IMAADPCM or XMA into memory and leave it compressed. During playback the FMOD software mixer will decode it in realtime as a 'compressed sample'. Can only be used in combination with FMOD_SOFTWARE. Overrides FMOD_CREATESAMPLE. If the sound data is not ADPCM, MPEG or XMA it will behave as if it was created with FMOD_CREATESAMPLE and decode the sound into PCM. */
#define FMOD_OPENUSER 0x00000400 /* Opens a user created static sample or stream. Use FMOD_CREATESOUNDEXINFO to specify format and/or read callbacks. If a user created 'sample' is created with no read callback, the sample will be empty. Use Sound::lock and Sound::unlock to place sound data into the sound if this is the case. */
#define FMOD_OPENMEMORY 0x00000800 /* "name_or_data" will be interpreted as a pointer to memory instead of filename for creating sounds. Use FMOD_CREATESOUNDEXINFO to specify length. If used with FMOD_CREATESAMPLE or FMOD_CREATECOMPRESSEDSAMPLE, FMOD duplicates the memory into its own buffers. Your own buffer can be freed after open. If used with FMOD_CREATESTREAM, FMOD will stream out of the buffer whose pointer you passed in. In this case, your own buffer should not be freed until you have finished with and released the stream.*/
#define FMOD_OPENMEMORY_POINT 0x10000000 /* "name_or_data" will be interpreted as a pointer to memory instead of filename for creating sounds. Use FMOD_CREATESOUNDEXINFO to specify length. This differs to FMOD_OPENMEMORY in that it uses the memory as is, without duplicating the memory into its own buffers. For Wii/PSP FMOD_HARDWARE supports this flag for the GCADPCM/VAG formats. On other platforms FMOD_SOFTWARE must be used, as sound hardware on the other platforms (ie PC) cannot access main ram. Cannot be freed after open, only after Sound::release. Will not work if the data is compressed and FMOD_CREATECOMPRESSEDSAMPLE is not used. */
#define FMOD_OPENRAW 0x00001000 /* Will ignore file format and treat as raw pcm. Use FMOD_CREATESOUNDEXINFO to specify format. Requires at least defaultfrequency, numchannels and format to be specified before it will open. Must be little endian data. */
#define FMOD_OPENONLY 0x00002000 /* Just open the file, dont prebuffer or read. Good for fast opens for info, or when sound::readData is to be used. */
#define FMOD_ACCURATETIME 0x00004000 /* For System::createSound - for accurate Sound::getLength/Channel::setPosition on VBR MP3, and MOD/S3M/XM/IT/MIDI files. Scans file first, so takes longer to open. FMOD_OPENONLY does not affect this. */
#define FMOD_MPEGSEARCH 0x00008000 /* For corrupted / bad MP3 files. This will search all the way through the file until it hits a valid MPEG header. Normally only searches for 4k. */
#define FMOD_NONBLOCKING 0x00010000 /* For opening sounds and getting streamed subsounds (seeking) asyncronously. Use Sound::getOpenState to poll the state of the sound as it opens or retrieves the subsound in the background. */
#define FMOD_UNIQUE 0x00020000 /* Unique sound, can only be played one at a time */
#define FMOD_3D_HEADRELATIVE 0x00040000 /* Make the sound's position, velocity and orientation relative to the listener. */
#define FMOD_3D_WORLDRELATIVE 0x00080000 /* Make the sound's position, velocity and orientation absolute (relative to the world). (DEFAULT) */
#define FMOD_3D_INVERSEROLLOFF 0x00100000 /* This sound will follow the inverse rolloff model where mindistance = full volume, maxdistance = where sound stops attenuating, and rolloff is fixed according to the global rolloff factor. (DEFAULT) */
#define FMOD_3D_LINEARROLLOFF 0x00200000 /* This sound will follow a linear rolloff model where mindistance = full volume, maxdistance = silence. Rolloffscale is ignored. */
#define FMOD_3D_LINEARSQUAREROLLOFF 0x00400000 /* This sound will follow a linear-square rolloff model where mindistance = full volume, maxdistance = silence. Rolloffscale is ignored. */
#define FMOD_3D_CUSTOMROLLOFF 0x04000000 /* This sound will follow a rolloff model defined by Sound::set3DCustomRolloff / Channel::set3DCustomRolloff. */
#define FMOD_3D_IGNOREGEOMETRY 0x40000000 /* Is not affect by geometry occlusion. If not specified in Sound::setMode, or Channel::setMode, the flag is cleared and it is affected by geometry again. */
#define FMOD_UNICODE 0x01000000 /* Filename is double-byte unicode. */
#define FMOD_IGNORETAGS 0x02000000 /* Skips id3v2/asf/etc tag checks when opening a sound, to reduce seek/read overhead when opening files (helps with CD performance). */
#define FMOD_LOWMEM 0x08000000 /* Removes some features from samples to give a lower memory overhead, like Sound::getName. See remarks. */
#define FMOD_LOADSECONDARYRAM 0x20000000 /* Load sound into the secondary RAM of supported platform. On PS3, sounds will be loaded into RSX/VRAM. */
#define FMOD_VIRTUAL_PLAYFROMSTART 0x80000000 /* For sounds that start virtual (due to being quiet or low importance), instead of swapping back to audible, and playing at the correct offset according to time, this flag makes the sound play from the start. */
/* [DEFINE_END] */
/*
[ENUM]
[
[DESCRIPTION]
These values describe what state a sound is in after FMOD_NONBLOCKING has been used to open it.
[REMARKS]
With streams, if you are using FMOD_NONBLOCKING, note that if the user calls Sound::getSubSound, a stream will go into FMOD_OPENSTATE_SEEKING state and sound related commands will return FMOD_ERR_NOTREADY.<br>
With streams, if you are using FMOD_NONBLOCKING, note that if the user calls Channel::getPosition, a stream will go into FMOD_OPENSTATE_SETPOSITION state and sound related commands will return FMOD_ERR_NOTREADY.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Sound::getOpenState
FMOD_MODE
]
*/
typedef enum
{
FMOD_OPENSTATE_READY = 0, /* Opened and ready to play. */
FMOD_OPENSTATE_LOADING, /* Initial load in progress. */
FMOD_OPENSTATE_ERROR, /* Failed to open - file not found, out of memory etc. See return value of Sound::getOpenState for what happened. */
FMOD_OPENSTATE_CONNECTING, /* Connecting to remote host (internet sounds only). */
FMOD_OPENSTATE_BUFFERING, /* Buffering data. */
FMOD_OPENSTATE_SEEKING, /* Seeking to subsound and re-flushing stream buffer. */
FMOD_OPENSTATE_PLAYING, /* Ready and playing, but not possible to release at this time without stalling the main thread. */
FMOD_OPENSTATE_SETPOSITION, /* Seeking within a stream to a different position. */
FMOD_OPENSTATE_MAX, /* Maximum number of open state types. */
FMOD_OPENSTATE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_OPENSTATE;
/*
[ENUM]
[
[DESCRIPTION]
These flags are used with SoundGroup::setMaxAudibleBehavior to determine what happens when more sounds
are played than are specified with SoundGroup::setMaxAudible.
[REMARKS]
When using FMOD_SOUNDGROUP_BEHAVIOR_MUTE, SoundGroup::setMuteFadeSpeed can be used to stop a sudden transition.
Instead, the time specified will be used to cross fade between the sounds that go silent and the ones that become audible.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
SoundGroup::setMaxAudibleBehavior
SoundGroup::getMaxAudibleBehavior
SoundGroup::setMaxAudible
SoundGroup::getMaxAudible
SoundGroup::setMuteFadeSpeed
SoundGroup::getMuteFadeSpeed
]
*/
typedef enum
{
FMOD_SOUNDGROUP_BEHAVIOR_FAIL, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will simply fail during System::playSound. */
FMOD_SOUNDGROUP_BEHAVIOR_MUTE, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will be silent, then if another sound in the group stops the sound that was silent before becomes audible again. */
FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will steal the quietest / least important sound playing in the group. */
FMOD_SOUNDGROUP_BEHAVIOR_MAX, /* Maximum number of open state types. */
FMOD_SOUNDGROUP_BEHAVIOR_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_SOUNDGROUP_BEHAVIOR;
/*
[ENUM]
[
[DESCRIPTION]
These callback types are used with Channel::setCallback.
[REMARKS]
Each callback has commanddata parameters passed as int unique to the type of callback.<br>
See reference to FMOD_CHANNEL_CALLBACK to determine what they might mean for each type of callback.<br>
<br>
<b>Note!</b> Currently the user must call System::update for these callbacks to trigger!
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Channel::setCallback
FMOD_CHANNEL_CALLBACK
System::update
]
*/
typedef enum
{
FMOD_CHANNEL_CALLBACKTYPE_END, /* Called when a sound ends. */
FMOD_CHANNEL_CALLBACKTYPE_VIRTUALVOICE, /* Called when a voice is swapped out or swapped in. */
FMOD_CHANNEL_CALLBACKTYPE_SYNCPOINT, /* Called when a syncpoint is encountered. Can be from wav file markers. */
FMOD_CHANNEL_CALLBACKTYPE_OCCLUSION, /* Called when the channel has its geometry occlusion value calculated. Can be used to clamp or change the value. */
FMOD_CHANNEL_CALLBACKTYPE_MAX, /* Maximum number of callback types supported. */
FMOD_CHANNEL_CALLBACKTYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_CHANNEL_CALLBACKTYPE;
/*
[ENUM]
[
[DESCRIPTION]
These callback types are used with System::setCallback.
[REMARKS]
Each callback has commanddata parameters passed as void* unique to the type of callback.<br>
See reference to FMOD_SYSTEM_CALLBACK to determine what they might mean for each type of callback.<br>
<br>
<b>Note!</b> Using FMOD_SYSTEM_CALLBACKTYPE_DEVICELISTCHANGED (on Mac only) requires the application to be running an event loop which will allow external changes to device list to be detected by FMOD.
<br>
<b>Note!</b> The 'system' object pointer will be null for FMOD_SYSTEM_CALLBACKTYPE_THREADCREATED and FMOD_SYSTEM_CALLBACKTYPE_MEMORYALLOCATIONFAILED callbacks.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::setCallback
FMOD_SYSTEM_CALLBACK
System::update
DSP::addInput
]
*/
typedef enum
{
FMOD_SYSTEM_CALLBACKTYPE_DEVICELISTCHANGED, /* Called from System::update when the enumerated list of devices has changed. */
FMOD_SYSTEM_CALLBACKTYPE_DEVICELOST, /* Called from System::update when an output device has been lost due to control panel parameter changes and FMOD cannot automatically recover. */
FMOD_SYSTEM_CALLBACKTYPE_MEMORYALLOCATIONFAILED, /* Called directly when a memory allocation fails somewhere in FMOD. (NOTE - 'system' will be NULL in this callback type.)*/
FMOD_SYSTEM_CALLBACKTYPE_THREADCREATED, /* Called directly when a thread is created. (NOTE - 'system' will be NULL in this callback type.) */
FMOD_SYSTEM_CALLBACKTYPE_BADDSPCONNECTION, /* Called when a bad connection was made with DSP::addInput. Usually called from mixer thread because that is where the connections are made. */
FMOD_SYSTEM_CALLBACKTYPE_BADDSPLEVEL, /* Called when too many effects were added exceeding the maximum tree depth of 128. This is most likely caused by accidentally adding too many DSP effects. Usually called from mixer thread because that is where the connections are made. */
FMOD_SYSTEM_CALLBACKTYPE_MAX, /* Maximum number of callback types supported. */
FMOD_SYSTEM_CALLBACKTYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_SYSTEM_CALLBACKTYPE;
/*
FMOD Callbacks
*/
typedef FMOD_RESULT (F_CALLBACK *FMOD_SYSTEM_CALLBACK) (FMOD_SYSTEM *system, FMOD_SYSTEM_CALLBACKTYPE type, void *commanddata1, void *commanddata2);
typedef FMOD_RESULT (F_CALLBACK *FMOD_CHANNEL_CALLBACK) (FMOD_CHANNEL *channel, FMOD_CHANNEL_CALLBACKTYPE type, void *commanddata1, void *commanddata2);
typedef FMOD_RESULT (F_CALLBACK *FMOD_SOUND_NONBLOCKCALLBACK)(FMOD_SOUND *sound, FMOD_RESULT result);
typedef FMOD_RESULT (F_CALLBACK *FMOD_SOUND_PCMREADCALLBACK)(FMOD_SOUND *sound, void *data, unsigned int datalen);
typedef FMOD_RESULT (F_CALLBACK *FMOD_SOUND_PCMSETPOSCALLBACK)(FMOD_SOUND *sound, int subsound, unsigned int position, FMOD_TIMEUNIT postype);
typedef FMOD_RESULT (F_CALLBACK *FMOD_FILE_OPENCALLBACK) (const char *name, int unicode, unsigned int *filesize, void **handle, void **userdata);
typedef FMOD_RESULT (F_CALLBACK *FMOD_FILE_CLOSECALLBACK) (void *handle, void *userdata);
typedef FMOD_RESULT (F_CALLBACK *FMOD_FILE_READCALLBACK) (void *handle, void *buffer, unsigned int sizebytes, unsigned int *bytesread, void *userdata);
typedef FMOD_RESULT (F_CALLBACK *FMOD_FILE_SEEKCALLBACK) (void *handle, unsigned int pos, void *userdata);
typedef FMOD_RESULT (F_CALLBACK *FMOD_FILE_ASYNCREADCALLBACK)(FMOD_ASYNCREADINFO *info, void *userdata);
typedef FMOD_RESULT (F_CALLBACK *FMOD_FILE_ASYNCCANCELCALLBACK)(void *handle, void *userdata);
typedef void * (F_CALLBACK *FMOD_MEMORY_ALLOCCALLBACK) (unsigned int size, FMOD_MEMORY_TYPE type, const char *sourcestr);
typedef void * (F_CALLBACK *FMOD_MEMORY_REALLOCCALLBACK)(void *ptr, unsigned int size, FMOD_MEMORY_TYPE type, const char *sourcestr);
typedef void (F_CALLBACK *FMOD_MEMORY_FREECALLBACK) (void *ptr, FMOD_MEMORY_TYPE type, const char *sourcestr);
typedef float (F_CALLBACK *FMOD_3D_ROLLOFFCALLBACK) (FMOD_CHANNEL *channel, float distance);
/*
[ENUM]
[
[DESCRIPTION]
List of windowing methods used in spectrum analysis to reduce leakage / transient signals intefering with the analysis.<br>
This is a problem with analysis of continuous signals that only have a small portion of the signal sample (the fft window size).<br>
Windowing the signal with a curve or triangle tapers the sides of the fft window to help alleviate this problem.
[REMARKS]
Cyclic signals such as a sine wave that repeat their cycle in a multiple of the window size do not need windowing.<br>
I.e. If the sine wave repeats every 1024, 512, 256 etc samples and the FMOD fft window is 1024, then the signal would not need windowing.<br>
Not windowing is the same as FMOD_DSP_FFT_WINDOW_RECT, which is the default.<br>
If the cycle of the signal (ie the sine wave) is not a multiple of the window size, it will cause frequency abnormalities, so a different windowing method is needed.<br>
<exclude>
<br>
FMOD_DSP_FFT_WINDOW_RECT.<br>
<img src="..\static\rectangle.gif"></img><br>
<br>
FMOD_DSP_FFT_WINDOW_TRIANGLE.<br>
<img src="..\static\triangle.gif"></img><br>
<br>
FMOD_DSP_FFT_WINDOW_HAMMING.<br>
<img src="..\static\hamming.gif"></img><br>
<br>
FMOD_DSP_FFT_WINDOW_HANNING.<br>
<img src="..\static\hanning.gif"></img><br>
<br>
FMOD_DSP_FFT_WINDOW_BLACKMAN.<br>
<img src="..\static\blackman.gif"></img><br>
<br>
FMOD_DSP_FFT_WINDOW_BLACKMANHARRIS.<br>
<img src="..\static\blackmanharris.gif"></img>
</exclude>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::getSpectrum
Channel::getSpectrum
]
*/
typedef enum
{
FMOD_DSP_FFT_WINDOW_RECT, /* w[n] = 1.0 */
FMOD_DSP_FFT_WINDOW_TRIANGLE, /* w[n] = TRI(2n/N) */
FMOD_DSP_FFT_WINDOW_HAMMING, /* w[n] = 0.54 - (0.46 * COS(n/N) ) */
FMOD_DSP_FFT_WINDOW_HANNING, /* w[n] = 0.5 * (1.0 - COS(n/N) ) */
FMOD_DSP_FFT_WINDOW_BLACKMAN, /* w[n] = 0.42 - (0.5 * COS(n/N) ) + (0.08 * COS(2.0 * n/N) ) */
FMOD_DSP_FFT_WINDOW_BLACKMANHARRIS, /* w[n] = 0.35875 - (0.48829 * COS(1.0 * n/N)) + (0.14128 * COS(2.0 * n/N)) - (0.01168 * COS(3.0 * n/N)) */
FMOD_DSP_FFT_WINDOW_MAX, /* Maximum number of FFT window types supported. */
FMOD_DSP_FFT_WINDOW_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_DSP_FFT_WINDOW;
/*
[ENUM]
[
[DESCRIPTION]
List of interpolation types that the FMOD Ex software mixer supports.
[REMARKS]
The default resampler type is FMOD_DSP_RESAMPLER_LINEAR.<br>
Use System::setSoftwareFormat to tell FMOD the resampling quality you require for FMOD_SOFTWARE based sounds.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::setSoftwareFormat
System::getSoftwareFormat
]
*/
typedef enum
{
FMOD_DSP_RESAMPLER_NOINTERP, /* No interpolation. High frequency aliasing hiss will be audible depending on the sample rate of the sound. */
FMOD_DSP_RESAMPLER_LINEAR, /* Linear interpolation (default method). Fast and good quality, causes very slight lowpass effect on low frequency sounds. */
FMOD_DSP_RESAMPLER_CUBIC, /* Cubic interpolation. Slower than linear interpolation but better quality. */
FMOD_DSP_RESAMPLER_SPLINE, /* 5 point spline interpolation. Slowest resampling method but best quality. */
FMOD_DSP_RESAMPLER_MAX, /* Maximum number of resample methods supported. */
FMOD_DSP_RESAMPLER_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_DSP_RESAMPLER;
/*
[ENUM]
[
[DESCRIPTION]
List of tag types that could be stored within a sound. These include id3 tags, metadata from netstreams and vorbis/asf data.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Sound::getTag
]
*/
typedef enum
{
FMOD_TAGTYPE_UNKNOWN = 0,
FMOD_TAGTYPE_ID3V1,
FMOD_TAGTYPE_ID3V2,
FMOD_TAGTYPE_VORBISCOMMENT,
FMOD_TAGTYPE_SHOUTCAST,
FMOD_TAGTYPE_ICECAST,
FMOD_TAGTYPE_ASF,
FMOD_TAGTYPE_MIDI,
FMOD_TAGTYPE_PLAYLIST,
FMOD_TAGTYPE_FMOD,
FMOD_TAGTYPE_USER,
FMOD_TAGTYPE_MAX, /* Maximum number of tag types supported. */
FMOD_TAGTYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_TAGTYPE;
/*
[ENUM]
[
[DESCRIPTION]
List of data types that can be returned by Sound::getTag
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Sound::getTag
]
*/
typedef enum
{
FMOD_TAGDATATYPE_BINARY = 0,
FMOD_TAGDATATYPE_INT,
FMOD_TAGDATATYPE_FLOAT,
FMOD_TAGDATATYPE_STRING,
FMOD_TAGDATATYPE_STRING_UTF16,
FMOD_TAGDATATYPE_STRING_UTF16BE,
FMOD_TAGDATATYPE_STRING_UTF8,
FMOD_TAGDATATYPE_CDTOC,
FMOD_TAGDATATYPE_MAX, /* Maximum number of tag datatypes supported. */
FMOD_TAGDATATYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_TAGDATATYPE;
/*
[ENUM]
[
[DESCRIPTION]
Types of delay that can be used with Channel::setDelay / Channel::getDelay.
[REMARKS]
If you haven't called Channel::setDelay yet, if you call Channel::getDelay with FMOD_DELAYTYPE_DSPCLOCK_START it will return the
equivalent global DSP clock value to determine when a channel started, so that you can use it for other channels to sync against.<br>
<br>
Use System::getDSPClock to also get the current dspclock time, a base for future calls to Channel::setDelay.<br>
<br>
Use FMOD_64BIT_ADD or FMOD_64BIT_SUB to add a hi/lo combination together and cope with wraparound.
<br>
If FMOD_DELAYTYPE_END_MS is specified, the value is not treated as a 64 bit number, just the delayhi value is used and it is treated as milliseconds.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Channel::setDelay
Channel::getDelay
System::getDSPClock
]
*/
typedef enum
{
FMOD_DELAYTYPE_END_MS, /* Delay at the end of the sound in milliseconds. Use delayhi only. Channel::isPlaying will remain true until this delay has passed even though the sound itself has stopped playing.*/
FMOD_DELAYTYPE_DSPCLOCK_START, /* Time the sound started if Channel::getDelay is used, or if Channel::setDelay is used, the sound will delay playing until this exact tick. */
FMOD_DELAYTYPE_DSPCLOCK_END, /* Time the sound should end. If this is non-zero, the channel will go silent at this exact tick. */
FMOD_DELAYTYPE_DSPCLOCK_PAUSE, /* Time the sound should pause. If this is non-zero, the channel will pause at this exact tick. */
FMOD_DELAYTYPE_MAX, /* Maximum number of tag datatypes supported. */
FMOD_DELAYTYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */
} FMOD_DELAYTYPE;
#define FMOD_64BIT_ADD(_hi1, _lo1, _hi2, _lo2) _hi1 += ((_hi2) + ((((_lo1) + (_lo2)) < (_lo1)) ? 1 : 0)); (_lo1) += (_lo2);
#define FMOD_64BIT_SUB(_hi1, _lo1, _hi2, _lo2) _hi1 -= ((_hi2) + ((((_lo1) - (_lo2)) > (_lo1)) ? 1 : 0)); (_lo1) -= (_lo2);
/*
[STRUCTURE]
[
[DESCRIPTION]
Structure describing a piece of tag data.
[REMARKS]
Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
Members marked with [w] mean the variable can be written to. The user can set the value.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Sound::getTag
FMOD_TAGTYPE
FMOD_TAGDATATYPE
]
*/
typedef struct FMOD_TAG
{
FMOD_TAGTYPE type; /* [r] The type of this tag. */
FMOD_TAGDATATYPE datatype; /* [r] The type of data that this tag contains */
char *name; /* [r] The name of this tag i.e. "TITLE", "ARTIST" etc. */
void *data; /* [r] Pointer to the tag data - its format is determined by the datatype member */
unsigned int datalen; /* [r] Length of the data contained in this tag */
FMOD_BOOL updated; /* [r] True if this tag has been updated since last being accessed with Sound::getTag */
} FMOD_TAG;
/*
[STRUCTURE]
[
[DESCRIPTION]
Structure describing a CD/DVD table of contents
[REMARKS]
Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
Members marked with [w] mean the variable can be written to. The user can set the value.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Sound::getTag
]
*/
typedef struct FMOD_CDTOC
{
int numtracks; /* [r] The number of tracks on the CD */
int min[100]; /* [r] The start offset of each track in minutes */
int sec[100]; /* [r] The start offset of each track in seconds */
int frame[100]; /* [r] The start offset of each track in frames */
} FMOD_CDTOC;
/*
[DEFINE]
[
[NAME]
FMOD_TIMEUNIT
[DESCRIPTION]
List of time types that can be returned by Sound::getLength and used with Channel::setPosition or Channel::getPosition.
[REMARKS]
FMOD_TIMEUNIT_SENTENCE_MS, FMOD_TIMEUNIT_SENTENCE_PCM, FMOD_TIMEUNIT_SENTENCE_PCMBYTES, FMOD_TIMEUNIT_SENTENCE and FMOD_TIMEUNIT_SENTENCE_SUBSOUND are only supported by Channel functions.
Do not combine flags except FMOD_TIMEUNIT_BUFFERED.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Sound::getLength
Channel::setPosition
Channel::getPosition
]
*/
#define FMOD_TIMEUNIT_MS 0x00000001 /* Milliseconds. */
#define FMOD_TIMEUNIT_PCM 0x00000002 /* PCM samples, related to milliseconds * samplerate / 1000. */
#define FMOD_TIMEUNIT_PCMBYTES 0x00000004 /* Bytes, related to PCM samples * channels * datawidth (ie 16bit = 2 bytes). */
#define FMOD_TIMEUNIT_RAWBYTES 0x00000008 /* Raw file bytes of (compressed) sound data (does not include headers). Only used by Sound::getLength and Channel::getPosition. */
#define FMOD_TIMEUNIT_PCMFRACTION 0x00000010 /* Fractions of 1 PCM sample. Unsigned int range 0 to 0xFFFFFFFF. Used for sub-sample granularity for DSP purposes. */
#define FMOD_TIMEUNIT_MODORDER 0x00000100 /* MOD/S3M/XM/IT. Order in a sequenced module format. Use Sound::getFormat to determine the PCM format being decoded to. */
#define FMOD_TIMEUNIT_MODROW 0x00000200 /* MOD/S3M/XM/IT. Current row in a sequenced module format. Sound::getLength will return the number of rows in the currently playing or seeked to pattern. */
#define FMOD_TIMEUNIT_MODPATTERN 0x00000400 /* MOD/S3M/XM/IT. Current pattern in a sequenced module format. Sound::getLength will return the number of patterns in the song and Channel::getPosition will return the currently playing pattern. */
#define FMOD_TIMEUNIT_SENTENCE_MS 0x00010000 /* Currently playing subsound in a sentence time in milliseconds. */
#define FMOD_TIMEUNIT_SENTENCE_PCM 0x00020000 /* Currently playing subsound in a sentence time in PCM Samples, related to milliseconds * samplerate / 1000. */
#define FMOD_TIMEUNIT_SENTENCE_PCMBYTES 0x00040000 /* Currently playing subsound in a sentence time in bytes, related to PCM samples * channels * datawidth (ie 16bit = 2 bytes). */
#define FMOD_TIMEUNIT_SENTENCE 0x00080000 /* Currently playing sentence index according to the channel. */
#define FMOD_TIMEUNIT_SENTENCE_SUBSOUND 0x00100000 /* Currently playing subsound index in a sentence. */
#define FMOD_TIMEUNIT_BUFFERED 0x10000000 /* Time value as seen by buffered stream. This is always ahead of audible time, and is only used for processing. */
/* [DEFINE_END] */
/*
[ENUM]
[
[DESCRIPTION]
When creating a multichannel sound, FMOD will pan them to their default speaker locations, for example a 6 channel sound will default to one channel per 5.1 output speaker.<br>
Another example is a stereo sound. It will default to left = front left, right = front right.<br>
<br>
This is for sounds that are not 'default'. For example you might have a sound that is 6 channels but actually made up of 3 stereo pairs, that should all be located in front left, front right only.
[REMARKS]
For full flexibility of speaker assignments, use Channel::setSpeakerLevels.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
FMOD_CREATESOUNDEXINFO
Channel::setSpeakerLevels
]
*/
typedef enum
{
FMOD_SPEAKERMAPTYPE_DEFAULT, /* This is the default, and just means FMOD decides which speakers it puts the source channels. */
FMOD_SPEAKERMAPTYPE_ALLMONO, /* This means the sound is made up of all mono sounds. All voices will be panned to the front center by default in this case. */
FMOD_SPEAKERMAPTYPE_ALLSTEREO, /* This means the sound is made up of all stereo sounds. All voices will be panned to front left and front right alternating every second channel. */
FMOD_SPEAKERMAPTYPE_51_PROTOOLS /* Map a 5.1 sound to use protools L C R Ls Rs LFE mapping. Will return an error if not a 6 channel sound. */
} FMOD_SPEAKERMAPTYPE;
/*
[STRUCTURE]
[
[DESCRIPTION]
Use this structure with System::createSound when more control is needed over loading.<br>
The possible reasons to use this with System::createSound are:<br>
<li>Loading a file from memory.
<li>Loading a file from within another larger (possibly wad/pak) file, by giving the loader an offset and length.
<li>To create a user created / non file based sound.
<li>To specify a starting subsound to seek to within a multi-sample sounds (ie FSB/DLS/SF2) when created as a stream.
<li>To specify which subsounds to load for multi-sample sounds (ie FSB/DLS/SF2) so that memory is saved and only a subset is actually loaded/read from disk.
<li>To specify 'piggyback' read and seek callbacks for capture of sound data as fmod reads and decodes it. Useful for ripping decoded PCM data from sounds as they are loaded / played.
<li>To specify a MIDI DLS/SF2 sample set file to load when opening a MIDI file.
See below on what members to fill for each of the above types of sound you want to create.
[REMARKS]
This structure is optional! Specify 0 or NULL in System::createSound if you don't need it!<br>
<br>
<u>Loading a file from memory.</u><br>
<li>Create the sound using the FMOD_OPENMEMORY flag.<br>
<li>Mandatory. Specify 'length' for the size of the memory block in bytes.
<li>Other flags are optional.
<br>
<br>
<u>Loading a file from within another larger (possibly wad/pak) file, by giving the loader an offset and length.</u><br>
<li>Mandatory. Specify 'fileoffset' and 'length'.
<li>Other flags are optional.
<br>
<br>
<u>To create a user created / non file based sound.</u><br>
<li>Create the sound using the FMOD_OPENUSER flag.
<li>Mandatory. Specify 'defaultfrequency, 'numchannels' and 'format'.
<li>Other flags are optional.
<br>
<br>
<u>To specify a starting subsound to seek to and flush with, within a multi-sample stream (ie FSB/DLS/SF2).</u><br>
<br>
<li>Mandatory. Specify 'initialsubsound'.
<br>
<br>
<u>To specify which subsounds to load for multi-sample sounds (ie FSB/DLS/SF2) so that memory is saved and only a subset is actually loaded/read from disk.</u><br>
<br>
<li>Mandatory. Specify 'inclusionlist' and 'inclusionlistnum'.
<br>
<br>
<u>To specify 'piggyback' read and seek callbacks for capture of sound data as fmod reads and decodes it. Useful for ripping decoded PCM data from sounds as they are loaded / played.</u><br>
<br>
<li>Mandatory. Specify 'pcmreadcallback' and 'pcmseekcallback'.
<br>
<br>
<u>To specify a MIDI DLS/SF2 sample set file to load when opening a MIDI file.</u><br>
<br>
<li>Mandatory. Specify 'dlsname'.
<br>
<br>
Setting the 'decodebuffersize' is for cpu intensive codecs that may be causing stuttering, not file intensive codecs (ie those from CD or netstreams) which are normally
altered with System::setStreamBufferSize. As an example of cpu intensive codecs, an mp3 file will take more cpu to decode than a PCM wav file.<br>
If you have a stuttering effect, then it is using more cpu than the decode buffer playback rate can keep up with. Increasing the decode buffersize will most likely solve this problem.<br>
<br>
<br>
FSB codec. If inclusionlist and numsubsounds are used together, this will trigger a special mode where subsounds are shuffled down to save memory. (useful for large FSB
files where you only want to load 1 sound). There will be no gaps, ie no null subsounds. As an example, if there are 10,000 subsounds and there is an inclusionlist with only 1 entry,
and numsubsounds = 1, then subsound 0 will be that entry, and there will only be the memory allocated for 1 subsound. Previously there would still be 10,000 subsound pointers and other
associated codec entries allocated along with it multiplied by 10,000.<br>
<br>
Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
Members marked with [w] mean the variable can be written to. The user can set the value.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::createSound
System::setStreamBufferSize
FMOD_MODE
FMOD_SOUND_FORMAT
FMOD_SOUND_TYPE
FMOD_SPEAKERMAPTYPE
]
*/
typedef struct FMOD_CREATESOUNDEXINFO
{
int cbsize; /* [w] Size of this structure. This is used so the structure can be expanded in the future and still work on older versions of FMOD Ex. */
unsigned int length; /* [w] Optional. Specify 0 to ignore. Size in bytes of file to load, or sound to create (in this case only if FMOD_OPENUSER is used). Required if loading from memory. If 0 is specified, then it will use the size of the file (unless loading from memory then an error will be returned). */
unsigned int fileoffset; /* [w] Optional. Specify 0 to ignore. Offset from start of the file to start loading from. This is useful for loading files from inside big data files. */
int numchannels; /* [w] Optional. Specify 0 to ignore. Number of channels in a sound mandatory if FMOD_OPENUSER or FMOD_OPENRAW is used. */
int defaultfrequency; /* [w] Optional. Specify 0 to ignore. Default frequency of sound in a sound mandatory if FMOD_OPENUSER or FMOD_OPENRAW is used. Other formats use the frequency determined by the file format. */
FMOD_SOUND_FORMAT format; /* [w] Optional. Specify 0 or FMOD_SOUND_FORMAT_NONE to ignore. Format of the sound mandatory if FMOD_OPENUSER or FMOD_OPENRAW is used. Other formats use the format determined by the file format. */
unsigned int decodebuffersize; /* [w] Optional. Specify 0 to ignore. For streams. This determines the size of the double buffer (in PCM samples) that a stream uses. Use this for user created streams if you want to determine the size of the callback buffer passed to you. Specify 0 to use FMOD's default size which is currently equivalent to 400ms of the sound format created/loaded. */
int initialsubsound; /* [w] Optional. Specify 0 to ignore. In a multi-sample file format such as .FSB/.DLS/.SF2, specify the initial subsound to seek to, only if FMOD_CREATESTREAM is used. */
int numsubsounds; /* [w] Optional. Specify 0 to ignore or have no subsounds. In a sound created with FMOD_OPENUSER, specify the number of subsounds that are accessable with Sound::getSubSound. If not created with FMOD_OPENUSER, this will limit the number of subsounds loaded within a multi-subsound file. If using FSB, then if FMOD_CREATESOUNDEXINFO::inclusionlist is used, this will shuffle subsounds down so that there are not any gaps. It will mean that the indices of the sounds will be different. */
int *inclusionlist; /* [w] Optional. Specify 0 to ignore. In a multi-sample format such as .FSB/.DLS/.SF2 it may be desirable to specify only a subset of sounds to be loaded out of the whole file. This is an array of subsound indices to load into memory when created. */
int inclusionlistnum; /* [w] Optional. Specify 0 to ignore. This is the number of integers contained within the inclusionlist array. */
FMOD_SOUND_PCMREADCALLBACK pcmreadcallback; /* [w] Optional. Specify 0 to ignore. Callback to 'piggyback' on FMOD's read functions and accept or even write PCM data while FMOD is opening the sound. Used for user sounds created with FMOD_OPENUSER or for capturing decoded data as FMOD reads it. */
FMOD_SOUND_PCMSETPOSCALLBACK pcmsetposcallback; /* [w] Optional. Specify 0 to ignore. Callback for when the user calls a seeking function such as Channel::setTime or Channel::setPosition within a multi-sample sound, and for when it is opened.*/
FMOD_SOUND_NONBLOCKCALLBACK nonblockcallback; /* [w] Optional. Specify 0 to ignore. Callback for successful completion, or error while loading a sound that used the FMOD_NONBLOCKING flag.*/
const char *dlsname; /* [w] Optional. Specify 0 to ignore. Filename for a DLS or SF2 sample set when loading a MIDI file. If not specified, on Windows it will attempt to open /windows/system32/drivers/gm.dls or /windows/system32/drivers/etc/gm.dls, on Mac it will attempt to load /System/Library/Components/CoreAudio.component/Contents/Resources/gs_instruments.dls, otherwise the MIDI will fail to open. Current DLS support is for level 1 of the specification. */
const char *encryptionkey; /* [w] Optional. Specify 0 to ignore. Key for encrypted FSB file. Without this key an encrypted FSB file will not load. */
int maxpolyphony; /* [w] Optional. Specify 0 to ignore. For sequenced formats with dynamic channel allocation such as .MID and .IT, this specifies the maximum voice count allowed while playing. .IT defaults to 64. .MID defaults to 32. */
void *userdata; /* [w] Optional. Specify 0 to ignore. This is user data to be attached to the sound during creation. Access via Sound::getUserData. Note: This is not passed to FMOD_FILE_OPENCALLBACK, that is a different userdata that is file specific. */
FMOD_SOUND_TYPE suggestedsoundtype; /* [w] Optional. Specify 0 or FMOD_SOUND_TYPE_UNKNOWN to ignore. Instead of scanning all codec types, use this to speed up loading by making it jump straight to this codec. */
FMOD_FILE_OPENCALLBACK useropen; /* [w] Optional. Specify 0 to ignore. Callback for opening this file. */
FMOD_FILE_CLOSECALLBACK userclose; /* [w] Optional. Specify 0 to ignore. Callback for closing this file. */
FMOD_FILE_READCALLBACK userread; /* [w] Optional. Specify 0 to ignore. Callback for reading from this file. */
FMOD_FILE_SEEKCALLBACK userseek; /* [w] Optional. Specify 0 to ignore. Callback for seeking within this file. */
FMOD_FILE_ASYNCREADCALLBACK userasyncread; /* [w] Optional. Specify 0 to ignore. Callback for seeking within this file. */
FMOD_FILE_ASYNCCANCELCALLBACK userasynccancel; /* [w] Optional. Specify 0 to ignore. Callback for seeking within this file. */
FMOD_SPEAKERMAPTYPE speakermap; /* [w] Optional. Specify 0 to ignore. Use this to differ the way fmod maps multichannel sounds to speakers. See FMOD_SPEAKERMAPTYPE for more. */
FMOD_SOUNDGROUP *initialsoundgroup; /* [w] Optional. Specify 0 to ignore. Specify a sound group if required, to put sound in as it is created. */
unsigned int initialseekposition;/* [w] Optional. Specify 0 to ignore. For streams. Specify an initial position to seek the stream to. */
FMOD_TIMEUNIT initialseekpostype; /* [w] Optional. Specify 0 to ignore. For streams. Specify the time unit for the position set in initialseekposition. */
int ignoresetfilesystem;/* [w] Optional. Specify 0 to ignore. Set to 1 to use fmod's built in file system. Ignores setFileSystem callbacks and also FMOD_CREATESOUNEXINFO file callbacks. Useful for specific cases where you don't want to use your own file system but want to use fmod's file system (ie net streaming). */
int cddaforceaspi; /* [w] Optional. Specify 0 to ignore. For CDDA sounds only - if non-zero use ASPI instead of NTSCSI to access the specified CD/DVD device. */
unsigned int audioqueuepolicy; /* [w] Optional. Specify 0 or FMOD_AUDIOQUEUE_CODECPOLICY_DEFAULT to ignore. Policy used to determine whether hardware or software is used for decoding, see FMOD_AUDIOQUEUE_CODECPOLICY for options (iOS >= 3.0 required, otherwise only hardware is available) */
unsigned int minmidigranularity; /* [w] Optional. Specify 0 to ignore. Allows you to set a minimum desired MIDI mixer granularity. Values smaller than 512 give greater than default accuracy at the cost of more CPU and vice versa. Specify 0 for default (512 samples). */
int nonblockthreadid; /* [w] Optional. Specify 0 to ignore. Specifies a thread index to execute non blocking load on. Allows for up to 5 threads to be used for loading at once. This is to avoid one load blocking another. Maximum value = 4. */
} FMOD_CREATESOUNDEXINFO;
/*
[STRUCTURE]
[
[DESCRIPTION]
Structure defining a reverb environment.<br>
[REMARKS]
Note the default reverb properties are the same as the FMOD_PRESET_GENERIC preset.<br>
Note that integer values that typically range from -10,000 to 1000 are represented in
decibels, and are of a logarithmic scale, not linear, wheras float values are always linear.<br>
<br>
The numerical values listed below are the maximum, minimum and default values for each variable respectively.<br>
<br>
<b>SUPPORTED</b> next to each parameter means the platform the parameter can be set on. Some platforms support all parameters and some don't.<br>
WII means Nintendo Wii hardware reverb (must use FMOD_HARDWARE).<br>
PSP means Playstation Portable hardware reverb (must use FMOD_HARDWARE).<br>
SFX means FMOD SFX software reverb. This works on any platform that uses FMOD_SOFTWARE for loading sounds.<br>
--- means unsupported/deprecated. Will either be removed or supported by SFX in the future.
<br>
Nintendo Wii Notes:<br>
This structure supports only limited parameters, and maps them to the Wii hardware reverb as follows.<br>
DecayTime = 'time'<br>
ReverbDelay = 'predelay'<br>
ModulationDepth = 'damping'<br>
Reflections = 'coloration'<br>
EnvDiffusion = 'crosstalk'<br>
Room = 'mix'<br>
<br>
Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
Members marked with [w] mean the variable can be written to. The user can set the value.<br>
Members marked with [r/w] are either read or write depending on if you are using System::setReverbProperties (w) or System::getReverbProperties (r).
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::setReverbProperties
System::getReverbProperties
FMOD_REVERB_PRESETS
FMOD_REVERB_FLAGS
]
*/
typedef struct FMOD_REVERB_PROPERTIES
{ /* MIN MAX DEFAULT DESCRIPTION */
int Instance; /* [w] 0 3 0 Environment Instance. (SUPPORTED:SFX(4 instances) and Wii (3 instances)) */
int Environment; /* [r/w] -1 25 -1 Sets all listener properties. -1 = OFF. (SUPPORTED:SFX(-1 only)/PSP) */
float EnvDiffusion; /* [r/w] 0.0 1.0 1.0 Environment diffusion (SUPPORTED:WII) */
int Room; /* [r/w] -10000 0 -1000 Room effect level (at mid frequencies) (SUPPORTED:SFX/WII/PSP) */
int RoomHF; /* [r/w] -10000 0 -100 Relative room effect level at high frequencies (SUPPORTED:SFX) */
int RoomLF; /* [r/w] -10000 0 0 Relative room effect level at low frequencies (SUPPORTED:SFX) */
float DecayTime; /* [r/w] 0.1 20.0 1.49 Reverberation decay time at mid frequencies (SUPPORTED:SFX/WII) */
float DecayHFRatio; /* [r/w] 0.1 2.0 0.83 High-frequency to mid-frequency decay time ratio (SUPPORTED:SFX) */
float DecayLFRatio; /* [r/w] 0.1 2.0 1.0 Low-frequency to mid-frequency decay time ratio (SUPPORTED:---) */
int Reflections; /* [r/w] -10000 1000 -2602 Early reflections level relative to room effect (SUPPORTED:SFX/WII) */
float ReflectionsDelay; /* [r/w] 0.0 0.3 0.007 Initial reflection delay time (SUPPORTED:SFX) */
int Reverb; /* [r/w] -10000 2000 200 Late reverberation level relative to room effect (SUPPORTED:SFX) */
float ReverbDelay; /* [r/w] 0.0 0.1 0.011 Late reverberation delay time relative to initial reflection (SUPPORTED:SFX/WII) */
float ModulationTime; /* [r/w] 0.04 4.0 0.25 Modulation time (SUPPORTED:---) */
float ModulationDepth; /* [r/w] 0.0 1.0 0.0 Modulation depth (SUPPORTED:WII) */
float HFReference; /* [r/w] 20.0 20000.0 5000.0 Reference high frequency (hz) (SUPPORTED:SFX) */
float LFReference; /* [r/w] 20.0 1000.0 250.0 Reference low frequency (hz) (SUPPORTED:SFX) */
float Diffusion; /* [r/w] 0.0 100.0 100.0 Value that controls the echo density in the late reverberation decay. (SUPPORTED:SFX) */
float Density; /* [r/w] 0.0 100.0 100.0 Value that controls the modal density in the late reverberation decay (SUPPORTED:SFX) */
unsigned int Flags; /* [r/w] FMOD_REVERB_FLAGS - modifies the behavior of above properties (SUPPORTED:WII) */
} FMOD_REVERB_PROPERTIES;
/*
[DEFINE]
[
[NAME]
FMOD_REVERB_FLAGS
[DESCRIPTION]
Values for the Flags member of the FMOD_REVERB_PROPERTIES structure.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
FMOD_REVERB_PROPERTIES
]
*/
#define FMOD_REVERB_FLAGS_HIGHQUALITYREVERB 0x00000400 /* Wii. Use high quality reverb */
#define FMOD_REVERB_FLAGS_HIGHQUALITYDPL2REVERB 0x00000800 /* Wii. Use high quality DPL2 reverb */
#define FMOD_REVERB_FLAGS_HARDWAREONLY 0x00001000 /* Don't create an SFX reverb for FMOD_SOFTWARE channels, hardware reverb only */
#define FMOD_REVERB_FLAGS_DEFAULT 0x00000000
/* [DEFINE_END] */
/*
[DEFINE]
[
[NAME]
FMOD_REVERB_PRESETS
[DESCRIPTION]
A set of predefined environment PARAMETERS.<br>
These are used to initialize an FMOD_REVERB_PROPERTIES structure statically.<br>
i.e.<br>
FMOD_REVERB_PROPERTIES prop = FMOD_PRESET_GENERIC;
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::setReverbProperties
]
*/
/* Inst Env Diffus Room RoomHF RmLF DecTm DecHF DecLF Refl RefDel Revb RevDel ModTm ModDp HFRef LFRef Diffus Densty FLAGS */
#define FMOD_PRESET_OFF { 0, -1, 1.00f, -10000, -10000, 0, 1.00f, 1.00f, 1.0f, -2602, 0.007f, 200, 0.011f, 0.25f, 0.000f, 5000.0f, 250.0f, 0.0f, 0.0f, 0x33f }
#define FMOD_PRESET_GENERIC { 0, 0, 1.00f, -1000, -100, 0, 1.49f, 0.83f, 1.0f, -2602, 0.007f, 200, 0.011f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_PADDEDCELL { 0, 1, 1.00f, -1000, -6000, 0, 0.17f, 0.10f, 1.0f, -1204, 0.001f, 207, 0.002f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_ROOM { 0, 2, 1.00f, -1000, -454, 0, 0.40f, 0.83f, 1.0f, -1646, 0.002f, 53, 0.003f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_BATHROOM { 0, 3, 1.00f, -1000, -1200, 0, 1.49f, 0.54f, 1.0f, -370, 0.007f, 1030, 0.011f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 60.0f, 0x3f }
#define FMOD_PRESET_LIVINGROOM { 0, 4, 1.00f, -1000, -6000, 0, 0.50f, 0.10f, 1.0f, -1376, 0.003f, -1104, 0.004f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_STONEROOM { 0, 5, 1.00f, -1000, -300, 0, 2.31f, 0.64f, 1.0f, -711, 0.012f, 83, 0.017f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_AUDITORIUM { 0, 6, 1.00f, -1000, -476, 0, 4.32f, 0.59f, 1.0f, -789, 0.020f, -289, 0.030f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_CONCERTHALL { 0, 7, 1.00f, -1000, -500, 0, 3.92f, 0.70f, 1.0f, -1230, 0.020f, -2, 0.029f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_CAVE { 0, 8, 1.00f, -1000, 0, 0, 2.91f, 1.30f, 1.0f, -602, 0.015f, -302, 0.022f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x1f }
#define FMOD_PRESET_ARENA { 0, 9, 1.00f, -1000, -698, 0, 7.24f, 0.33f, 1.0f, -1166, 0.020f, 16, 0.030f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_HANGAR { 0, 10, 1.00f, -1000, -1000, 0, 10.05f, 0.23f, 1.0f, -602, 0.020f, 198, 0.030f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_CARPETTEDHALLWAY { 0, 11, 1.00f, -1000, -4000, 0, 0.30f, 0.10f, 1.0f, -1831, 0.002f, -1630, 0.030f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_HALLWAY { 0, 12, 1.00f, -1000, -300, 0, 1.49f, 0.59f, 1.0f, -1219, 0.007f, 441, 0.011f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_STONECORRIDOR { 0, 13, 1.00f, -1000, -237, 0, 2.70f, 0.79f, 1.0f, -1214, 0.013f, 395, 0.020f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_ALLEY { 0, 14, 0.30f, -1000, -270, 0, 1.49f, 0.86f, 1.0f, -1204, 0.007f, -4, 0.011f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_FOREST { 0, 15, 0.30f, -1000, -3300, 0, 1.49f, 0.54f, 1.0f, -2560, 0.162f, -229, 0.088f, 0.25f, 0.000f, 5000.0f, 250.0f, 79.0f, 100.0f, 0x3f }
#define FMOD_PRESET_CITY { 0, 16, 0.50f, -1000, -800, 0, 1.49f, 0.67f, 1.0f, -2273, 0.007f, -1691, 0.011f, 0.25f, 0.000f, 5000.0f, 250.0f, 50.0f, 100.0f, 0x3f }
#define FMOD_PRESET_MOUNTAINS { 0, 17, 0.27f, -1000, -2500, 0, 1.49f, 0.21f, 1.0f, -2780, 0.300f, -1434, 0.100f, 0.25f, 0.000f, 5000.0f, 250.0f, 27.0f, 100.0f, 0x1f }
#define FMOD_PRESET_QUARRY { 0, 18, 1.00f, -1000, -1000, 0, 1.49f, 0.83f, 1.0f, -10000, 0.061f, 500, 0.025f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
#define FMOD_PRESET_PLAIN { 0, 19, 0.21f, -1000, -2000, 0, 1.49f, 0.50f, 1.0f, -2466, 0.179f, -1926, 0.100f, 0.25f, 0.000f, 5000.0f, 250.0f, 21.0f, 100.0f, 0x3f }
#define FMOD_PRESET_PARKINGLOT { 0, 20, 1.00f, -1000, 0, 0, 1.65f, 1.50f, 1.0f, -1363, 0.008f, -1153, 0.012f, 0.25f, 0.000f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x1f }
#define FMOD_PRESET_SEWERPIPE { 0, 21, 0.80f, -1000, -1000, 0, 2.81f, 0.14f, 1.0f, 429, 0.014f, 1023, 0.021f, 0.25f, 0.000f, 5000.0f, 250.0f, 80.0f, 60.0f, 0x3f }
#define FMOD_PRESET_UNDERWATER { 0, 22, 1.00f, -1000, -4000, 0, 1.49f, 0.10f, 1.0f, -449, 0.007f, 1700, 0.011f, 1.18f, 0.348f, 5000.0f, 250.0f, 100.0f, 100.0f, 0x3f }
/* PlayStation Portable Only presets */
#define FMOD_PRESET_PSP_ROOM { 0, 1, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_STUDIO_A { 0, 2, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_STUDIO_B { 0, 3, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_STUDIO_C { 0, 4, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_HALL { 0, 5, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_SPACE { 0, 6, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_ECHO { 0, 7, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_DELAY { 0, 8, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
#define FMOD_PRESET_PSP_PIPE { 0, 9, 0, 0, 0, 0, 0.0f, 0.0f, 0.0f, 0, 0.000f, 0, 0.000f, 0.00f, 0.000f, 0000.0f, 0.0f, 0.0f, 0.0f, 0x31f }
/* [DEFINE_END] */
/*
[STRUCTURE]
[
[DESCRIPTION]
Structure defining the properties for a reverb source, related to a FMOD channel.<br>
<br>
Note the default reverb properties are the same as the FMOD_PRESET_GENERIC preset.<br>
Note that integer values that typically range from -10,000 to 1000 are represented in
decibels, and are of a logarithmic scale, not linear, wheras float values are typically linear.<br>
PORTABILITY: Each member has the platform it supports in braces ie (win32/wii).<br>
<br>
The numerical values listed below are the maximum, minimum and default values for each variable respectively.<br>
[REMARKS]
<b>SUPPORTED</b> next to each parameter means the platform the parameter can be set on. Some platforms support all parameters and some don't.<br>
WII means Nintendo Wii hardware reverb (must use FMOD_HARDWARE).<br>
PSP means Playstation Portable hardware reverb (must use FMOD_HARDWARE).<br>
SFX means FMOD SFX software reverb. This works on any platform that uses FMOD_SOFTWARE for loading sounds.<br>
--- means unsupported/deprecated. Will either be removed or supported by SFX in the future.
<br>
<br>
<b>'ConnectionPoint' Parameter.</b> This parameter is for the FMOD software reverb only (known as SFX in the list above).<br>
By default the dsp network connection for a channel and its reverb is between the 'SFX Reverb' unit, and the channel's wavetable/resampler/dspcodec/oscillator unit (the unit below the channel DSP head). NULL can be used for this parameter to make it use this default behaviour.<br>
This parameter allows the user to connect the SFX reverb to somewhere else internally, for example the channel DSP head, or a related channelgroup. The event system uses this so that it can have the output of an event going to the reverb, instead of just the output of the event's channels (thereby ignoring event effects/submixes etc).<br>
Do not use if you are unaware of DSP network connection issues. Leave it at the default of NULL instead.<br>
<br>
Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
Members marked with [w] mean the variable can be written to. The user can set the value.<br>
Members marked with [r/w] are either read or write depending on if you are using Channel::setReverbProperties (w) or Channel::getReverbProperties (r).
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
Channel::setReverbProperties
Channel::getReverbProperties
FMOD_REVERB_CHANNELFLAGS
]
*/
typedef struct FMOD_REVERB_CHANNELPROPERTIES
{ /* MIN MAX DEFAULT DESCRIPTION */
int Direct; /* [r/w] -10000 1000 0 Direct path level (SUPPORTED:SFX) */
int Room; /* [r/w] -10000 1000 0 Room effect level (SUPPORTED:SFX) */
unsigned int Flags; /* [r/w] FMOD_REVERB_CHANNELFLAGS - modifies the behavior of properties (SUPPORTED:SFX) */
FMOD_DSP *ConnectionPoint; /* [r/w] See remarks. DSP network location to connect reverb for this channel. (SUPPORTED:SFX).*/
} FMOD_REVERB_CHANNELPROPERTIES;
/*
[DEFINE]
[
[NAME]
FMOD_REVERB_CHANNELFLAGS
[DESCRIPTION]
Values for the Flags member of the FMOD_REVERB_CHANNELPROPERTIES structure.
[REMARKS]
For SFX Reverb, there is support for multiple reverb environments.<br>
Use FMOD_REVERB_CHANNELFLAGS_ENVIRONMENT0 to FMOD_REVERB_CHANNELFLAGS_ENVIRONMENT3 in the flags member
of FMOD_REVERB_CHANNELPROPERTIES to specify which environment instance(s) to target. <br>
- If you do not specify any instance the first reverb instance will be used.<br>
- If you specify more than one instance with getReverbProperties, the first instance will be used.<br>
- If you specify more than one instance with setReverbProperties, it will set more than 1 instance at once.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
FMOD_REVERB_CHANNELPROPERTIES
]
*/
#define FMOD_REVERB_CHANNELFLAGS_INSTANCE0 0x00000010 /* SFX/Wii. Specify channel to target reverb instance 0. Default target. */
#define FMOD_REVERB_CHANNELFLAGS_INSTANCE1 0x00000020 /* SFX/Wii. Specify channel to target reverb instance 1. */
#define FMOD_REVERB_CHANNELFLAGS_INSTANCE2 0x00000040 /* SFX/Wii. Specify channel to target reverb instance 2. */
#define FMOD_REVERB_CHANNELFLAGS_INSTANCE3 0x00000080 /* SFX. Specify channel to target reverb instance 3. */
#define FMOD_REVERB_CHANNELFLAGS_DEFAULT FMOD_REVERB_CHANNELFLAGS_INSTANCE0
/* [DEFINE_END] */
/*
[STRUCTURE]
[
[DESCRIPTION]
Settings for advanced features like configuring memory and cpu usage for the FMOD_CREATECOMPRESSEDSAMPLE feature.
[REMARKS]
maxMPEGcodecs / maxADPCMcodecs / maxXMAcodecs will determine the maximum cpu usage of playing realtime samples. Use this to lower potential excess cpu usage and also control memory usage.<br>
<br>
maxPCMcodecs is for use with PS3 only. It will determine the maximum number of PCM voices that can be played at once. This includes streams of any format and all sounds created
*without* the FMOD_CREATECOMPRESSEDSAMPLE flag.
<br>
Memory will be allocated for codecs 'up front' (during System::init) if these values are specified as non zero. If any are zero, it allocates memory for the codec whenever a file of the type in question is loaded. So if maxMPEGcodecs is 0 for example, it will allocate memory for the mpeg codecs the first time an mp3 is loaded or an mp3 based .FSB file is loaded.<br>
<br>
Due to inefficient encoding techniques on certain .wav based ADPCM files, FMOD can can need an extra 29720 bytes per codec. This means for lowest memory consumption. Use FSB as it uses an optimal/small ADPCM block size.<br>
<br>
Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
Members marked with [w] mean the variable can be written to. The user can set the value.<br>
Members marked with [r/w] are either read or write depending on if you are using System::setAdvancedSettings (w) or System::getAdvancedSettings (r).
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::setAdvancedSettings
System::getAdvancedSettings
System::init
FMOD_MODE
]
*/
typedef struct FMOD_ADVANCEDSETTINGS
{
int cbsize; /* [w] Size of this structure. Use sizeof(FMOD_ADVANCEDSETTINGS) NOTE: This must be set before calling System::getAdvancedSettings! */
int maxMPEGcodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. Mpeg codecs consume 21,684 bytes per instance and this number will determine how many mpeg channels can be played simultaneously. Default = 32. */
int maxADPCMcodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. ADPCM codecs consume 2,136 bytes per instance and this number will determine how many ADPCM channels can be played simultaneously. Default = 32. */
int maxXMAcodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. XMA codecs consume 14,836 bytes per instance and this number will determine how many XMA channels can be played simultaneously. Default = 32. */
int maxCELTcodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. CELT codecs consume 11,500 bytes per instance and this number will determine how many CELT channels can be played simultaneously. Default = 32. */
int maxVORBIScodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. Vorbis codecs consume 12,000 bytes per instance and this number will determine how many Vorbis channels can be played simultaneously. Default = 32. */
int maxPCMcodecs; /* [r/w] Optional. Specify 0 to ignore. For use with PS3 only. PCM codecs consume 12,672 bytes per instance and this number will determine how many streams and PCM voices can be played simultaneously. Default = 16. */
int ASIONumChannels; /* [r/w] Optional. Specify 0 to ignore. Number of channels available on the ASIO device. */
char **ASIOChannelList; /* [r/w] Optional. Specify 0 to ignore. Pointer to an array of strings (number of entries defined by ASIONumChannels) with ASIO channel names. */
FMOD_SPEAKER *ASIOSpeakerList; /* [r/w] Optional. Specify 0 to ignore. Pointer to a list of speakers that the ASIO channels map to. This can be called after System::init to remap ASIO output. */
int max3DReverbDSPs; /* [r/w] Optional. Specify 0 to ignore. The max number of 3d reverb DSP's in the system. (NOTE: CURRENTLY DISABLED / UNUSED) */
float HRTFMinAngle; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_HRTF_LOWPASS. The angle range (0-360) of a 3D sound in relation to the listener, at which the HRTF function begins to have an effect. 0 = in front of the listener. 180 = from 90 degrees to the left of the listener to 90 degrees to the right. 360 = behind the listener. Default = 180.0. */
float HRTFMaxAngle; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_HRTF_LOWPASS. The angle range (0-360) of a 3D sound in relation to the listener, at which the HRTF function has maximum effect. 0 = front of the listener. 180 = from 90 degrees to the left of the listener to 90 degrees to the right. 360 = behind the listener. Default = 360.0. */
float HRTFFreq; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_HRTF_LOWPASS. The cutoff frequency of the HRTF's lowpass filter function when at maximum effect. (i.e. at HRTFMaxAngle). Default = 4000.0. */
float vol0virtualvol; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_VOL0_BECOMES_VIRTUAL. If this flag is used, and the volume is 0.0, then the sound will become virtual. Use this value to raise the threshold to a different point where a sound goes virtual. */
int eventqueuesize; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD Event system only. Specifies the number of slots available for simultaneous non blocking loads, across all threads. Default = 32. */
unsigned int defaultDecodeBufferSize; /* [r/w] Optional. Specify 0 to ignore. For streams. This determines the default size of the double buffer (in milliseconds) that a stream uses. Default = 400ms */
char *debugLogFilename; /* [r/w] Optional. Specify 0 to ignore. Gives fmod's logging system a path/filename. Normally the log is placed in the same directory as the executable and called fmod.log. When using System::getAdvancedSettings, provide at least 256 bytes of memory to copy into. */
unsigned short profileport; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_ENABLE_PROFILE. Specify the port to listen on for connections by the profiler application. */
unsigned int geometryMaxFadeTime; /* [r/w] Optional. Specify 0 to ignore. The maximum time in miliseconds it takes for a channel to fade to the new level when its occlusion changes. */
unsigned int maxSpectrumWaveDataBuffers; /* [r/w] Optional. Specify 0 to ignore. Tells System::init to allocate a pool of wavedata/spectrum buffers to prevent memory fragmentation, any additional buffers will be allocated normally. */
unsigned int musicSystemCacheDelay; /* [r/w] Optional. Specify 0 to ignore. The delay the music system should allow for loading a sample from disk (in milliseconds). Default = 400 ms. */
float distanceFilterCenterFreq; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_DISTANCE_FILTERING. The default center frequency in Hz for the distance filtering effect. Default = 1500.0. */
} FMOD_ADVANCEDSETTINGS;
/*
[ENUM]
[
[DESCRIPTION]
Special channel index values for FMOD functions.
[REMARKS]
To get 'all' of the channels, use System::getMasterChannelGroup.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox360, PlayStation Portable, PlayStation 3, Wii, iPhone, 3GS, NGP, Android
[SEE_ALSO]
System::playSound
System::playDSP
System::getChannel
System::getMasterChannelGroup
]
*/
typedef enum
{
FMOD_CHANNEL_FREE = -1, /* For a channel index, FMOD chooses a free voice using the priority system. */
FMOD_CHANNEL_REUSE = -2 /* For a channel index, re-use the channel handle that was passed in. */
} FMOD_CHANNELINDEX;
#include "fmod_codec.h"
#include "fmod_dsp.h"
#include "fmod_memoryinfo.h"
/* ========================================================================================== */
/* FUNCTION PROTOTYPES */
/* ========================================================================================== */
#ifdef __cplusplus
extern "C"
{
#endif
/*
FMOD global system functions (optional).
*/
FMOD_RESULT F_API FMOD_Memory_Initialize (void *poolmem, int poollen, FMOD_MEMORY_ALLOCCALLBACK useralloc, FMOD_MEMORY_REALLOCCALLBACK userrealloc, FMOD_MEMORY_FREECALLBACK userfree, FMOD_MEMORY_TYPE memtypeflags);
FMOD_RESULT F_API FMOD_Memory_GetStats (int *currentalloced, int *maxalloced, FMOD_BOOL blocking);
FMOD_RESULT F_API FMOD_Debug_SetLevel (FMOD_DEBUGLEVEL level);
FMOD_RESULT F_API FMOD_Debug_GetLevel (FMOD_DEBUGLEVEL *level);
FMOD_RESULT F_API FMOD_File_SetDiskBusy (int busy);
FMOD_RESULT F_API FMOD_File_GetDiskBusy (int *busy);
/*
FMOD System factory functions. Use this to create an FMOD System Instance. below you will see FMOD_System_Init/Close to get started.
*/
FMOD_RESULT F_API FMOD_System_Create (FMOD_SYSTEM **system);
FMOD_RESULT F_API FMOD_System_Release (FMOD_SYSTEM *system);
/*$ preserve end $*/
/*
'System' API
*/
/*
Pre-init functions.
*/
FMOD_RESULT F_API FMOD_System_SetOutput (FMOD_SYSTEM *system, FMOD_OUTPUTTYPE output);
FMOD_RESULT F_API FMOD_System_GetOutput (FMOD_SYSTEM *system, FMOD_OUTPUTTYPE *output);
FMOD_RESULT F_API FMOD_System_GetNumDrivers (FMOD_SYSTEM *system, int *numdrivers);
FMOD_RESULT F_API FMOD_System_GetDriverInfo (FMOD_SYSTEM *system, int id, char *name, int namelen, FMOD_GUID *guid);
FMOD_RESULT F_API FMOD_System_GetDriverInfoW (FMOD_SYSTEM *system, int id, short *name, int namelen, FMOD_GUID *guid);
FMOD_RESULT F_API FMOD_System_GetDriverCaps (FMOD_SYSTEM *system, int id, FMOD_CAPS *caps, int *controlpaneloutputrate, FMOD_SPEAKERMODE *controlpanelspeakermode);
FMOD_RESULT F_API FMOD_System_SetDriver (FMOD_SYSTEM *system, int driver);
FMOD_RESULT F_API FMOD_System_GetDriver (FMOD_SYSTEM *system, int *driver);
FMOD_RESULT F_API FMOD_System_SetHardwareChannels (FMOD_SYSTEM *system, int numhardwarechannels);
FMOD_RESULT F_API FMOD_System_SetSoftwareChannels (FMOD_SYSTEM *system, int numsoftwarechannels);
FMOD_RESULT F_API FMOD_System_GetSoftwareChannels (FMOD_SYSTEM *system, int *numsoftwarechannels);
FMOD_RESULT F_API FMOD_System_SetSoftwareFormat (FMOD_SYSTEM *system, int samplerate, FMOD_SOUND_FORMAT format, int numoutputchannels, int maxinputchannels, FMOD_DSP_RESAMPLER resamplemethod);
FMOD_RESULT F_API FMOD_System_GetSoftwareFormat (FMOD_SYSTEM *system, int *samplerate, FMOD_SOUND_FORMAT *format, int *numoutputchannels, int *maxinputchannels, FMOD_DSP_RESAMPLER *resamplemethod, int *bits);
FMOD_RESULT F_API FMOD_System_SetDSPBufferSize (FMOD_SYSTEM *system, unsigned int bufferlength, int numbuffers);
FMOD_RESULT F_API FMOD_System_GetDSPBufferSize (FMOD_SYSTEM *system, unsigned int *bufferlength, int *numbuffers);
FMOD_RESULT F_API FMOD_System_SetFileSystem (FMOD_SYSTEM *system, FMOD_FILE_OPENCALLBACK useropen, FMOD_FILE_CLOSECALLBACK userclose, FMOD_FILE_READCALLBACK userread, FMOD_FILE_SEEKCALLBACK userseek, FMOD_FILE_ASYNCREADCALLBACK userasyncread, FMOD_FILE_ASYNCCANCELCALLBACK userasynccancel, int blockalign);
FMOD_RESULT F_API FMOD_System_AttachFileSystem (FMOD_SYSTEM *system, FMOD_FILE_OPENCALLBACK useropen, FMOD_FILE_CLOSECALLBACK userclose, FMOD_FILE_READCALLBACK userread, FMOD_FILE_SEEKCALLBACK userseek);
FMOD_RESULT F_API FMOD_System_SetAdvancedSettings (FMOD_SYSTEM *system, FMOD_ADVANCEDSETTINGS *settings);
FMOD_RESULT F_API FMOD_System_GetAdvancedSettings (FMOD_SYSTEM *system, FMOD_ADVANCEDSETTINGS *settings);
FMOD_RESULT F_API FMOD_System_SetSpeakerMode (FMOD_SYSTEM *system, FMOD_SPEAKERMODE speakermode);
FMOD_RESULT F_API FMOD_System_GetSpeakerMode (FMOD_SYSTEM *system, FMOD_SPEAKERMODE *speakermode);
FMOD_RESULT F_API FMOD_System_SetCallback (FMOD_SYSTEM *system, FMOD_SYSTEM_CALLBACK callback);
/*
Plug-in support
*/
FMOD_RESULT F_API FMOD_System_SetPluginPath (FMOD_SYSTEM *system, const char *path);
FMOD_RESULT F_API FMOD_System_LoadPlugin (FMOD_SYSTEM *system, const char *filename, unsigned int *handle, unsigned int priority);
FMOD_RESULT F_API FMOD_System_UnloadPlugin (FMOD_SYSTEM *system, unsigned int handle);
FMOD_RESULT F_API FMOD_System_GetNumPlugins (FMOD_SYSTEM *system, FMOD_PLUGINTYPE plugintype, int *numplugins);
FMOD_RESULT F_API FMOD_System_GetPluginHandle (FMOD_SYSTEM *system, FMOD_PLUGINTYPE plugintype, int index, unsigned int *handle);
FMOD_RESULT F_API FMOD_System_GetPluginInfo (FMOD_SYSTEM *system, unsigned int handle, FMOD_PLUGINTYPE *plugintype, char *name, int namelen, unsigned int *version);
FMOD_RESULT F_API FMOD_System_SetOutputByPlugin (FMOD_SYSTEM *system, unsigned int handle);
FMOD_RESULT F_API FMOD_System_GetOutputByPlugin (FMOD_SYSTEM *system, unsigned int *handle);
FMOD_RESULT F_API FMOD_System_CreateDSPByPlugin (FMOD_SYSTEM *system, unsigned int handle, FMOD_DSP **dsp);
FMOD_RESULT F_API FMOD_System_RegisterCodec (FMOD_SYSTEM *system, FMOD_CODEC_DESCRIPTION *description, unsigned int *handle, unsigned int priority);
FMOD_RESULT F_API FMOD_System_RegisterDSP (FMOD_SYSTEM *system, FMOD_DSP_DESCRIPTION *description, unsigned int *handle);
/*
Init/Close
*/
FMOD_RESULT F_API FMOD_System_Init (FMOD_SYSTEM *system, int maxchannels, FMOD_INITFLAGS flags, void *extradriverdata);
FMOD_RESULT F_API FMOD_System_Close (FMOD_SYSTEM *system);
/*
General post-init system functions
*/
FMOD_RESULT F_API FMOD_System_Update (FMOD_SYSTEM *system);
FMOD_RESULT F_API FMOD_System_Set3DSettings (FMOD_SYSTEM *system, float dopplerscale, float distancefactor, float rolloffscale);
FMOD_RESULT F_API FMOD_System_Get3DSettings (FMOD_SYSTEM *system, float *dopplerscale, float *distancefactor, float *rolloffscale);
FMOD_RESULT F_API FMOD_System_Set3DNumListeners (FMOD_SYSTEM *system, int numlisteners);
FMOD_RESULT F_API FMOD_System_Get3DNumListeners (FMOD_SYSTEM *system, int *numlisteners);
FMOD_RESULT F_API FMOD_System_Set3DListenerAttributes(FMOD_SYSTEM *system, int listener, const FMOD_VECTOR *pos, const FMOD_VECTOR *vel, const FMOD_VECTOR *forward, const FMOD_VECTOR *up);
FMOD_RESULT F_API FMOD_System_Get3DListenerAttributes(FMOD_SYSTEM *system, int listener, FMOD_VECTOR *pos, FMOD_VECTOR *vel, FMOD_VECTOR *forward, FMOD_VECTOR *up);
FMOD_RESULT F_API FMOD_System_Set3DRolloffCallback (FMOD_SYSTEM *system, FMOD_3D_ROLLOFFCALLBACK callback);
FMOD_RESULT F_API FMOD_System_Set3DSpeakerPosition (FMOD_SYSTEM *system, FMOD_SPEAKER speaker, float x, float y, FMOD_BOOL active);
FMOD_RESULT F_API FMOD_System_Get3DSpeakerPosition (FMOD_SYSTEM *system, FMOD_SPEAKER speaker, float *x, float *y, FMOD_BOOL *active);
FMOD_RESULT F_API FMOD_System_SetStreamBufferSize (FMOD_SYSTEM *system, unsigned int filebuffersize, FMOD_TIMEUNIT filebuffersizetype);
FMOD_RESULT F_API FMOD_System_GetStreamBufferSize (FMOD_SYSTEM *system, unsigned int *filebuffersize, FMOD_TIMEUNIT *filebuffersizetype);
/*
System information functions.
*/
FMOD_RESULT F_API FMOD_System_GetVersion (FMOD_SYSTEM *system, unsigned int *version);
FMOD_RESULT F_API FMOD_System_GetOutputHandle (FMOD_SYSTEM *system, void **handle);
FMOD_RESULT F_API FMOD_System_GetChannelsPlaying (FMOD_SYSTEM *system, int *channels);
FMOD_RESULT F_API FMOD_System_GetHardwareChannels (FMOD_SYSTEM *system, int *numhardwarechannels);
FMOD_RESULT F_API FMOD_System_GetCPUUsage (FMOD_SYSTEM *system, float *dsp, float *stream, float *geometry, float *update, float *total);
FMOD_RESULT F_API FMOD_System_GetSoundRAM (FMOD_SYSTEM *system, int *currentalloced, int *maxalloced, int *total);
FMOD_RESULT F_API FMOD_System_GetNumCDROMDrives (FMOD_SYSTEM *system, int *numdrives);
FMOD_RESULT F_API FMOD_System_GetCDROMDriveName (FMOD_SYSTEM *system, int drive, char *drivename, int drivenamelen, char *scsiname, int scsinamelen, char *devicename, int devicenamelen);
FMOD_RESULT F_API FMOD_System_GetSpectrum (FMOD_SYSTEM *system, float *spectrumarray, int numvalues, int channeloffset, FMOD_DSP_FFT_WINDOW windowtype);
FMOD_RESULT F_API FMOD_System_GetWaveData (FMOD_SYSTEM *system, float *wavearray, int numvalues, int channeloffset);
/*
Sound/DSP/Channel/FX creation and retrieval.
*/
FMOD_RESULT F_API FMOD_System_CreateSound (FMOD_SYSTEM *system, const char *name_or_data, FMOD_MODE mode, FMOD_CREATESOUNDEXINFO *exinfo, FMOD_SOUND **sound);
FMOD_RESULT F_API FMOD_System_CreateStream (FMOD_SYSTEM *system, const char *name_or_data, FMOD_MODE mode, FMOD_CREATESOUNDEXINFO *exinfo, FMOD_SOUND **sound);
FMOD_RESULT F_API FMOD_System_CreateDSP (FMOD_SYSTEM *system, FMOD_DSP_DESCRIPTION *description, FMOD_DSP **dsp);
FMOD_RESULT F_API FMOD_System_CreateDSPByType (FMOD_SYSTEM *system, FMOD_DSP_TYPE type, FMOD_DSP **dsp);
FMOD_RESULT F_API FMOD_System_CreateChannelGroup (FMOD_SYSTEM *system, const char *name, FMOD_CHANNELGROUP **channelgroup);
FMOD_RESULT F_API FMOD_System_CreateSoundGroup (FMOD_SYSTEM *system, const char *name, FMOD_SOUNDGROUP **soundgroup);
FMOD_RESULT F_API FMOD_System_CreateReverb (FMOD_SYSTEM *system, FMOD_REVERB **reverb);
FMOD_RESULT F_API FMOD_System_PlaySound (FMOD_SYSTEM *system, FMOD_CHANNELINDEX channelid, FMOD_SOUND *sound, FMOD_BOOL paused, FMOD_CHANNEL **channel);
FMOD_RESULT F_API FMOD_System_PlayDSP (FMOD_SYSTEM *system, FMOD_CHANNELINDEX channelid, FMOD_DSP *dsp, FMOD_BOOL paused, FMOD_CHANNEL **channel);
FMOD_RESULT F_API FMOD_System_GetChannel (FMOD_SYSTEM *system, int channelid, FMOD_CHANNEL **channel);
FMOD_RESULT F_API FMOD_System_GetMasterChannelGroup (FMOD_SYSTEM *system, FMOD_CHANNELGROUP **channelgroup);
FMOD_RESULT F_API FMOD_System_GetMasterSoundGroup (FMOD_SYSTEM *system, FMOD_SOUNDGROUP **soundgroup);
/*
Reverb API
*/
FMOD_RESULT F_API FMOD_System_SetReverbProperties (FMOD_SYSTEM *system, const FMOD_REVERB_PROPERTIES *prop);
FMOD_RESULT F_API FMOD_System_GetReverbProperties (FMOD_SYSTEM *system, FMOD_REVERB_PROPERTIES *prop);
FMOD_RESULT F_API FMOD_System_SetReverbAmbientProperties(FMOD_SYSTEM *system, FMOD_REVERB_PROPERTIES *prop);
FMOD_RESULT F_API FMOD_System_GetReverbAmbientProperties(FMOD_SYSTEM *system, FMOD_REVERB_PROPERTIES *prop);
/*
System level DSP access.
*/
FMOD_RESULT F_API FMOD_System_GetDSPHead (FMOD_SYSTEM *system, FMOD_DSP **dsp);
FMOD_RESULT F_API FMOD_System_AddDSP (FMOD_SYSTEM *system, FMOD_DSP *dsp, FMOD_DSPCONNECTION **connection);
FMOD_RESULT F_API FMOD_System_LockDSP (FMOD_SYSTEM *system);
FMOD_RESULT F_API FMOD_System_UnlockDSP (FMOD_SYSTEM *system);
FMOD_RESULT F_API FMOD_System_GetDSPClock (FMOD_SYSTEM *system, unsigned int *hi, unsigned int *lo);
/*
Recording API.
*/
FMOD_RESULT F_API FMOD_System_GetRecordNumDrivers (FMOD_SYSTEM *system, int *numdrivers);
FMOD_RESULT F_API FMOD_System_GetRecordDriverInfo (FMOD_SYSTEM *system, int id, char *name, int namelen, FMOD_GUID *guid);
FMOD_RESULT F_API FMOD_System_GetRecordDriverInfoW (FMOD_SYSTEM *system, int id, short *name, int namelen, FMOD_GUID *guid);
FMOD_RESULT F_API FMOD_System_GetRecordDriverCaps (FMOD_SYSTEM *system, int id, FMOD_CAPS *caps, int *minfrequency, int *maxfrequency);
FMOD_RESULT F_API FMOD_System_GetRecordPosition (FMOD_SYSTEM *system, int id, unsigned int *position);
FMOD_RESULT F_API FMOD_System_RecordStart (FMOD_SYSTEM *system, int id, FMOD_SOUND *sound, FMOD_BOOL loop);
FMOD_RESULT F_API FMOD_System_RecordStop (FMOD_SYSTEM *system, int id);
FMOD_RESULT F_API FMOD_System_IsRecording (FMOD_SYSTEM *system, int id, FMOD_BOOL *recording);
/*
Geometry API.
*/
FMOD_RESULT F_API FMOD_System_CreateGeometry (FMOD_SYSTEM *system, int maxpolygons, int maxvertices, FMOD_GEOMETRY **geometry);
FMOD_RESULT F_API FMOD_System_SetGeometrySettings (FMOD_SYSTEM *system, float maxworldsize);
FMOD_RESULT F_API FMOD_System_GetGeometrySettings (FMOD_SYSTEM *system, float *maxworldsize);
FMOD_RESULT F_API FMOD_System_LoadGeometry (FMOD_SYSTEM *system, const void *data, int datasize, FMOD_GEOMETRY **geometry);
FMOD_RESULT F_API FMOD_System_GetGeometryOcclusion (FMOD_SYSTEM *system, const FMOD_VECTOR *listener, const FMOD_VECTOR *source, float *direct, float *reverb);
/*
Network functions.
*/
FMOD_RESULT F_API FMOD_System_SetNetworkProxy (FMOD_SYSTEM *system, const char *proxy);
FMOD_RESULT F_API FMOD_System_GetNetworkProxy (FMOD_SYSTEM *system, char *proxy, int proxylen);
FMOD_RESULT F_API FMOD_System_SetNetworkTimeout (FMOD_SYSTEM *system, int timeout);
FMOD_RESULT F_API FMOD_System_GetNetworkTimeout (FMOD_SYSTEM *system, int *timeout);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_System_SetUserData (FMOD_SYSTEM *system, void *userdata);
FMOD_RESULT F_API FMOD_System_GetUserData (FMOD_SYSTEM *system, void **userdata);
FMOD_RESULT F_API FMOD_System_GetMemoryInfo (FMOD_SYSTEM *system, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'Sound' API
*/
FMOD_RESULT F_API FMOD_Sound_Release (FMOD_SOUND *sound);
FMOD_RESULT F_API FMOD_Sound_GetSystemObject (FMOD_SOUND *sound, FMOD_SYSTEM **system);
/*
Standard sound manipulation functions.
*/
FMOD_RESULT F_API FMOD_Sound_Lock (FMOD_SOUND *sound, unsigned int offset, unsigned int length, void **ptr1, void **ptr2, unsigned int *len1, unsigned int *len2);
FMOD_RESULT F_API FMOD_Sound_Unlock (FMOD_SOUND *sound, void *ptr1, void *ptr2, unsigned int len1, unsigned int len2);
FMOD_RESULT F_API FMOD_Sound_SetDefaults (FMOD_SOUND *sound, float frequency, float volume, float pan, int priority);
FMOD_RESULT F_API FMOD_Sound_GetDefaults (FMOD_SOUND *sound, float *frequency, float *volume, float *pan, int *priority);
FMOD_RESULT F_API FMOD_Sound_SetVariations (FMOD_SOUND *sound, float frequencyvar, float volumevar, float panvar);
FMOD_RESULT F_API FMOD_Sound_GetVariations (FMOD_SOUND *sound, float *frequencyvar, float *volumevar, float *panvar);
FMOD_RESULT F_API FMOD_Sound_Set3DMinMaxDistance (FMOD_SOUND *sound, float min, float max);
FMOD_RESULT F_API FMOD_Sound_Get3DMinMaxDistance (FMOD_SOUND *sound, float *min, float *max);
FMOD_RESULT F_API FMOD_Sound_Set3DConeSettings (FMOD_SOUND *sound, float insideconeangle, float outsideconeangle, float outsidevolume);
FMOD_RESULT F_API FMOD_Sound_Get3DConeSettings (FMOD_SOUND *sound, float *insideconeangle, float *outsideconeangle, float *outsidevolume);
FMOD_RESULT F_API FMOD_Sound_Set3DCustomRolloff (FMOD_SOUND *sound, FMOD_VECTOR *points, int numpoints);
FMOD_RESULT F_API FMOD_Sound_Get3DCustomRolloff (FMOD_SOUND *sound, FMOD_VECTOR **points, int *numpoints);
FMOD_RESULT F_API FMOD_Sound_SetSubSound (FMOD_SOUND *sound, int index, FMOD_SOUND *subsound);
FMOD_RESULT F_API FMOD_Sound_GetSubSound (FMOD_SOUND *sound, int index, FMOD_SOUND **subsound);
FMOD_RESULT F_API FMOD_Sound_SetSubSoundSentence (FMOD_SOUND *sound, int *subsoundlist, int numsubsounds);
FMOD_RESULT F_API FMOD_Sound_GetName (FMOD_SOUND *sound, char *name, int namelen);
FMOD_RESULT F_API FMOD_Sound_GetLength (FMOD_SOUND *sound, unsigned int *length, FMOD_TIMEUNIT lengthtype);
FMOD_RESULT F_API FMOD_Sound_GetFormat (FMOD_SOUND *sound, FMOD_SOUND_TYPE *type, FMOD_SOUND_FORMAT *format, int *channels, int *bits);
FMOD_RESULT F_API FMOD_Sound_GetNumSubSounds (FMOD_SOUND *sound, int *numsubsounds);
FMOD_RESULT F_API FMOD_Sound_GetNumTags (FMOD_SOUND *sound, int *numtags, int *numtagsupdated);
FMOD_RESULT F_API FMOD_Sound_GetTag (FMOD_SOUND *sound, const char *name, int index, FMOD_TAG *tag);
FMOD_RESULT F_API FMOD_Sound_GetOpenState (FMOD_SOUND *sound, FMOD_OPENSTATE *openstate, unsigned int *percentbuffered, FMOD_BOOL *starving, FMOD_BOOL *diskbusy);
FMOD_RESULT F_API FMOD_Sound_ReadData (FMOD_SOUND *sound, void *buffer, unsigned int lenbytes, unsigned int *read);
FMOD_RESULT F_API FMOD_Sound_SeekData (FMOD_SOUND *sound, unsigned int pcm);
FMOD_RESULT F_API FMOD_Sound_SetSoundGroup (FMOD_SOUND *sound, FMOD_SOUNDGROUP *soundgroup);
FMOD_RESULT F_API FMOD_Sound_GetSoundGroup (FMOD_SOUND *sound, FMOD_SOUNDGROUP **soundgroup);
/*
Synchronization point API. These points can come from markers embedded in wav files, and can also generate channel callbacks.
*/
FMOD_RESULT F_API FMOD_Sound_GetNumSyncPoints (FMOD_SOUND *sound, int *numsyncpoints);
FMOD_RESULT F_API FMOD_Sound_GetSyncPoint (FMOD_SOUND *sound, int index, FMOD_SYNCPOINT **point);
FMOD_RESULT F_API FMOD_Sound_GetSyncPointInfo (FMOD_SOUND *sound, FMOD_SYNCPOINT *point, char *name, int namelen, unsigned int *offset, FMOD_TIMEUNIT offsettype);
FMOD_RESULT F_API FMOD_Sound_AddSyncPoint (FMOD_SOUND *sound, unsigned int offset, FMOD_TIMEUNIT offsettype, const char *name, FMOD_SYNCPOINT **point);
FMOD_RESULT F_API FMOD_Sound_DeleteSyncPoint (FMOD_SOUND *sound, FMOD_SYNCPOINT *point);
/*
Functions also in Channel class but here they are the 'default' to save having to change it in Channel all the time.
*/
FMOD_RESULT F_API FMOD_Sound_SetMode (FMOD_SOUND *sound, FMOD_MODE mode);
FMOD_RESULT F_API FMOD_Sound_GetMode (FMOD_SOUND *sound, FMOD_MODE *mode);
FMOD_RESULT F_API FMOD_Sound_SetLoopCount (FMOD_SOUND *sound, int loopcount);
FMOD_RESULT F_API FMOD_Sound_GetLoopCount (FMOD_SOUND *sound, int *loopcount);
FMOD_RESULT F_API FMOD_Sound_SetLoopPoints (FMOD_SOUND *sound, unsigned int loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int loopend, FMOD_TIMEUNIT loopendtype);
FMOD_RESULT F_API FMOD_Sound_GetLoopPoints (FMOD_SOUND *sound, unsigned int *loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int *loopend, FMOD_TIMEUNIT loopendtype);
/*
For MOD/S3M/XM/IT/MID sequenced formats only.
*/
FMOD_RESULT F_API FMOD_Sound_GetMusicNumChannels (FMOD_SOUND *sound, int *numchannels);
FMOD_RESULT F_API FMOD_Sound_SetMusicChannelVolume (FMOD_SOUND *sound, int channel, float volume);
FMOD_RESULT F_API FMOD_Sound_GetMusicChannelVolume (FMOD_SOUND *sound, int channel, float *volume);
FMOD_RESULT F_API FMOD_Sound_SetMusicSpeed (FMOD_SOUND *sound, float speed);
FMOD_RESULT F_API FMOD_Sound_GetMusicSpeed (FMOD_SOUND *sound, float *speed);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_Sound_SetUserData (FMOD_SOUND *sound, void *userdata);
FMOD_RESULT F_API FMOD_Sound_GetUserData (FMOD_SOUND *sound, void **userdata);
FMOD_RESULT F_API FMOD_Sound_GetMemoryInfo (FMOD_SOUND *sound, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'Channel' API
*/
FMOD_RESULT F_API FMOD_Channel_GetSystemObject (FMOD_CHANNEL *channel, FMOD_SYSTEM **system);
FMOD_RESULT F_API FMOD_Channel_Stop (FMOD_CHANNEL *channel);
FMOD_RESULT F_API FMOD_Channel_SetPaused (FMOD_CHANNEL *channel, FMOD_BOOL paused);
FMOD_RESULT F_API FMOD_Channel_GetPaused (FMOD_CHANNEL *channel, FMOD_BOOL *paused);
FMOD_RESULT F_API FMOD_Channel_SetVolume (FMOD_CHANNEL *channel, float volume);
FMOD_RESULT F_API FMOD_Channel_GetVolume (FMOD_CHANNEL *channel, float *volume);
FMOD_RESULT F_API FMOD_Channel_SetFrequency (FMOD_CHANNEL *channel, float frequency);
FMOD_RESULT F_API FMOD_Channel_GetFrequency (FMOD_CHANNEL *channel, float *frequency);
FMOD_RESULT F_API FMOD_Channel_SetPan (FMOD_CHANNEL *channel, float pan);
FMOD_RESULT F_API FMOD_Channel_GetPan (FMOD_CHANNEL *channel, float *pan);
FMOD_RESULT F_API FMOD_Channel_SetDelay (FMOD_CHANNEL *channel, FMOD_DELAYTYPE delaytype, unsigned int delayhi, unsigned int delaylo);
FMOD_RESULT F_API FMOD_Channel_GetDelay (FMOD_CHANNEL *channel, FMOD_DELAYTYPE delaytype, unsigned int *delayhi, unsigned int *delaylo);
FMOD_RESULT F_API FMOD_Channel_SetSpeakerMix (FMOD_CHANNEL *channel, float frontleft, float frontright, float center, float lfe, float backleft, float backright, float sideleft, float sideright);
FMOD_RESULT F_API FMOD_Channel_GetSpeakerMix (FMOD_CHANNEL *channel, float *frontleft, float *frontright, float *center, float *lfe, float *backleft, float *backright, float *sideleft, float *sideright);
FMOD_RESULT F_API FMOD_Channel_SetSpeakerLevels (FMOD_CHANNEL *channel, FMOD_SPEAKER speaker, float *levels, int numlevels);
FMOD_RESULT F_API FMOD_Channel_GetSpeakerLevels (FMOD_CHANNEL *channel, FMOD_SPEAKER speaker, float *levels, int numlevels);
FMOD_RESULT F_API FMOD_Channel_SetInputChannelMix (FMOD_CHANNEL *channel, float *levels, int numlevels);
FMOD_RESULT F_API FMOD_Channel_GetInputChannelMix (FMOD_CHANNEL *channel, float *levels, int numlevels);
FMOD_RESULT F_API FMOD_Channel_SetMute (FMOD_CHANNEL *channel, FMOD_BOOL mute);
FMOD_RESULT F_API FMOD_Channel_GetMute (FMOD_CHANNEL *channel, FMOD_BOOL *mute);
FMOD_RESULT F_API FMOD_Channel_SetPriority (FMOD_CHANNEL *channel, int priority);
FMOD_RESULT F_API FMOD_Channel_GetPriority (FMOD_CHANNEL *channel, int *priority);
FMOD_RESULT F_API FMOD_Channel_SetPosition (FMOD_CHANNEL *channel, unsigned int position, FMOD_TIMEUNIT postype);
FMOD_RESULT F_API FMOD_Channel_GetPosition (FMOD_CHANNEL *channel, unsigned int *position, FMOD_TIMEUNIT postype);
FMOD_RESULT F_API FMOD_Channel_SetReverbProperties (FMOD_CHANNEL *channel, const FMOD_REVERB_CHANNELPROPERTIES *prop);
FMOD_RESULT F_API FMOD_Channel_GetReverbProperties (FMOD_CHANNEL *channel, FMOD_REVERB_CHANNELPROPERTIES *prop);
FMOD_RESULT F_API FMOD_Channel_SetLowPassGain (FMOD_CHANNEL *channel, float gain);
FMOD_RESULT F_API FMOD_Channel_GetLowPassGain (FMOD_CHANNEL *channel, float *gain);
FMOD_RESULT F_API FMOD_Channel_SetChannelGroup (FMOD_CHANNEL *channel, FMOD_CHANNELGROUP *channelgroup);
FMOD_RESULT F_API FMOD_Channel_GetChannelGroup (FMOD_CHANNEL *channel, FMOD_CHANNELGROUP **channelgroup);
FMOD_RESULT F_API FMOD_Channel_SetCallback (FMOD_CHANNEL *channel, FMOD_CHANNEL_CALLBACK callback);
/*
3D functionality.
*/
FMOD_RESULT F_API FMOD_Channel_Set3DAttributes (FMOD_CHANNEL *channel, const FMOD_VECTOR *pos, const FMOD_VECTOR *vel);
FMOD_RESULT F_API FMOD_Channel_Get3DAttributes (FMOD_CHANNEL *channel, FMOD_VECTOR *pos, FMOD_VECTOR *vel);
FMOD_RESULT F_API FMOD_Channel_Set3DMinMaxDistance (FMOD_CHANNEL *channel, float mindistance, float maxdistance);
FMOD_RESULT F_API FMOD_Channel_Get3DMinMaxDistance (FMOD_CHANNEL *channel, float *mindistance, float *maxdistance);
FMOD_RESULT F_API FMOD_Channel_Set3DConeSettings (FMOD_CHANNEL *channel, float insideconeangle, float outsideconeangle, float outsidevolume);
FMOD_RESULT F_API FMOD_Channel_Get3DConeSettings (FMOD_CHANNEL *channel, float *insideconeangle, float *outsideconeangle, float *outsidevolume);
FMOD_RESULT F_API FMOD_Channel_Set3DConeOrientation (FMOD_CHANNEL *channel, FMOD_VECTOR *orientation);
FMOD_RESULT F_API FMOD_Channel_Get3DConeOrientation (FMOD_CHANNEL *channel, FMOD_VECTOR *orientation);
FMOD_RESULT F_API FMOD_Channel_Set3DCustomRolloff (FMOD_CHANNEL *channel, FMOD_VECTOR *points, int numpoints);
FMOD_RESULT F_API FMOD_Channel_Get3DCustomRolloff (FMOD_CHANNEL *channel, FMOD_VECTOR **points, int *numpoints);
FMOD_RESULT F_API FMOD_Channel_Set3DOcclusion (FMOD_CHANNEL *channel, float directocclusion, float reverbocclusion);
FMOD_RESULT F_API FMOD_Channel_Get3DOcclusion (FMOD_CHANNEL *channel, float *directocclusion, float *reverbocclusion);
FMOD_RESULT F_API FMOD_Channel_Set3DSpread (FMOD_CHANNEL *channel, float angle);
FMOD_RESULT F_API FMOD_Channel_Get3DSpread (FMOD_CHANNEL *channel, float *angle);
FMOD_RESULT F_API FMOD_Channel_Set3DPanLevel (FMOD_CHANNEL *channel, float level);
FMOD_RESULT F_API FMOD_Channel_Get3DPanLevel (FMOD_CHANNEL *channel, float *level);
FMOD_RESULT F_API FMOD_Channel_Set3DDopplerLevel (FMOD_CHANNEL *channel, float level);
FMOD_RESULT F_API FMOD_Channel_Get3DDopplerLevel (FMOD_CHANNEL *channel, float *level);
FMOD_RESULT F_API FMOD_Channel_Set3DDistanceFilter (FMOD_CHANNEL *channel, FMOD_BOOL custom, float customLevel, float centerFreq);
FMOD_RESULT F_API FMOD_Channel_Get3DDistanceFilter (FMOD_CHANNEL *channel, FMOD_BOOL *custom, float *customLevel, float *centerFreq);
/*
DSP functionality only for channels playing sounds created with FMOD_SOFTWARE.
*/
FMOD_RESULT F_API FMOD_Channel_GetDSPHead (FMOD_CHANNEL *channel, FMOD_DSP **dsp);
FMOD_RESULT F_API FMOD_Channel_AddDSP (FMOD_CHANNEL *channel, FMOD_DSP *dsp, FMOD_DSPCONNECTION **connection);
/*
Information only functions.
*/
FMOD_RESULT F_API FMOD_Channel_IsPlaying (FMOD_CHANNEL *channel, FMOD_BOOL *isplaying);
FMOD_RESULT F_API FMOD_Channel_IsVirtual (FMOD_CHANNEL *channel, FMOD_BOOL *isvirtual);
FMOD_RESULT F_API FMOD_Channel_GetAudibility (FMOD_CHANNEL *channel, float *audibility);
FMOD_RESULT F_API FMOD_Channel_GetCurrentSound (FMOD_CHANNEL *channel, FMOD_SOUND **sound);
FMOD_RESULT F_API FMOD_Channel_GetSpectrum (FMOD_CHANNEL *channel, float *spectrumarray, int numvalues, int channeloffset, FMOD_DSP_FFT_WINDOW windowtype);
FMOD_RESULT F_API FMOD_Channel_GetWaveData (FMOD_CHANNEL *channel, float *wavearray, int numvalues, int channeloffset);
FMOD_RESULT F_API FMOD_Channel_GetIndex (FMOD_CHANNEL *channel, int *index);
/*
Functions also found in Sound class but here they can be set per channel.
*/
FMOD_RESULT F_API FMOD_Channel_SetMode (FMOD_CHANNEL *channel, FMOD_MODE mode);
FMOD_RESULT F_API FMOD_Channel_GetMode (FMOD_CHANNEL *channel, FMOD_MODE *mode);
FMOD_RESULT F_API FMOD_Channel_SetLoopCount (FMOD_CHANNEL *channel, int loopcount);
FMOD_RESULT F_API FMOD_Channel_GetLoopCount (FMOD_CHANNEL *channel, int *loopcount);
FMOD_RESULT F_API FMOD_Channel_SetLoopPoints (FMOD_CHANNEL *channel, unsigned int loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int loopend, FMOD_TIMEUNIT loopendtype);
FMOD_RESULT F_API FMOD_Channel_GetLoopPoints (FMOD_CHANNEL *channel, unsigned int *loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int *loopend, FMOD_TIMEUNIT loopendtype);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_Channel_SetUserData (FMOD_CHANNEL *channel, void *userdata);
FMOD_RESULT F_API FMOD_Channel_GetUserData (FMOD_CHANNEL *channel, void **userdata);
FMOD_RESULT F_API FMOD_Channel_GetMemoryInfo (FMOD_CHANNEL *channel, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'ChannelGroup' API
*/
FMOD_RESULT F_API FMOD_ChannelGroup_Release (FMOD_CHANNELGROUP *channelgroup);
FMOD_RESULT F_API FMOD_ChannelGroup_GetSystemObject (FMOD_CHANNELGROUP *channelgroup, FMOD_SYSTEM **system);
/*
Channelgroup scale values. (changes attributes relative to the channels, doesn't overwrite them)
*/
FMOD_RESULT F_API FMOD_ChannelGroup_SetVolume (FMOD_CHANNELGROUP *channelgroup, float volume);
FMOD_RESULT F_API FMOD_ChannelGroup_GetVolume (FMOD_CHANNELGROUP *channelgroup, float *volume);
FMOD_RESULT F_API FMOD_ChannelGroup_SetPitch (FMOD_CHANNELGROUP *channelgroup, float pitch);
FMOD_RESULT F_API FMOD_ChannelGroup_GetPitch (FMOD_CHANNELGROUP *channelgroup, float *pitch);
FMOD_RESULT F_API FMOD_ChannelGroup_Set3DOcclusion (FMOD_CHANNELGROUP *channelgroup, float directocclusion, float reverbocclusion);
FMOD_RESULT F_API FMOD_ChannelGroup_Get3DOcclusion (FMOD_CHANNELGROUP *channelgroup, float *directocclusion, float *reverbocclusion);
FMOD_RESULT F_API FMOD_ChannelGroup_SetPaused (FMOD_CHANNELGROUP *channelgroup, FMOD_BOOL paused);
FMOD_RESULT F_API FMOD_ChannelGroup_GetPaused (FMOD_CHANNELGROUP *channelgroup, FMOD_BOOL *paused);
FMOD_RESULT F_API FMOD_ChannelGroup_SetMute (FMOD_CHANNELGROUP *channelgroup, FMOD_BOOL mute);
FMOD_RESULT F_API FMOD_ChannelGroup_GetMute (FMOD_CHANNELGROUP *channelgroup, FMOD_BOOL *mute);
/*
Channelgroup override values. (recursively overwrites whatever settings the channels had)
*/
FMOD_RESULT F_API FMOD_ChannelGroup_Stop (FMOD_CHANNELGROUP *channelgroup);
FMOD_RESULT F_API FMOD_ChannelGroup_OverrideVolume (FMOD_CHANNELGROUP *channelgroup, float volume);
FMOD_RESULT F_API FMOD_ChannelGroup_OverrideFrequency(FMOD_CHANNELGROUP *channelgroup, float frequency);
FMOD_RESULT F_API FMOD_ChannelGroup_OverridePan (FMOD_CHANNELGROUP *channelgroup, float pan);
FMOD_RESULT F_API FMOD_ChannelGroup_OverrideReverbProperties(FMOD_CHANNELGROUP *channelgroup, const FMOD_REVERB_CHANNELPROPERTIES *prop);
FMOD_RESULT F_API FMOD_ChannelGroup_Override3DAttributes(FMOD_CHANNELGROUP *channelgroup, const FMOD_VECTOR *pos, const FMOD_VECTOR *vel);
FMOD_RESULT F_API FMOD_ChannelGroup_OverrideSpeakerMix(FMOD_CHANNELGROUP *channelgroup, float frontleft, float frontright, float center, float lfe, float backleft, float backright, float sideleft, float sideright);
/*
Nested channel groups.
*/
FMOD_RESULT F_API FMOD_ChannelGroup_AddGroup (FMOD_CHANNELGROUP *channelgroup, FMOD_CHANNELGROUP *group);
FMOD_RESULT F_API FMOD_ChannelGroup_GetNumGroups (FMOD_CHANNELGROUP *channelgroup, int *numgroups);
FMOD_RESULT F_API FMOD_ChannelGroup_GetGroup (FMOD_CHANNELGROUP *channelgroup, int index, FMOD_CHANNELGROUP **group);
FMOD_RESULT F_API FMOD_ChannelGroup_GetParentGroup (FMOD_CHANNELGROUP *channelgroup, FMOD_CHANNELGROUP **group);
/*
DSP functionality only for channel groups playing sounds created with FMOD_SOFTWARE.
*/
FMOD_RESULT F_API FMOD_ChannelGroup_GetDSPHead (FMOD_CHANNELGROUP *channelgroup, FMOD_DSP **dsp);
FMOD_RESULT F_API FMOD_ChannelGroup_AddDSP (FMOD_CHANNELGROUP *channelgroup, FMOD_DSP *dsp, FMOD_DSPCONNECTION **connection);
/*
Information only functions.
*/
FMOD_RESULT F_API FMOD_ChannelGroup_GetName (FMOD_CHANNELGROUP *channelgroup, char *name, int namelen);
FMOD_RESULT F_API FMOD_ChannelGroup_GetNumChannels (FMOD_CHANNELGROUP *channelgroup, int *numchannels);
FMOD_RESULT F_API FMOD_ChannelGroup_GetChannel (FMOD_CHANNELGROUP *channelgroup, int index, FMOD_CHANNEL **channel);
FMOD_RESULT F_API FMOD_ChannelGroup_GetSpectrum (FMOD_CHANNELGROUP *channelgroup, float *spectrumarray, int numvalues, int channeloffset, FMOD_DSP_FFT_WINDOW windowtype);
FMOD_RESULT F_API FMOD_ChannelGroup_GetWaveData (FMOD_CHANNELGROUP *channelgroup, float *wavearray, int numvalues, int channeloffset);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_ChannelGroup_SetUserData (FMOD_CHANNELGROUP *channelgroup, void *userdata);
FMOD_RESULT F_API FMOD_ChannelGroup_GetUserData (FMOD_CHANNELGROUP *channelgroup, void **userdata);
FMOD_RESULT F_API FMOD_ChannelGroup_GetMemoryInfo (FMOD_CHANNELGROUP *channelgroup, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'SoundGroup' API
*/
FMOD_RESULT F_API FMOD_SoundGroup_Release (FMOD_SOUNDGROUP *soundgroup);
FMOD_RESULT F_API FMOD_SoundGroup_GetSystemObject (FMOD_SOUNDGROUP *soundgroup, FMOD_SYSTEM **system);
/*
SoundGroup control functions.
*/
FMOD_RESULT F_API FMOD_SoundGroup_SetMaxAudible (FMOD_SOUNDGROUP *soundgroup, int maxaudible);
FMOD_RESULT F_API FMOD_SoundGroup_GetMaxAudible (FMOD_SOUNDGROUP *soundgroup, int *maxaudible);
FMOD_RESULT F_API FMOD_SoundGroup_SetMaxAudibleBehavior(FMOD_SOUNDGROUP *soundgroup, FMOD_SOUNDGROUP_BEHAVIOR behavior);
FMOD_RESULT F_API FMOD_SoundGroup_GetMaxAudibleBehavior(FMOD_SOUNDGROUP *soundgroup, FMOD_SOUNDGROUP_BEHAVIOR *behavior);
FMOD_RESULT F_API FMOD_SoundGroup_SetMuteFadeSpeed (FMOD_SOUNDGROUP *soundgroup, float speed);
FMOD_RESULT F_API FMOD_SoundGroup_GetMuteFadeSpeed (FMOD_SOUNDGROUP *soundgroup, float *speed);
FMOD_RESULT F_API FMOD_SoundGroup_SetVolume (FMOD_SOUNDGROUP *soundgroup, float volume);
FMOD_RESULT F_API FMOD_SoundGroup_GetVolume (FMOD_SOUNDGROUP *soundgroup, float *volume);
FMOD_RESULT F_API FMOD_SoundGroup_Stop (FMOD_SOUNDGROUP *soundgroup);
/*
Information only functions.
*/
FMOD_RESULT F_API FMOD_SoundGroup_GetName (FMOD_SOUNDGROUP *soundgroup, char *name, int namelen);
FMOD_RESULT F_API FMOD_SoundGroup_GetNumSounds (FMOD_SOUNDGROUP *soundgroup, int *numsounds);
FMOD_RESULT F_API FMOD_SoundGroup_GetSound (FMOD_SOUNDGROUP *soundgroup, int index, FMOD_SOUND **sound);
FMOD_RESULT F_API FMOD_SoundGroup_GetNumPlaying (FMOD_SOUNDGROUP *soundgroup, int *numplaying);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_SoundGroup_SetUserData (FMOD_SOUNDGROUP *soundgroup, void *userdata);
FMOD_RESULT F_API FMOD_SoundGroup_GetUserData (FMOD_SOUNDGROUP *soundgroup, void **userdata);
FMOD_RESULT F_API FMOD_SoundGroup_GetMemoryInfo (FMOD_SOUNDGROUP *soundgroup, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'DSP' API
*/
FMOD_RESULT F_API FMOD_DSP_Release (FMOD_DSP *dsp);
FMOD_RESULT F_API FMOD_DSP_GetSystemObject (FMOD_DSP *dsp, FMOD_SYSTEM **system);
/*
Connection / disconnection / input and output enumeration.
*/
FMOD_RESULT F_API FMOD_DSP_AddInput (FMOD_DSP *dsp, FMOD_DSP *target, FMOD_DSPCONNECTION **connection);
FMOD_RESULT F_API FMOD_DSP_DisconnectFrom (FMOD_DSP *dsp, FMOD_DSP *target);
FMOD_RESULT F_API FMOD_DSP_DisconnectAll (FMOD_DSP *dsp, FMOD_BOOL inputs, FMOD_BOOL outputs);
FMOD_RESULT F_API FMOD_DSP_Remove (FMOD_DSP *dsp);
FMOD_RESULT F_API FMOD_DSP_GetNumInputs (FMOD_DSP *dsp, int *numinputs);
FMOD_RESULT F_API FMOD_DSP_GetNumOutputs (FMOD_DSP *dsp, int *numoutputs);
FMOD_RESULT F_API FMOD_DSP_GetInput (FMOD_DSP *dsp, int index, FMOD_DSP **input, FMOD_DSPCONNECTION **inputconnection);
FMOD_RESULT F_API FMOD_DSP_GetOutput (FMOD_DSP *dsp, int index, FMOD_DSP **output, FMOD_DSPCONNECTION **outputconnection);
/*
DSP unit control.
*/
FMOD_RESULT F_API FMOD_DSP_SetActive (FMOD_DSP *dsp, FMOD_BOOL active);
FMOD_RESULT F_API FMOD_DSP_GetActive (FMOD_DSP *dsp, FMOD_BOOL *active);
FMOD_RESULT F_API FMOD_DSP_SetBypass (FMOD_DSP *dsp, FMOD_BOOL bypass);
FMOD_RESULT F_API FMOD_DSP_GetBypass (FMOD_DSP *dsp, FMOD_BOOL *bypass);
FMOD_RESULT F_API FMOD_DSP_SetSpeakerActive (FMOD_DSP *dsp, FMOD_SPEAKER speaker, FMOD_BOOL active);
FMOD_RESULT F_API FMOD_DSP_GetSpeakerActive (FMOD_DSP *dsp, FMOD_SPEAKER speaker, FMOD_BOOL *active);
FMOD_RESULT F_API FMOD_DSP_Reset (FMOD_DSP *dsp);
/*
DSP parameter control.
*/
FMOD_RESULT F_API FMOD_DSP_SetParameter (FMOD_DSP *dsp, int index, float value);
FMOD_RESULT F_API FMOD_DSP_GetParameter (FMOD_DSP *dsp, int index, float *value, char *valuestr, int valuestrlen);
FMOD_RESULT F_API FMOD_DSP_GetNumParameters (FMOD_DSP *dsp, int *numparams);
FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, char *name, char *label, char *description, int descriptionlen, float *min, float *max);
FMOD_RESULT F_API FMOD_DSP_ShowConfigDialog (FMOD_DSP *dsp, void *hwnd, FMOD_BOOL show);
/*
DSP attributes.
*/
FMOD_RESULT F_API FMOD_DSP_GetInfo (FMOD_DSP *dsp, char *name, unsigned int *version, int *channels, int *configwidth, int *configheight);
FMOD_RESULT F_API FMOD_DSP_GetType (FMOD_DSP *dsp, FMOD_DSP_TYPE *type);
FMOD_RESULT F_API FMOD_DSP_SetDefaults (FMOD_DSP *dsp, float frequency, float volume, float pan, int priority);
FMOD_RESULT F_API FMOD_DSP_GetDefaults (FMOD_DSP *dsp, float *frequency, float *volume, float *pan, int *priority);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_DSP_SetUserData (FMOD_DSP *dsp, void *userdata);
FMOD_RESULT F_API FMOD_DSP_GetUserData (FMOD_DSP *dsp, void **userdata);
FMOD_RESULT F_API FMOD_DSP_GetMemoryInfo (FMOD_DSP *dsp, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'DSPConnection' API
*/
FMOD_RESULT F_API FMOD_DSPConnection_GetInput (FMOD_DSPCONNECTION *dspconnection, FMOD_DSP **input);
FMOD_RESULT F_API FMOD_DSPConnection_GetOutput (FMOD_DSPCONNECTION *dspconnection, FMOD_DSP **output);
FMOD_RESULT F_API FMOD_DSPConnection_SetMix (FMOD_DSPCONNECTION *dspconnection, float volume);
FMOD_RESULT F_API FMOD_DSPConnection_GetMix (FMOD_DSPCONNECTION *dspconnection, float *volume);
FMOD_RESULT F_API FMOD_DSPConnection_SetLevels (FMOD_DSPCONNECTION *dspconnection, FMOD_SPEAKER speaker, float *levels, int numlevels);
FMOD_RESULT F_API FMOD_DSPConnection_GetLevels (FMOD_DSPCONNECTION *dspconnection, FMOD_SPEAKER speaker, float *levels, int numlevels);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_DSPConnection_SetUserData (FMOD_DSPCONNECTION *dspconnection, void *userdata);
FMOD_RESULT F_API FMOD_DSPConnection_GetUserData (FMOD_DSPCONNECTION *dspconnection, void **userdata);
FMOD_RESULT F_API FMOD_DSPConnection_GetMemoryInfo (FMOD_DSPCONNECTION *dspconnection, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'Geometry' API
*/
FMOD_RESULT F_API FMOD_Geometry_Release (FMOD_GEOMETRY *geometry);
/*
Polygon manipulation.
*/
FMOD_RESULT F_API FMOD_Geometry_AddPolygon (FMOD_GEOMETRY *geometry, float directocclusion, float reverbocclusion, FMOD_BOOL doublesided, int numvertices, const FMOD_VECTOR *vertices, int *polygonindex);
FMOD_RESULT F_API FMOD_Geometry_GetNumPolygons (FMOD_GEOMETRY *geometry, int *numpolygons);
FMOD_RESULT F_API FMOD_Geometry_GetMaxPolygons (FMOD_GEOMETRY *geometry, int *maxpolygons, int *maxvertices);
FMOD_RESULT F_API FMOD_Geometry_GetPolygonNumVertices(FMOD_GEOMETRY *geometry, int index, int *numvertices);
FMOD_RESULT F_API FMOD_Geometry_SetPolygonVertex (FMOD_GEOMETRY *geometry, int index, int vertexindex, const FMOD_VECTOR *vertex);
FMOD_RESULT F_API FMOD_Geometry_GetPolygonVertex (FMOD_GEOMETRY *geometry, int index, int vertexindex, FMOD_VECTOR *vertex);
FMOD_RESULT F_API FMOD_Geometry_SetPolygonAttributes (FMOD_GEOMETRY *geometry, int index, float directocclusion, float reverbocclusion, FMOD_BOOL doublesided);
FMOD_RESULT F_API FMOD_Geometry_GetPolygonAttributes (FMOD_GEOMETRY *geometry, int index, float *directocclusion, float *reverbocclusion, FMOD_BOOL *doublesided);
/*
Object manipulation.
*/
FMOD_RESULT F_API FMOD_Geometry_SetActive (FMOD_GEOMETRY *geometry, FMOD_BOOL active);
FMOD_RESULT F_API FMOD_Geometry_GetActive (FMOD_GEOMETRY *geometry, FMOD_BOOL *active);
FMOD_RESULT F_API FMOD_Geometry_SetRotation (FMOD_GEOMETRY *geometry, const FMOD_VECTOR *forward, const FMOD_VECTOR *up);
FMOD_RESULT F_API FMOD_Geometry_GetRotation (FMOD_GEOMETRY *geometry, FMOD_VECTOR *forward, FMOD_VECTOR *up);
FMOD_RESULT F_API FMOD_Geometry_SetPosition (FMOD_GEOMETRY *geometry, const FMOD_VECTOR *position);
FMOD_RESULT F_API FMOD_Geometry_GetPosition (FMOD_GEOMETRY *geometry, FMOD_VECTOR *position);
FMOD_RESULT F_API FMOD_Geometry_SetScale (FMOD_GEOMETRY *geometry, const FMOD_VECTOR *scale);
FMOD_RESULT F_API FMOD_Geometry_GetScale (FMOD_GEOMETRY *geometry, FMOD_VECTOR *scale);
FMOD_RESULT F_API FMOD_Geometry_Save (FMOD_GEOMETRY *geometry, void *data, int *datasize);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_Geometry_SetUserData (FMOD_GEOMETRY *geometry, void *userdata);
FMOD_RESULT F_API FMOD_Geometry_GetUserData (FMOD_GEOMETRY *geometry, void **userdata);
FMOD_RESULT F_API FMOD_Geometry_GetMemoryInfo (FMOD_GEOMETRY *geometry, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*
'Reverb' API
*/
FMOD_RESULT F_API FMOD_Reverb_Release (FMOD_REVERB *reverb);
/*
Reverb manipulation.
*/
FMOD_RESULT F_API FMOD_Reverb_Set3DAttributes (FMOD_REVERB *reverb, const FMOD_VECTOR *position, float mindistance, float maxdistance);
FMOD_RESULT F_API FMOD_Reverb_Get3DAttributes (FMOD_REVERB *reverb, FMOD_VECTOR *position, float *mindistance, float *maxdistance);
FMOD_RESULT F_API FMOD_Reverb_SetProperties (FMOD_REVERB *reverb, const FMOD_REVERB_PROPERTIES *properties);
FMOD_RESULT F_API FMOD_Reverb_GetProperties (FMOD_REVERB *reverb, FMOD_REVERB_PROPERTIES *properties);
FMOD_RESULT F_API FMOD_Reverb_SetActive (FMOD_REVERB *reverb, FMOD_BOOL active);
FMOD_RESULT F_API FMOD_Reverb_GetActive (FMOD_REVERB *reverb, FMOD_BOOL *active);
/*
Userdata set/get.
*/
FMOD_RESULT F_API FMOD_Reverb_SetUserData (FMOD_REVERB *reverb, void *userdata);
FMOD_RESULT F_API FMOD_Reverb_GetUserData (FMOD_REVERB *reverb, void **userdata);
FMOD_RESULT F_API FMOD_Reverb_GetMemoryInfo (FMOD_REVERB *reverb, unsigned int memorybits, unsigned int event_memorybits, unsigned int *memoryused, FMOD_MEMORY_USAGE_DETAILS *memoryused_details);
/*$ preserve start $*/
#ifdef __cplusplus
}
#endif
#endif
/*$ preserve end $*/
|
{
"content_hash": "736bee263cb847117b13729b16fc6f58",
"timestamp": "",
"source": "github",
"line_count": 2474,
"max_line_length": 661,
"avg_line_length": 68.20937752627324,
"alnum_prop": 0.6848177777777777,
"repo_name": "Ne02ptzero/Grog-Knight",
"id": "d299bd72b1d4db594494e67b34be2ab44fa1c4d4",
"size": "168750",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "Angel/Libraries/FMOD/inc/fmod.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "143356"
},
{
"name": "Awk",
"bytes": "3965"
},
{
"name": "Batchfile",
"bytes": "5835"
},
{
"name": "C",
"bytes": "17868443"
},
{
"name": "C#",
"bytes": "55726"
},
{
"name": "C++",
"bytes": "7252022"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CMake",
"bytes": "32795"
},
{
"name": "CSS",
"bytes": "46494"
},
{
"name": "DIGITAL Command Language",
"bytes": "59070"
},
{
"name": "Groff",
"bytes": "3728947"
},
{
"name": "HTML",
"bytes": "5247431"
},
{
"name": "JavaScript",
"bytes": "42790"
},
{
"name": "Lua",
"bytes": "511143"
},
{
"name": "M",
"bytes": "3824"
},
{
"name": "Makefile",
"bytes": "418614"
},
{
"name": "Mathematica",
"bytes": "27410"
},
{
"name": "Module Management System",
"bytes": "2870"
},
{
"name": "Objective-C",
"bytes": "92337"
},
{
"name": "Pascal",
"bytes": "61164"
},
{
"name": "Perl",
"bytes": "31459"
},
{
"name": "Python",
"bytes": "185439"
},
{
"name": "SAS",
"bytes": "1711"
},
{
"name": "Shell",
"bytes": "2560503"
},
{
"name": "TeX",
"bytes": "144346"
}
],
"symlink_target": ""
}
|
package org.locationtech.geomesa
package object convert {
@deprecated("Use evaluation context metrics")
trait Counter {
def incSuccess(i: Long = 1): Unit
def getSuccess: Long
def incFailure(i: Long = 1): Unit
def getFailure: Long
// For things like Avro think of this as a recordCount as well
def incLineCount(i: Long = 1): Unit
def getLineCount: Long
def setLineCount(i: Long)
}
// noinspection ScalaDeprecation
@deprecated("Use evaluation context metrics")
class DefaultCounter extends Counter {
private var s: Long = 0
private var f: Long = 0
private var c: Long = 0
override def incSuccess(i: Long = 1): Unit = s += i
override def getSuccess: Long = s
override def incFailure(i: Long = 1): Unit = f += i
override def getFailure: Long = f
override def incLineCount(i: Long = 1): Unit = c += i
override def getLineCount: Long = c
override def setLineCount(i: Long): Unit = c = i
}
}
|
{
"content_hash": "eb1382835f4f498fb8a64e36271480b9",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 66,
"avg_line_length": 25.81578947368421,
"alnum_prop": 0.6636085626911316,
"repo_name": "elahrvivaz/geomesa",
"id": "e683fb8bffba9faee32ad7e2e1f3d7b1825e8367",
"size": "1444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "geomesa-convert/geomesa-convert-common/src/main/scala/org/locationtech/geomesa/convert/package.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2900"
},
{
"name": "Java",
"bytes": "301988"
},
{
"name": "JavaScript",
"bytes": "140"
},
{
"name": "Python",
"bytes": "12067"
},
{
"name": "R",
"bytes": "2716"
},
{
"name": "Scala",
"bytes": "8440279"
},
{
"name": "Scheme",
"bytes": "3143"
},
{
"name": "Shell",
"bytes": "154842"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Sat Jan 09 21:46:11 PST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.annotation.JsonSubTypes.Type (Jackson-annotations 2.7.0 API)</title>
<meta name="date" content="2016-01-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.annotation.JsonSubTypes.Type (Jackson-annotations 2.7.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../com/fasterxml/jackson/annotation/package-summary.html">Package</a></li>
<li><a href="../../../../../com/fasterxml/jackson/annotation/JsonSubTypes.Type.html" title="annotation in com.fasterxml.jackson.annotation">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/fasterxml/jackson/annotation/class-use/JsonSubTypes.Type.html" target="_top">Frames</a></li>
<li><a href="JsonSubTypes.Type.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.fasterxml.jackson.annotation.JsonSubTypes.Type" class="title">Uses of Class<br>com.fasterxml.jackson.annotation.JsonSubTypes.Type</h2>
</div>
<div class="classUseContainer">No usage of com.fasterxml.jackson.annotation.JsonSubTypes.Type</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="../../../../../com/fasterxml/jackson/annotation/package-summary.html">Package</a></li>
<li><a href="../../../../../com/fasterxml/jackson/annotation/JsonSubTypes.Type.html" title="annotation in com.fasterxml.jackson.annotation">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/fasterxml/jackson/annotation/class-use/JsonSubTypes.Type.html" target="_top">Frames</a></li>
<li><a href="JsonSubTypes.Type.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2008–2016 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
|
{
"content_hash": "32154ed86504cebd9d2fa9b2dba746ea",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 163,
"avg_line_length": 39.22608695652174,
"alnum_prop": 0.6320106406561738,
"repo_name": "FasterXML/jackson-annotations",
"id": "74526c285c456997a484f55a7b6953ebc625db02",
"size": "4511",
"binary": false,
"copies": "1",
"ref": "refs/heads/2.15",
"path": "docs/javadoc/2.7/com/fasterxml/jackson/annotation/class-use/JsonSubTypes.Type.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "241575"
},
{
"name": "Logos",
"bytes": "7816"
}
],
"symlink_target": ""
}
|
import { URI } from 'vs/base/common/uri';
import { IListService } from 'vs/platform/list/browser/listService';
import { OpenEditor, IExplorerService } from 'vs/workbench/contrib/files/common/files';
import { toResource, SideBySideEditor, IEditorIdentifier } from 'vs/workbench/common/editor';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { coalesce } from 'vs/base/common/arrays';
import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
function getFocus(listService: IListService): unknown | undefined {
let list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
let focus: unknown;
if (list instanceof List) {
const focused = list.getFocusedElements();
if (focused.length) {
focus = focused[0];
}
} else if (list instanceof AsyncDataTree) {
const focused = list.getFocus();
if (focused.length) {
focus = focused[0];
}
}
return focus;
}
return undefined;
}
// Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding
// To cover all these cases we need to properly compute the resource on which the command is being executed
export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined {
if (URI.isUri(resource)) {
return resource;
}
const focus = getFocus(listService);
if (focus instanceof ExplorerItem) {
return focus.resource;
} else if (focus instanceof OpenEditor) {
return focus.getResource();
}
return editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY }) : undefined;
}
export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Explorer
if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {
// Explorer
const context = explorerService.getContext(true);
if (context.length) {
return context.map(c => c.resource);
}
}
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource()));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainUriStr: string | undefined = undefined;
if (URI.isUri(resource)) {
mainUriStr = resource.toString();
} else if (focus instanceof OpenEditor) {
const focusedResource = focus.getResource();
mainUriStr = focusedResource ? focusedResource.toString() : undefined;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s.toString() === mainUriStr)) {
return selection;
}
}
}
const result = getResourceForCommand(resource, listService, editorService);
return !!result ? [result] : [];
}
export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainEditor: IEditorIdentifier | undefined = undefined;
if (focus instanceof OpenEditor) {
mainEditor = focus;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s === mainEditor)) {
return selection;
}
}
}
return undefined;
}
|
{
"content_hash": "f921bc17c408341f499daa4759c3208b",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 184,
"avg_line_length": 39.351851851851855,
"alnum_prop": 0.736,
"repo_name": "hoovercj/vscode",
"id": "ac012e62fc4c7ebfd3d59411de1b31f8d219b333",
"size": "4601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/vs/workbench/contrib/files/browser/files.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5527"
},
{
"name": "C",
"bytes": "818"
},
{
"name": "C#",
"bytes": "1640"
},
{
"name": "C++",
"bytes": "1038"
},
{
"name": "CSS",
"bytes": "429597"
},
{
"name": "Clojure",
"bytes": "1206"
},
{
"name": "CoffeeScript",
"bytes": "590"
},
{
"name": "F#",
"bytes": "634"
},
{
"name": "Go",
"bytes": "628"
},
{
"name": "Groovy",
"bytes": "3928"
},
{
"name": "HLSL",
"bytes": "184"
},
{
"name": "HTML",
"bytes": "28219"
},
{
"name": "Inno Setup",
"bytes": "108702"
},
{
"name": "Java",
"bytes": "599"
},
{
"name": "JavaScript",
"bytes": "839590"
},
{
"name": "Lua",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "553"
},
{
"name": "Objective-C",
"bytes": "1387"
},
{
"name": "PHP",
"bytes": "998"
},
{
"name": "Perl",
"bytes": "857"
},
{
"name": "Perl6",
"bytes": "1065"
},
{
"name": "PowerShell",
"bytes": "6526"
},
{
"name": "Python",
"bytes": "2119"
},
{
"name": "R",
"bytes": "362"
},
{
"name": "Ruby",
"bytes": "1703"
},
{
"name": "Rust",
"bytes": "532"
},
{
"name": "ShaderLab",
"bytes": "330"
},
{
"name": "Shell",
"bytes": "31357"
},
{
"name": "Swift",
"bytes": "220"
},
{
"name": "TypeScript",
"bytes": "13413255"
},
{
"name": "Visual Basic",
"bytes": "893"
}
],
"symlink_target": ""
}
|
import os
from shutil import copyfile
from subprocess import check_call
def setup(loader, variant=None):
_, variant = loader.setup_project_env(None, variant)
work_dir = loader.config['work_dir']
use_symlink = not loader.config.get('no_symlink_please', False)
if use_symlink:
link_fn = loader.force_symlink
else:
link_fn = copyfile
package_path = os.path.join(work_dir, 'bower.json')
package_var_path = os.path.join(work_dir, 'bower-%s.json' % variant)
if os.path.exists(package_var_path):
link_fn(package_var_path, package_path)
if os.path.exists(package_path):
print("Setup bower_components")
check_call(['bower', 'install'], cwd=work_dir)
|
{
"content_hash": "6a432bdf23b877de62ac94818b89c055",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 72,
"avg_line_length": 32.77272727272727,
"alnum_prop": 0.6629680998613038,
"repo_name": "dozymoe/fireh_runner",
"id": "078b3a88b6d32f40f391c1f2db5de3985b96d4a1",
"size": "721",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "setup_modules/bower.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "85000"
}
],
"symlink_target": ""
}
|
import numpy as np
import pytest
from pandas import Categorical, DataFrame, Series
import pandas._testing as tm
class TestSeriesSortValues:
def test_sort_values(self, datetime_series):
# check indexes are reordered corresponding with the values
ser = Series([3, 2, 4, 1], ["A", "B", "C", "D"])
expected = Series([1, 2, 3, 4], ["D", "B", "A", "C"])
result = ser.sort_values()
tm.assert_series_equal(expected, result)
ts = datetime_series.copy()
ts[:5] = np.NaN
vals = ts.values
result = ts.sort_values()
assert np.isnan(result[-5:]).all()
tm.assert_numpy_array_equal(result[:-5].values, np.sort(vals[5:]))
# na_position
result = ts.sort_values(na_position="first")
assert np.isnan(result[:5]).all()
tm.assert_numpy_array_equal(result[5:].values, np.sort(vals[5:]))
# something object-type
ser = Series(["A", "B"], [1, 2])
# no failure
ser.sort_values()
# ascending=False
ordered = ts.sort_values(ascending=False)
expected = np.sort(ts.dropna().values)[::-1]
tm.assert_almost_equal(expected, ordered.dropna().values)
ordered = ts.sort_values(ascending=False, na_position="first")
tm.assert_almost_equal(expected, ordered.dropna().values)
# ascending=[False] should behave the same as ascending=False
ordered = ts.sort_values(ascending=[False])
expected = ts.sort_values(ascending=False)
tm.assert_series_equal(expected, ordered)
ordered = ts.sort_values(ascending=[False], na_position="first")
expected = ts.sort_values(ascending=False, na_position="first")
tm.assert_series_equal(expected, ordered)
msg = "ascending must be boolean"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=None)
msg = r"Length of ascending \(0\) must be 1 for Series"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=[])
msg = r"Length of ascending \(3\) must be 1 for Series"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=[1, 2, 3])
msg = r"Length of ascending \(2\) must be 1 for Series"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=[False, False])
msg = "ascending must be boolean"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending="foobar")
# inplace=True
ts = datetime_series.copy()
return_value = ts.sort_values(ascending=False, inplace=True)
assert return_value is None
tm.assert_series_equal(ts, datetime_series.sort_values(ascending=False))
tm.assert_index_equal(
ts.index, datetime_series.sort_values(ascending=False).index
)
# GH#5856/5853
# Series.sort_values operating on a view
df = DataFrame(np.random.randn(10, 4))
s = df.iloc[:, 0]
msg = (
"This Series is a view of some other array, to sort in-place "
"you must create a copy"
)
with pytest.raises(ValueError, match=msg):
s.sort_values(inplace=True)
def test_sort_values_categorical(self):
c = Categorical(["a", "b", "b", "a"], ordered=False)
cat = Series(c.copy())
# sort in the categories order
expected = Series(
Categorical(["a", "a", "b", "b"], ordered=False), index=[0, 3, 1, 2]
)
result = cat.sort_values()
tm.assert_series_equal(result, expected)
cat = Series(Categorical(["a", "c", "b", "d"], ordered=True))
res = cat.sort_values()
exp = np.array(["a", "b", "c", "d"], dtype=np.object_)
tm.assert_numpy_array_equal(res.__array__(), exp)
cat = Series(
Categorical(
["a", "c", "b", "d"], categories=["a", "b", "c", "d"], ordered=True
)
)
res = cat.sort_values()
exp = np.array(["a", "b", "c", "d"], dtype=np.object_)
tm.assert_numpy_array_equal(res.__array__(), exp)
res = cat.sort_values(ascending=False)
exp = np.array(["d", "c", "b", "a"], dtype=np.object_)
tm.assert_numpy_array_equal(res.__array__(), exp)
raw_cat1 = Categorical(
["a", "b", "c", "d"], categories=["a", "b", "c", "d"], ordered=False
)
raw_cat2 = Categorical(
["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True
)
s = ["a", "b", "c", "d"]
df = DataFrame(
{"unsort": raw_cat1, "sort": raw_cat2, "string": s, "values": [1, 2, 3, 4]}
)
# Cats must be sorted in a dataframe
res = df.sort_values(by=["string"], ascending=False)
exp = np.array(["d", "c", "b", "a"], dtype=np.object_)
tm.assert_numpy_array_equal(res["sort"].values.__array__(), exp)
assert res["sort"].dtype == "category"
res = df.sort_values(by=["sort"], ascending=False)
exp = df.sort_values(by=["string"], ascending=True)
tm.assert_series_equal(res["values"], exp["values"])
assert res["sort"].dtype == "category"
assert res["unsort"].dtype == "category"
# unordered cat, but we allow this
df.sort_values(by=["unsort"], ascending=False)
# multi-columns sort
# GH#7848
df = DataFrame(
{"id": [6, 5, 4, 3, 2, 1], "raw_grade": ["a", "b", "b", "a", "a", "e"]}
)
df["grade"] = Categorical(df["raw_grade"], ordered=True)
df["grade"] = df["grade"].cat.set_categories(["b", "e", "a"])
# sorts 'grade' according to the order of the categories
result = df.sort_values(by=["grade"])
expected = df.iloc[[1, 2, 5, 0, 3, 4]]
tm.assert_frame_equal(result, expected)
# multi
result = df.sort_values(by=["grade", "id"])
expected = df.iloc[[2, 1, 5, 4, 3, 0]]
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize(
"original_list, sorted_list, ignore_index, output_index",
[
([2, 3, 6, 1], [6, 3, 2, 1], True, [0, 1, 2, 3]),
([2, 3, 6, 1], [6, 3, 2, 1], False, [2, 1, 0, 3]),
],
)
def test_sort_values_ignore_index(
self, inplace, original_list, sorted_list, ignore_index, output_index
):
# GH 30114
ser = Series(original_list)
expected = Series(sorted_list, index=output_index)
kwargs = {"ignore_index": ignore_index, "inplace": inplace}
if inplace:
result_ser = ser.copy()
result_ser.sort_values(ascending=False, **kwargs)
else:
result_ser = ser.sort_values(ascending=False, **kwargs)
tm.assert_series_equal(result_ser, expected)
tm.assert_series_equal(ser, Series(original_list))
class TestSeriesSortingKey:
def test_sort_values_key(self):
series = Series(np.array(["Hello", "goodbye"]))
result = series.sort_values(0)
expected = series
tm.assert_series_equal(result, expected)
result = series.sort_values(0, key=lambda x: x.str.lower())
expected = series[::-1]
tm.assert_series_equal(result, expected)
def test_sort_values_key_nan(self):
series = Series(np.array([0, 5, np.nan, 3, 2, np.nan]))
result = series.sort_values(0)
expected = series.iloc[[0, 4, 3, 1, 2, 5]]
tm.assert_series_equal(result, expected)
result = series.sort_values(0, key=lambda x: x + 5)
expected = series.iloc[[0, 4, 3, 1, 2, 5]]
tm.assert_series_equal(result, expected)
result = series.sort_values(0, key=lambda x: -x, ascending=False)
expected = series.iloc[[0, 4, 3, 1, 2, 5]]
tm.assert_series_equal(result, expected)
|
{
"content_hash": "601f9a30c58b75b5e3c33d1ddbde3099",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 87,
"avg_line_length": 37.64622641509434,
"alnum_prop": 0.5593284049617843,
"repo_name": "jreback/pandas",
"id": "b49e39d4592ea13f3b55de84672fd8afaa026d4d",
"size": "7981",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pandas/tests/series/methods/test_sort_values.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4879"
},
{
"name": "C",
"bytes": "406353"
},
{
"name": "C++",
"bytes": "17193"
},
{
"name": "HTML",
"bytes": "606963"
},
{
"name": "Makefile",
"bytes": "529"
},
{
"name": "Python",
"bytes": "14930989"
},
{
"name": "Shell",
"bytes": "29317"
},
{
"name": "Smarty",
"bytes": "2040"
}
],
"symlink_target": ""
}
|
<?php
namespace Coyote\ApiBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class RegisterControllerTest extends WebTestCase
{
public function testCompleteScenario()
{
$client = static::createClient();
$crawler = $client->request('GET', '/register/');
$this->assertEquals(200, $client->getResponse()->getStatusCode());
}
/*
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient();
// Create a new entry in the database
$crawler = $client->request('GET', '/register/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /register/");
$crawler = $client->click($crawler->selectLink('Create a new entry')->link());
// Fill in the form and submit it
$form = $crawler->selectButton('Create')->form(array(
'coyote_apibundle_register[field_name]' => 'Test',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")');
// Edit the entity
$crawler = $client->click($crawler->selectLink('Edit')->link());
$form = $crawler->selectButton('Update')->form(array(
'coyote_apibundle_register[field_name]' => 'Foo',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]');
// Delete the entity
$client->submit($crawler->selectButton('Delete')->form());
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
}
|
{
"content_hash": "1a3be7c260c6a93a04e43a66efed7aac",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 125,
"avg_line_length": 34.125,
"alnum_prop": 0.5989010989010989,
"repo_name": "Coyotealone/webservice",
"id": "7bbaa819b4334f6f0b1853ad3046d57c1128d8b7",
"size": "2184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Coyote/ApiBundle/Tests/Controller/RegisterControllerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "PHP",
"bytes": "170435"
}
],
"symlink_target": ""
}
|
import { toTitleCase } from "@artsy/to-title-case"
import { StackScreenProps } from "@react-navigation/stack"
import { FilterData, FilterDisplayName, FilterParamName } from "../ArtworkFilterHelpers"
import { ArtworkFilterNavigationStack } from "../ArtworkFilterNavigator"
import { useArtworkFiltersAggregation } from "../useArtworkFilters"
import { MultiSelectOptionScreen } from "./MultiSelectOption"
import { useMultiSelect } from "./useMultiSelect"
const PARAM_NAME = FilterParamName.artistNationalities
interface ArtistNationalitiesOptionsScreenProps
extends StackScreenProps<ArtworkFilterNavigationStack, "ArtistNationalitiesOptionsScreen"> {}
export const ArtistNationalitiesOptionsScreen: React.FC<ArtistNationalitiesOptionsScreenProps> = ({
navigation,
}) => {
const { aggregation } = useArtworkFiltersAggregation({ paramName: PARAM_NAME })
const options: FilterData[] = (aggregation?.counts ?? []).map(({ value: paramValue, name }) => {
return { displayText: toTitleCase(name), paramName: PARAM_NAME, paramValue }
})
const { handleSelect, isSelected, handleClear, isActive } = useMultiSelect({
options,
paramName: PARAM_NAME,
})
const filterOptions = options.map((option) => ({ ...option, paramValue: isSelected(option) }))
return (
<MultiSelectOptionScreen
onSelect={handleSelect}
filterHeaderText={FilterDisplayName.artistNationalities}
filterOptions={filterOptions}
navigation={navigation}
searchable
{...(isActive ? { rightButtonText: "Clear", onRightButtonPress: handleClear } : {})}
/>
)
}
|
{
"content_hash": "156d664d4053434781261a8bb8fbd2c4",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 99,
"avg_line_length": 39.7,
"alnum_prop": 0.743073047858942,
"repo_name": "artsy/eigen",
"id": "420c1b7ed2959f49a25f14b9e92e459e27807f93",
"size": "1588",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/app/Components/ArtworkFilter/Filters/ArtistNationalitiesOptions.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4714"
},
{
"name": "Java",
"bytes": "20632"
},
{
"name": "JavaScript",
"bytes": "53066"
},
{
"name": "Objective-C",
"bytes": "863169"
},
{
"name": "Ruby",
"bytes": "29876"
},
{
"name": "Shell",
"bytes": "17266"
},
{
"name": "Starlark",
"bytes": "602"
},
{
"name": "Swift",
"bytes": "471776"
},
{
"name": "TypeScript",
"bytes": "6136180"
},
{
"name": "Vim Script",
"bytes": "428"
}
],
"symlink_target": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.