text
stringlengths 2
99.9k
| meta
dict |
---|---|
/****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* 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.
*
****************************************************************************/
/****************************************************************************
* libc/string/lib_strcasecmp.c
*
* Copyright (C) 2008-2009, 2011 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
/****************************************************************************
* Included Files
*****************************************************************************/
#include <tinyara/config.h>
#include <strings.h>
#include <ctype.h>
/****************************************************************************
* Public Functions
*****************************************************************************/
#ifndef CONFIG_ARCH_STRCMP
int strcasecmp(const char *cs, const char *ct)
{
int result;
for (;;) {
if ((result = (int)toupper(*cs) - (int)toupper(*ct)) != 0 || !*cs) {
break;
}
cs++;
ct++;
}
return result;
}
#endif
| {
"pile_set_name": "Github"
} |
{
"name": "Flot",
"version": "0.8.2",
"main": "jquery.flot.js",
"scripts": {
"test": "make test"
},
"devDependencies": {
"jshint": "0.9.1"
}
}
| {
"pile_set_name": "Github"
} |
using System;
using BuildVision.Common;
using BuildVision.UI.Models;
namespace BuildVision.UI.Settings.Models
{
public class BuildMessagesSettings : SettingsBase
{
private BuildMajorMessageFormat _majorMessageFormat = BuildMajorMessageFormat.Entire;
private string _buildBeginMajorMessageStringFormat = "{0} ...";
private string _buildDoneMajorMessageStringFormat = "{0}";
private bool _showSolutionName = true;
private bool _showProjectName = true;
private string _dateTimeFormat = "HH:mm:ss";
private string _timeSpanFormat = @"mm\:ss";
private bool _showExtraMessage = true;
private BuildExtraMessageFormat _extraMessageFormat = BuildExtraMessageFormat.Custom;
private string _extraMessageStringFormat = " ({0})";
private int _extraMessageDelay = 5;
public BuildMajorMessageFormat MajorMessageFormat
{
get => _majorMessageFormat;
set => SetProperty(ref _majorMessageFormat, value);
}
public BuildExtraMessageFormat ExtraMessageFormat
{
get => _extraMessageFormat;
set => SetProperty(ref _extraMessageFormat, value);
}
public bool ShowSolutionName
{
get => _showSolutionName;
set => SetProperty(ref _showSolutionName, value);
}
public bool ShowProjectName
{
get => _showProjectName;
set => SetProperty(ref _showProjectName, value);
}
public bool ShowExtraMessage
{
get => _showExtraMessage;
set => SetProperty(ref _showExtraMessage, value);
}
public int ExtraMessageDelay
{
get => _extraMessageDelay;
set => SetProperty(ref _extraMessageDelay, value);
}
public string BuildBeginMajorMessageStringFormat
{
get => _buildBeginMajorMessageStringFormat;
set
{
if (_buildBeginMajorMessageStringFormat != value)
{
_buildBeginMajorMessageStringFormat = value;
OnPropertyChanged(nameof(BuildBeginMajorMessageStringFormat));
if (!value.Contains("{0}"))
{
throw new FormatException("Format must contain '{0}' argument.");
}
string tmp = string.Format(value, "test");
}
}
}
public string BuildDoneMajorMessageStringFormat
{
get => _buildDoneMajorMessageStringFormat;
set
{
if (_buildDoneMajorMessageStringFormat != value)
{
_buildDoneMajorMessageStringFormat = value;
OnPropertyChanged(nameof(BuildDoneMajorMessageStringFormat));
if (!value.Contains("{0}"))
{
throw new FormatException("Format must contain '{0}' argument.");
}
string tmp = string.Format(value, "test");
}
}
}
public string DateTimeFormat
{
get => _dateTimeFormat;
set
{
if (_dateTimeFormat != value)
{
_dateTimeFormat = value;
OnPropertyChanged(nameof(DateTimeFormat));
var tmp = DateTime.Now.ToString(value);
}
}
}
public string TimeSpanFormat
{
get => _timeSpanFormat;
set
{
if (_timeSpanFormat != value)
{
_timeSpanFormat = value;
OnPropertyChanged(nameof(TimeSpanFormat));
var tmp = TimeSpan.MaxValue.ToString(value);
}
}
}
public string ExtraMessageStringFormat
{
get => _extraMessageStringFormat;
set
{
if (_extraMessageStringFormat != value)
{
_extraMessageStringFormat = value;
OnPropertyChanged(nameof(ExtraMessageStringFormat));
if (!value.Contains("{0}"))
{
throw new FormatException("Format must contain '{0}' argument.");
}
var tmp = string.Format(value, "test");
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-10 07:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('main', '0022_auto_20171110_0857'),
]
operations = [
migrations.AddField(
model_name='template',
name='inventory',
field=models.CharField(blank=True, default=None, max_length=128, null=True),
),
migrations.AddField(
model_name='template',
name='project',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='main.Project'),
),
migrations.AlterIndexTogether(
name='template',
index_together=set([('id', 'name', 'kind', 'inventory', 'project')]),
),
]
| {
"pile_set_name": "Github"
} |
<!doctype html>
<title>CodeMirror: IDL mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="idl.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">IDL</a>
</ul>
</div>
<article>
<h2>IDL mode</h2>
<div><textarea id="code" name="code">
;; Example IDL code
FUNCTION mean_and_stddev,array
;; This program reads in an array of numbers
;; and returns a structure containing the
;; average and standard deviation
ave = 0.0
count = 0.0
for i=0,N_ELEMENTS(array)-1 do begin
ave = ave + array[i]
count = count + 1
endfor
ave = ave/count
std = stddev(array)
return, {average:ave,std:std}
END
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: {name: "idl",
version: 1,
singleLineStringErrors: false},
lineNumbers: true,
indentUnit: 4,
matchBrackets: true
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-idl</code>.</p>
</article>
| {
"pile_set_name": "Github"
} |
package com.thinkbiganalytics.scheduler.util;
/*-
* #%L
* thinkbig-commons-util
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import org.apache.commons.lang3.StringUtils;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.Seconds;
import org.quartz.CronExpression;
import java.text.ParseException;
/**
* Converts a simple timer string such as 5 sec, 200 min, 50 days and converts it to a valid cron Expression
*/
public class TimerToCronExpression {
/**
* Parse a timer string to a Joda time period
*
* @param timer a string indicating a time unit (i.e. 5 sec)
* @param periodType the Period unit to use.
*/
public static Period timerStringToPeriod(String timer, PeriodType periodType) {
String cronString = null;
Integer time = Integer.parseInt(StringUtils.substringBefore(timer, " "));
String units = StringUtils.substringAfter(timer, " ").toLowerCase();
//time to years,days,months,hours,min, sec
Integer days = 0;
Integer hours = 0;
Integer min = 0;
Integer sec = 0;
Period p = null;
if (units.startsWith("sec")) {
p = Period.seconds(time);
} else if (units.startsWith("min")) {
p = Period.minutes(time);
} else if (units.startsWith("hr") || units.startsWith("hour")) {
p = Period.hours(time);
} else if (units.startsWith("day")) {
p = Period.days(time);
}
if (periodType != null) {
p = p.normalizedStandard(periodType);
} else {
}
return p;
}
/**
* Parse a timer string to a Joda time period
*/
public static Period timerStringToPeriod(String timer) {
return timerStringToPeriod(timer, PeriodType.dayTime());
}
/**
* Pass in a time String with a single unit the Max Unit is days (sec or secs, min or mins, hrs or hours, day or days) Examples: 5 sec, 100 min, 30 days, 20 hrs
*/
public static CronExpression timerToCronExpression(String timer) throws ParseException {
Period p = timerStringToPeriod(timer);
if (p != null) {
String cron = getSecondsCron(p) + " " + getMinutesCron(p) + " " + getHoursCron(p) + " " + getDaysCron(p) + " * ? *";
return new CronExpression(cron);
}
return null;
}
private static String getSecondsCron(Period p) {
Integer sec = p.getSeconds();
Seconds s = p.toStandardSeconds();
Integer seconds = s.getSeconds();
String str = "0" + (sec > 0 ? "/" + sec : "");
if (seconds > 60) {
str = sec + "";
}
return str;
}
private static String getMinutesCron(Period p) {
Integer min = p.getMinutes();
Minutes m = p.toStandardMinutes();
Integer minutes = m.getMinutes();
String str = "0" + (min > 0 ? "/" + min : "");
if (minutes > 60) {
str = min + "";
}
return str;
}
private static String getHoursCron(Period p) {
Integer hrs = p.getHours();
Hours h = p.toStandardHours();
Integer hours = h.getHours();
String str = "0" + (hrs > 0 ? "/" + hrs : "");
if (hours > 24) {
str = hrs + "";
}
return str;
}
private static String getDaysCron(Period p) {
Integer days = p.getDays();
String str = "1" + (days > 0 ? "/" + days : "/1");
return str;
}
}
| {
"pile_set_name": "Github"
} |
# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For IE 9-11 support, please uncomment the last line of the file and adjust as needed
> 0.5%
last 2 versions
Firefox ESR
not dead
# IE 9-11 | {
"pile_set_name": "Github"
} |
package com.wrbug.developerhelper.ui.activity.xposed.shellmanager
import android.content.Context
import android.content.Intent
import com.wrbug.developerhelper.R
import com.wrbug.developerhelper.commonutil.entity.ApkInfo
import com.wrbug.developerhelper.ipc.processshare.manager.DumpDexListProcessDataManager
import com.wrbug.developerhelper.ui.activity.xposed.BaseXposedAppManagerActivity
import com.wrbug.developerhelper.ui.activity.xposed.XposedAppListAdapter
class ShellAppManagerActivity : BaseXposedAppManagerActivity() {
override fun getManagerTitle(): String = getString(R.string.shell_app_manager)
override fun getAppEnableStatus(): Map<String, Boolean> {
val packageNames = DumpDexListProcessDataManager.instance.getData()
return packageNames
}
override fun onChanged(adapter: XposedAppListAdapter, apkInfo: ApkInfo, isChecked: Boolean) {
DumpDexListProcessDataManager.instance.setData(apkInfo.applicationInfo.packageName to isChecked)
}
companion object {
fun start(context: Context) {
context.startActivity(Intent(context, ShellAppManagerActivity::class.java))
}
}
}
| {
"pile_set_name": "Github"
} |
module BubbleWrap
module Motion
class Gyroscope < GenericMotionInterface
def start(options={}, &handler)
if options.key?(:interval)
@manager.gyroUpdateInterval = options[:interval]
end
if handler
queue = convert_queue(options[:queue])
@manager.startGyroUpdatesToQueue(queue, withHandler: internal_handler(handler))
else
@manager.startGyroUpdates
end
return self
end
private def handle_result(result_data, error, handler)
if result_data
result = {
data: result_data,
rotation: result_data.rotationRate,
x: result_data.rotationRate.x,
y: result_data.rotationRate.y,
z: result_data.rotationRate.z,
}
else
result = nil
end
handler.call(result, error)
end
def available?
@manager.gyroAvailable?
end
def active?
@manager.gyroActive?
end
def data
@manager.gyroData
end
def stop
@manager.stopGyroUpdates
end
end
end
end
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>"queryable/queryable" | smoke-node</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">smoke-node</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="_queryable_queryable_.html">"queryable/queryable"</a>
</li>
</ul>
<h1>External module "queryable/queryable"</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-external">
<h3>Classes</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-class tsd-parent-kind-external-module tsd-has-type-parameter tsd-is-external"><a href="../classes/_queryable_queryable_.queryable.html" class="tsd-kind-icon">Queryable</a></li>
</ul>
</section>
</div>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class="current tsd-kind-external-module tsd-is-external">
<a href="_queryable_queryable_.html">"queryable/queryable"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-has-type-parameter tsd-is-external">
<a href="../classes/_queryable_queryable_.queryable.html" class="tsd-kind-icon">Queryable</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
void TdApi::release()
{
this->api->Release()
};
bool TdApi::init()
{
this->active = true;
this->task_thread = thread(&MdApi::processTask, this);
this->api->Init();
};
void TdApi::registerFront(string pszFrontAddress)
{
this->api->RegisterFront(string pszFrontAddress)
};
void TdApi::subscribePrivateTopic(KS_TE_RESUME_TYPE reqid)
{
this->api->SubscribePrivateTopic(KS_TE_RESUME_TYPE reqid)
};
void TdApi::subscribePublicTopic(KS_TE_RESUME_TYPE reqid)
{
this->api->SubscribePublicTopic(KS_TE_RESUME_TYPE reqid)
};
void createGoldQutoApi(string pszFlowPath)
{
this->api = CKSGoldQuotApi::CreateGoldQutoApi(pszFlowPath.c_str());
this->api->RegisterSpi(this);
};
int TdApi::join()
{
int i =this->api->Join()
return i;
};
int TdApi::reqUserLogin(const dict &req, int reqid)
{
CThostFtdcReqUserLoginField myreq = CThostFtdcReqUserLoginField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "AccountID", myreq.AccountID);
getInt(req, "LoginType", &myreq.LoginType);
getString(req, "Password", myreq.Password);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
getString(req, "UserProductionInfo", myreq.UserProductionInfo);
getString(req, "ProtocolInfo", myreq.ProtocolInfo);
int i = this->api->ReqUserLogin(&myreq, reqid);
return i;
};
int TdApi::reqUserLogout(const dict &req, int reqid)
{
CThostFtdcUserLogoutField myreq = CThostFtdcUserLogoutField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
getString(req, "ClientID", myreq.ClientID);
int i = this->api->ReqUserLogout(&myreq, reqid);
return i;
};
int TdApi::reqQryInstrument(const dict &req, int reqid)
{
CThostFtdcQryInstrumentField myreq = CThostFtdcQryInstrumentField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "ContractID", myreq.ContractID);
getString(req, "ProductID", myreq.ProductID);
int i = this->api->ReqQryInstrument(&myreq, reqid);
return i;
};
int TdApi::reqQryVarietyCode(const dict &req, int reqid)
{
CThostFtdcQryVarietyCodeField myreq = CThostFtdcQryVarietyCodeField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "VarietyID", myreq.VarietyID);
getString(req, "ProductID", myreq.ProductID);
int i = this->api->ReqQryVarietyCode(&myreq, reqid);
return i;
};
int TdApi::reqOrderInsert(const dict &req, int reqid)
{
CThostFtdcInputOrderField myreq = CThostFtdcInputOrderField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "SeatID", myreq.SeatID);
getString(req, "ClientID", myreq.ClientID);
getString(req, "TradeCode", myreq.TradeCode);
getString(req, "InstID", myreq.InstID);
getChar(req, "BuyOrSell", &myreq.BuyOrSell);
getChar(req, "OffsetFlag", &myreq.OffsetFlag);
getInt(req, "Amount", &myreq.Amount);
getDouble(req, "Price", &myreq.Price);
getString(req, "MarketID", myreq.MarketID);
getString(req, "OrderRef", myreq.OrderRef);
getInt(req, "SessionID", &myreq.SessionID);
getChar(req, "HedgeFlag", &myreq.HedgeFlag);
getString(req, "CmdType", myreq.CmdType);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqOrderInsert(&myreq, reqid);
return i;
};
int TdApi::reqOrderAction(const dict &req, int reqid)
{
CThostFtdcInputOrderActionField myreq = CThostFtdcInputOrderActionField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "LocalOrderNo", myreq.LocalOrderNo);
getString(req, "MarketID", myreq.MarketID);
getString(req, "OrderRef", myreq.OrderRef);
getInt(req, "SessionID", &myreq.SessionID);
getInt(req, "RequestID", &myreq.RequestID);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqOrderAction(&myreq, reqid);
return i;
};
int TdApi::reqQryInvestorPosition(const dict &req, int reqid)
{
CThostFtdcQryInvestorPositionField myreq = CThostFtdcQryInvestorPositionField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "MarketID", myreq.MarketID);
getString(req, "InstID", myreq.InstID);
int i = this->api->ReqQryInvestorPosition(&myreq, reqid);
return i;
};
int TdApi::reqQryTradingAccount(const dict &req, int reqid)
{
CThostFtdcQryTradingAccountField myreq = CThostFtdcQryTradingAccountField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
int i = this->api->ReqQryTradingAccount(&myreq, reqid);
return i;
};
int TdApi::reqQryTrade(const dict &req, int reqid)
{
CThostFtdcQryTradeField myreq = CThostFtdcQryTradeField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "MarketID", myreq.MarketID);
getString(req, "InstID", myreq.InstID);
getString(req, "LocalOrderNo", myreq.LocalOrderNo);
int i = this->api->ReqQryTrade(&myreq, reqid);
return i;
};
int TdApi::reqQryOrder(const dict &req, int reqid)
{
CThostFtdcQryOrderField myreq = CThostFtdcQryOrderField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "MarketID", myreq.MarketID);
getString(req, "LocalOrderNo", myreq.LocalOrderNo);
getString(req, "InstID", myreq.InstID);
getChar(req, "HedgeFlag", &myreq.HedgeFlag);
getString(req, "CmdType", myreq.CmdType);
getInt(req, "SessionID", &myreq.SessionID);
getString(req, "OrderRef", myreq.OrderRef);
int i = this->api->ReqQryOrder(&myreq, reqid);
return i;
};
int TdApi::reqQryStorage(const dict &req, int reqid)
{
CThostFtdcQryStorageField myreq = CThostFtdcQryStorageField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "VarietyID", myreq.VarietyID);
getString(req, "ClientID", myreq.ClientID);
int i = this->api->ReqQryStorage(&myreq, reqid);
return i;
};
int TdApi::reqQryCostMarginFeeRate(const dict &req, int reqid)
{
CThostFtdcQryCostMarginFeeField myreq = CThostFtdcQryCostMarginFeeField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "InstID", myreq.InstID);
int i = this->api->ReqQryCostMarginFeeRate(&myreq, reqid);
return i;
};
int TdApi::reqConditionOrderInsert(const dict &req, int reqid)
{
CThostFtdcConditionOrderField myreq = CThostFtdcConditionOrderField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ExchangeID", myreq.ExchangeID);
getString(req, "SeatID", myreq.SeatID);
getString(req, "ClientID", myreq.ClientID);
getString(req, "TradeCode", myreq.TradeCode);
getString(req, "MarketID", myreq.MarketID);
getString(req, "InstID", myreq.InstID);
getChar(req, "BuyOrSell", &myreq.BuyOrSell);
getChar(req, "OffsetFlag", &myreq.OffsetFlag);
getInt(req, "Amount", &myreq.Amount);
getChar(req, "OrderType", &myreq.OrderType);
getChar(req, "MiddleFlag", &myreq.MiddleFlag);
getChar(req, "PriceFlag", &myreq.PriceFlag);
getDouble(req, "Price", &myreq.Price);
getDouble(req, "TrigPrice", &myreq.TrigPrice);
getInt(req, "ValidDay", &myreq.ValidDay);
getInt(req, "VolumnCheck", &myreq.VolumnCheck);
getString(req, "OrderRef", myreq.OrderRef);
getInt(req, "SessionID", &myreq.SessionID);
getString(req, "CmdType", myreq.CmdType);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqConditionOrderInsert(&myreq, reqid);
return i;
};
int TdApi::reqConditionOrderAction(const dict &req, int reqid)
{
CThostFtdcConditionActionOrderField myreq = CThostFtdcConditionActionOrderField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "ConditionOrderNo", myreq.ConditionOrderNo);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqConditionOrderAction(&myreq, reqid);
return i;
};
int TdApi::reqQryConditionOrder(const dict &req, int reqid)
{
CThostFtdcConditionOrderQryField myreq = CThostFtdcConditionOrderQryField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "ConditionOrderNo", myreq.ConditionOrderNo);
getChar(req, "Status", &myreq.Status);
getString(req, "InstID", myreq.InstID);
getString(req, "StartDate", myreq.StartDate);
getString(req, "EndDate", myreq.EndDate);
getString(req, "OrderRef", myreq.OrderRef);
getInt(req, "SessionID", &myreq.SessionID);
getString(req, "CmdType", myreq.CmdType);
int i = this->api->ReqQryConditionOrder(&myreq, reqid);
return i;
};
int TdApi::reqQryConditionOrderTrade(const dict &req, int reqid)
{
CThostFtdcConditionOrderMatchField myreq = CThostFtdcConditionOrderMatchField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "InstID", myreq.InstID);
getString(req, "ConditionOrderNo", myreq.ConditionOrderNo);
getString(req, "LocalOrderNo", myreq.LocalOrderNo);
int i = this->api->ReqQryConditionOrderTrade(&myreq, reqid);
return i;
};
int TdApi::reqQryClientSessionInfo(const dict &req, int reqid)
{
CThostFtdcQryClientSessionField myreq = CThostFtdcQryClientSessionField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
int i = this->api->ReqQryClientSessionInfo(&myreq, reqid);
return i;
};
int TdApi::reqQryQuotation(const dict &req, int reqid)
{
CThostFtdcQryQuotationField myreq = CThostFtdcQryQuotationField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "marketID", myreq.marketID);
getString(req, "InstrumentID", myreq.InstrumentID);
int i = this->api->ReqQryQuotation(&myreq, reqid);
return i;
};
int TdApi::reqQryInvestorPositionDetail(const dict &req, int reqid)
{
CThostFtdcQryInvestorPositionDetailField myreq = CThostFtdcQryInvestorPositionDetailField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "QueryData", myreq.QueryData);
int i = this->api->ReqQryInvestorPositionDetail(&myreq, reqid);
return i;
};
int TdApi::reqModifyPassword(const dict &req, int reqid)
{
CThostFtdcModifyPasswordField myreq = CThostFtdcModifyPasswordField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "OldPassword", myreq.OldPassword);
getString(req, "NewPassword", myreq.NewPassword);
int i = this->api->ReqModifyPassword(&myreq, reqid);
return i;
};
int TdApi::reqQryHisCapital(const dict &req, int reqid)
{
CThostFtdcQryHisCapitalField myreq = CThostFtdcQryHisCapitalField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "StartDate", myreq.StartDate);
getString(req, "EndDate", myreq.EndDate);
int i = this->api->ReqQryHisCapital(&myreq, reqid);
return i;
};
int TdApi::reqETFSubScription(const dict &req, int reqid)
{
CThostFtdcSubScriptionField myreq = CThostFtdcSubScriptionField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "SeatNo", myreq.SeatNo);
getString(req, "EtfCode", myreq.EtfCode);
getString(req, "InstrumentID1", myreq.InstrumentID1);
getDouble(req, "weight1", &myreq.weight1);
getString(req, "InstrumentID2", myreq.InstrumentID2);
getDouble(req, "weight2", &myreq.weight2);
getString(req, "InstrumentID3", myreq.InstrumentID3);
getDouble(req, "weight3", &myreq.weight3);
getString(req, "InstrumentID4", myreq.InstrumentID4);
getDouble(req, "weight4", &myreq.weight4);
getString(req, "InstrumentID5", myreq.InstrumentID5);
getDouble(req, "weight5", &myreq.weight5);
getDouble(req, "Totalweight", &myreq.Totalweight);
getInt(req, "SessionID", &myreq.SessionID);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqETFSubScription(&myreq, reqid);
return i;
};
int TdApi::reqETFApplyForPurchase(const dict &req, int reqid)
{
CThostFtdcApplyForPurchaseField myreq = CThostFtdcApplyForPurchaseField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "SeatNo", myreq.SeatNo);
getString(req, "EtfCode", myreq.EtfCode);
getString(req, "InstrumentID1", myreq.InstrumentID1);
getDouble(req, "weight1", &myreq.weight1);
getString(req, "InstrumentID2", myreq.InstrumentID2);
getDouble(req, "weight2", &myreq.weight2);
getString(req, "InstrumentID3", myreq.InstrumentID3);
getDouble(req, "weight3", &myreq.weight3);
getString(req, "InstrumentID4", myreq.InstrumentID4);
getDouble(req, "weight4", &myreq.weight4);
getString(req, "InstrumentID5", myreq.InstrumentID5);
getDouble(req, "weight5", &myreq.weight5);
getDouble(req, "Totalweight", &myreq.Totalweight);
getInt(req, "SessionID", &myreq.SessionID);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqETFApplyForPurchase(&myreq, reqid);
return i;
};
int TdApi::reqETFRedeem(const dict &req, int reqid)
{
CThostFtdcRedeemField myreq = CThostFtdcRedeemField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "SeatNo", myreq.SeatNo);
getString(req, "EtfCode", myreq.EtfCode);
getInt(req, "SessionID", &myreq.SessionID);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqETFRedeem(&myreq, reqid);
return i;
};
int TdApi::reqETFAccountBinding(const dict &req, int reqid)
{
CThostFtdcETFBingingField myreq = CThostFtdcETFBingingField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "StockTradeCode", myreq.StockTradeCode);
getString(req, "EtfCode", myreq.EtfCode);
getChar(req, "EtfManagedUnit", &myreq.EtfManagedUnit);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqETFAccountBinding(&myreq, reqid);
return i;
};
int TdApi::reqETFAccountUnbinding(const dict &req, int reqid)
{
CThostFtdcETFUnBingingField myreq = CThostFtdcETFUnBingingField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
getString(req, "StockTradeCode", myreq.StockTradeCode);
getString(req, "EtfCode", myreq.EtfCode);
getString(req, "LoginIp", myreq.LoginIp);
getString(req, "MacAddress", myreq.MacAddress);
int i = this->api->ReqETFAccountUnbinding(&myreq, reqid);
return i;
};
int TdApi::reqETFTradeDetail(const dict &req, int reqid)
{
CThostFtdcQryETFTradeDetailField myreq = CThostFtdcQryETFTradeDetailField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "ClientID", myreq.ClientID);
int i = this->api->ReqETFTradeDetail(&myreq, reqid);
return i;
};
int TdApi::reqETFPcfDetail(const dict &req, int reqid)
{
CThostFtdcQryETFPcfDetailField myreq = CThostFtdcQryETFPcfDetailField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "StartDate", myreq.StartDate);
getString(req, "EndDate", myreq.EndDate);
getString(req, "EtfCode", myreq.EtfCode);
int i = this->api->ReqETFPcfDetail(&myreq, reqid);
return i;
};
int TdApi::reqBOCMoneyIO(const dict &req, int reqid)
{
CThostFtdcBOCMoneyIOField myreq = CThostFtdcBOCMoneyIOField();
memset(&myreq, 0, sizeof(myreq));
getString(req, "TransFerType", myreq.TransFerType);
getDouble(req, "TransFerAmount", &myreq.TransFerAmount);
getString(req, "TradePassword", myreq.TradePassword);
getString(req, "ClientID", myreq.ClientID);
int i = this->api->ReqBOCMoneyIO(&myreq, reqid);
return i;
};
| {
"pile_set_name": "Github"
} |
package types
import (
"fmt"
)
type CodeLocation struct {
FileName string
LineNumber int
FullStackTrace string
}
func (codeLocation CodeLocation) String() string {
return fmt.Sprintf("%s:%d", codeLocation.FileName, codeLocation.LineNumber)
}
| {
"pile_set_name": "Github"
} |
// @flow
interface Ok {
[key: string]: string;
}
interface Bad {
[k1: string]: string;
[k2: number]: number; // error: not supported (yet)
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 1e20e66aa2deb7943993c444137d9acd
timeCreated: 1487328709
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
## `filepath-securejoin` ##
[](https://travis-ci.org/cyphar/filepath-securejoin)
An implementation of `SecureJoin`, a [candidate for inclusion in the Go
standard library][go#20126]. The purpose of this function is to be a "secure"
alternative to `filepath.Join`, and in particular it provides certain
guarantees that are not provided by `filepath.Join`.
This is the function prototype:
```go
func SecureJoin(root, unsafePath string) (string, error)
```
This library **guarantees** the following:
* If no error is set, the resulting string **must** be a child path of
`SecureJoin` and will not contain any symlink path components (they will all
be expanded).
* When expanding symlinks, all symlink path components **must** be resolved
relative to the provided root. In particular, this can be considered a
userspace implementation of how `chroot(2)` operates on file paths. Note that
these symlinks will **not** be expanded lexically (`filepath.Clean` is not
called on the input before processing).
* Non-existant path components are unaffected by `SecureJoin` (similar to
`filepath.EvalSymlinks`'s semantics).
* The returned path will always be `filepath.Clean`ed and thus not contain any
`..` components.
A (trivial) implementation of this function on GNU/Linux systems could be done
with the following (note that this requires root privileges and is far more
opaque than the implementation in this library, and also requires that
`readlink` is inside the `root` path):
```go
package securejoin
import (
"os/exec"
"path/filepath"
)
func SecureJoin(root, unsafePath string) (string, error) {
unsafePath = string(filepath.Separator) + unsafePath
cmd := exec.Command("chroot", root,
"readlink", "--canonicalize-missing", "--no-newline", unsafePath)
output, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
expanded := string(output)
return filepath.Join(root, expanded), nil
}
```
[go#20126]: https://github.com/golang/go/issues/20126
### License ###
The license of this project is the same as Go, which is a BSD 3-clause license
available in the `LICENSE` file.
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root> | {
"pile_set_name": "Github"
} |
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Disabling obfuscation is useful if you collect stack traces from production crashes
# (unless you are using a system that supports de-obfuscate the stack traces).
-dontobfuscate
# React Native
# Keep our interfaces so they can be used by other ProGuard rules.
# See http://sourceforge.net/p/proguard/bugs/466/
-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters
-keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip
# Do not strip any method/class that is annotated with @DoNotStrip
-keep @com.facebook.proguard.annotations.DoNotStrip class *
-keep @com.facebook.common.internal.DoNotStrip class *
-keepclassmembers class * {
@com.facebook.proguard.annotations.DoNotStrip *;
@com.facebook.common.internal.DoNotStrip *;
}
-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
void set*(***);
*** get*();
}
-keep class * extends com.facebook.react.bridge.JavaScriptModule { *; }
-keep class * extends com.facebook.react.bridge.NativeModule { *; }
-keepclassmembers,includedescriptorclasses class * { native <methods>; }
-keepclassmembers class * { @com.facebook.react.uimanager.UIProp <fields>; }
-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }
-dontwarn com.facebook.react.**
# TextLayoutBuilder uses a non-public Android constructor within StaticLayout.
# See libs/proxy/src/main/java/com/facebook/fbui/textlayoutbuilder/proxy for details.
-dontwarn android.text.StaticLayout
# okhttp
-keepattributes Signature
-keepattributes *Annotation*
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
# okio
-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**
# Firefox accounts component
-dontwarn java.awt.*
-keep class com.sun.jna.* { *; }
-keepclassmembers class * extends com.sun.jna.* { public *; }
-ignorewarnings
| {
"pile_set_name": "Github"
} |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_video.h
*
* Header file for SDL video functions.
*/
#ifndef SDL_video_h_
#define SDL_video_h_
#include "SDL_stdinc.h"
#include "SDL_pixels.h"
#include "SDL_rect.h"
#include "SDL_surface.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The structure that defines a display mode
*
* \sa SDL_GetNumDisplayModes()
* \sa SDL_GetDisplayMode()
* \sa SDL_GetDesktopDisplayMode()
* \sa SDL_GetCurrentDisplayMode()
* \sa SDL_GetClosestDisplayMode()
* \sa SDL_SetWindowDisplayMode()
* \sa SDL_GetWindowDisplayMode()
*/
typedef struct
{
Uint32 format; /**< pixel format */
int w; /**< width, in screen coordinates */
int h; /**< height, in screen coordinates */
int refresh_rate; /**< refresh rate (or zero for unspecified) */
void *driverdata; /**< driver-specific data, initialize to 0 */
} SDL_DisplayMode;
/**
* \brief The type used to identify a window
*
* \sa SDL_CreateWindow()
* \sa SDL_CreateWindowFrom()
* \sa SDL_DestroyWindow()
* \sa SDL_GetWindowData()
* \sa SDL_GetWindowFlags()
* \sa SDL_GetWindowGrab()
* \sa SDL_GetWindowPosition()
* \sa SDL_GetWindowSize()
* \sa SDL_GetWindowTitle()
* \sa SDL_HideWindow()
* \sa SDL_MaximizeWindow()
* \sa SDL_MinimizeWindow()
* \sa SDL_RaiseWindow()
* \sa SDL_RestoreWindow()
* \sa SDL_SetWindowData()
* \sa SDL_SetWindowFullscreen()
* \sa SDL_SetWindowGrab()
* \sa SDL_SetWindowIcon()
* \sa SDL_SetWindowPosition()
* \sa SDL_SetWindowSize()
* \sa SDL_SetWindowBordered()
* \sa SDL_SetWindowResizable()
* \sa SDL_SetWindowTitle()
* \sa SDL_ShowWindow()
*/
typedef struct SDL_Window SDL_Window;
/**
* \brief The flags on a window
*
* \sa SDL_GetWindowFlags()
*/
typedef enum
{
SDL_WINDOW_FULLSCREEN = 0x00000001, /**< fullscreen window */
SDL_WINDOW_OPENGL = 0x00000002, /**< window usable with OpenGL context */
SDL_WINDOW_SHOWN = 0x00000004, /**< window is visible */
SDL_WINDOW_HIDDEN = 0x00000008, /**< window is not visible */
SDL_WINDOW_BORDERLESS = 0x00000010, /**< no window decoration */
SDL_WINDOW_RESIZABLE = 0x00000020, /**< window can be resized */
SDL_WINDOW_MINIMIZED = 0x00000040, /**< window is minimized */
SDL_WINDOW_MAXIMIZED = 0x00000080, /**< window is maximized */
SDL_WINDOW_INPUT_GRABBED = 0x00000100, /**< window has grabbed input focus */
SDL_WINDOW_INPUT_FOCUS = 0x00000200, /**< window has input focus */
SDL_WINDOW_MOUSE_FOCUS = 0x00000400, /**< window has mouse focus */
SDL_WINDOW_FULLSCREEN_DESKTOP = ( SDL_WINDOW_FULLSCREEN | 0x00001000 ),
SDL_WINDOW_FOREIGN = 0x00000800, /**< window not created by SDL */
SDL_WINDOW_ALLOW_HIGHDPI = 0x00002000, /**< window should be created in high-DPI mode if supported.
On macOS NSHighResolutionCapable must be set true in the
application's Info.plist for this to have any effect. */
SDL_WINDOW_MOUSE_CAPTURE = 0x00004000, /**< window has mouse captured (unrelated to INPUT_GRABBED) */
SDL_WINDOW_ALWAYS_ON_TOP = 0x00008000, /**< window should always be above others */
SDL_WINDOW_SKIP_TASKBAR = 0x00010000, /**< window should not be added to the taskbar */
SDL_WINDOW_UTILITY = 0x00020000, /**< window should be treated as a utility window */
SDL_WINDOW_TOOLTIP = 0x00040000, /**< window should be treated as a tooltip */
SDL_WINDOW_POPUP_MENU = 0x00080000, /**< window should be treated as a popup menu */
SDL_WINDOW_VULKAN = 0x10000000 /**< window usable for Vulkan surface */
} SDL_WindowFlags;
/**
* \brief Used to indicate that you don't care what the window position is.
*/
#define SDL_WINDOWPOS_UNDEFINED_MASK 0x1FFF0000u
#define SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) (SDL_WINDOWPOS_UNDEFINED_MASK|(X))
#define SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED_DISPLAY(0)
#define SDL_WINDOWPOS_ISUNDEFINED(X) \
(((X)&0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK)
/**
* \brief Used to indicate that the window position should be centered.
*/
#define SDL_WINDOWPOS_CENTERED_MASK 0x2FFF0000u
#define SDL_WINDOWPOS_CENTERED_DISPLAY(X) (SDL_WINDOWPOS_CENTERED_MASK|(X))
#define SDL_WINDOWPOS_CENTERED SDL_WINDOWPOS_CENTERED_DISPLAY(0)
#define SDL_WINDOWPOS_ISCENTERED(X) \
(((X)&0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK)
/**
* \brief Event subtype for window events
*/
typedef enum
{
SDL_WINDOWEVENT_NONE, /**< Never used */
SDL_WINDOWEVENT_SHOWN, /**< Window has been shown */
SDL_WINDOWEVENT_HIDDEN, /**< Window has been hidden */
SDL_WINDOWEVENT_EXPOSED, /**< Window has been exposed and should be
redrawn */
SDL_WINDOWEVENT_MOVED, /**< Window has been moved to data1, data2
*/
SDL_WINDOWEVENT_RESIZED, /**< Window has been resized to data1xdata2 */
SDL_WINDOWEVENT_SIZE_CHANGED, /**< The window size has changed, either as
a result of an API call or through the
system or user changing the window size. */
SDL_WINDOWEVENT_MINIMIZED, /**< Window has been minimized */
SDL_WINDOWEVENT_MAXIMIZED, /**< Window has been maximized */
SDL_WINDOWEVENT_RESTORED, /**< Window has been restored to normal size
and position */
SDL_WINDOWEVENT_ENTER, /**< Window has gained mouse focus */
SDL_WINDOWEVENT_LEAVE, /**< Window has lost mouse focus */
SDL_WINDOWEVENT_FOCUS_GAINED, /**< Window has gained keyboard focus */
SDL_WINDOWEVENT_FOCUS_LOST, /**< Window has lost keyboard focus */
SDL_WINDOWEVENT_CLOSE, /**< The window manager requests that the window be closed */
SDL_WINDOWEVENT_TAKE_FOCUS, /**< Window is being offered a focus (should SetWindowInputFocus() on itself or a subwindow, or ignore) */
SDL_WINDOWEVENT_HIT_TEST /**< Window had a hit test that wasn't SDL_HITTEST_NORMAL. */
} SDL_WindowEventID;
/**
* \brief Event subtype for display events
*/
typedef enum
{
SDL_DISPLAYEVENT_NONE, /**< Never used */
SDL_DISPLAYEVENT_ORIENTATION /**< Display orientation has changed to data1 */
} SDL_DisplayEventID;
typedef enum
{
SDL_ORIENTATION_UNKNOWN, /**< The display orientation can't be determined */
SDL_ORIENTATION_LANDSCAPE, /**< The display is in landscape mode, with the right side up, relative to portrait mode */
SDL_ORIENTATION_LANDSCAPE_FLIPPED, /**< The display is in landscape mode, with the left side up, relative to portrait mode */
SDL_ORIENTATION_PORTRAIT, /**< The display is in portrait mode */
SDL_ORIENTATION_PORTRAIT_FLIPPED /**< The display is in portrait mode, upside down */
} SDL_DisplayOrientation;
/**
* \brief An opaque handle to an OpenGL context.
*/
typedef void *SDL_GLContext;
/**
* \brief OpenGL configuration attributes
*/
typedef enum
{
SDL_GL_RED_SIZE,
SDL_GL_GREEN_SIZE,
SDL_GL_BLUE_SIZE,
SDL_GL_ALPHA_SIZE,
SDL_GL_BUFFER_SIZE,
SDL_GL_DOUBLEBUFFER,
SDL_GL_DEPTH_SIZE,
SDL_GL_STENCIL_SIZE,
SDL_GL_ACCUM_RED_SIZE,
SDL_GL_ACCUM_GREEN_SIZE,
SDL_GL_ACCUM_BLUE_SIZE,
SDL_GL_ACCUM_ALPHA_SIZE,
SDL_GL_STEREO,
SDL_GL_MULTISAMPLEBUFFERS,
SDL_GL_MULTISAMPLESAMPLES,
SDL_GL_ACCELERATED_VISUAL,
SDL_GL_RETAINED_BACKING,
SDL_GL_CONTEXT_MAJOR_VERSION,
SDL_GL_CONTEXT_MINOR_VERSION,
SDL_GL_CONTEXT_EGL,
SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_SHARE_WITH_CURRENT_CONTEXT,
SDL_GL_FRAMEBUFFER_SRGB_CAPABLE,
SDL_GL_CONTEXT_RELEASE_BEHAVIOR,
SDL_GL_CONTEXT_RESET_NOTIFICATION,
SDL_GL_CONTEXT_NO_ERROR
} SDL_GLattr;
typedef enum
{
SDL_GL_CONTEXT_PROFILE_CORE = 0x0001,
SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002,
SDL_GL_CONTEXT_PROFILE_ES = 0x0004 /**< GLX_CONTEXT_ES2_PROFILE_BIT_EXT */
} SDL_GLprofile;
typedef enum
{
SDL_GL_CONTEXT_DEBUG_FLAG = 0x0001,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002,
SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004,
SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008
} SDL_GLcontextFlag;
typedef enum
{
SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0x0000,
SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x0001
} SDL_GLcontextReleaseFlag;
typedef enum
{
SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0x0000,
SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 0x0001
} SDL_GLContextResetNotification;
/* Function prototypes */
/**
* \brief Get the number of video drivers compiled into SDL
*
* \sa SDL_GetVideoDriver()
*/
extern DECLSPEC int SDLCALL SDL_GetNumVideoDrivers(void);
/**
* \brief Get the name of a built in video driver.
*
* \note The video drivers are presented in the order in which they are
* normally checked during initialization.
*
* \sa SDL_GetNumVideoDrivers()
*/
extern DECLSPEC const char *SDLCALL SDL_GetVideoDriver(int index);
/**
* \brief Initialize the video subsystem, optionally specifying a video driver.
*
* \param driver_name Initialize a specific driver by name, or NULL for the
* default video driver.
*
* \return 0 on success, -1 on error
*
* This function initializes the video subsystem; setting up a connection
* to the window manager, etc, and determines the available display modes
* and pixel formats, but does not initialize a window or graphics mode.
*
* \sa SDL_VideoQuit()
*/
extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name);
/**
* \brief Shuts down the video subsystem.
*
* This function closes all windows, and restores the original video mode.
*
* \sa SDL_VideoInit()
*/
extern DECLSPEC void SDLCALL SDL_VideoQuit(void);
/**
* \brief Returns the name of the currently initialized video driver.
*
* \return The name of the current video driver or NULL if no driver
* has been initialized
*
* \sa SDL_GetNumVideoDrivers()
* \sa SDL_GetVideoDriver()
*/
extern DECLSPEC const char *SDLCALL SDL_GetCurrentVideoDriver(void);
/**
* \brief Returns the number of available video displays.
*
* \sa SDL_GetDisplayBounds()
*/
extern DECLSPEC int SDLCALL SDL_GetNumVideoDisplays(void);
/**
* \brief Get the name of a display in UTF-8 encoding
*
* \return The name of a display, or NULL for an invalid display index.
*
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC const char * SDLCALL SDL_GetDisplayName(int displayIndex);
/**
* \brief Get the desktop area represented by a display, with the primary
* display located at 0,0
*
* \return 0 on success, or -1 if the index is out of range.
*
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayBounds(int displayIndex, SDL_Rect * rect);
/**
* \brief Get the usable desktop area represented by a display, with the
* primary display located at 0,0
*
* This is the same area as SDL_GetDisplayBounds() reports, but with portions
* reserved by the system removed. For example, on Mac OS X, this subtracts
* the area occupied by the menu bar and dock.
*
* Setting a window to be fullscreen generally bypasses these unusable areas,
* so these are good guidelines for the maximum space available to a
* non-fullscreen window.
*
* \return 0 on success, or -1 if the index is out of range.
*
* \sa SDL_GetDisplayBounds()
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect * rect);
/**
* \brief Get the dots/pixels-per-inch for a display
*
* \note Diagonal, horizontal and vertical DPI can all be optionally
* returned if the parameter is non-NULL.
*
* \return 0 on success, or -1 if no DPI information is available or the index is out of range.
*
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayDPI(int displayIndex, float * ddpi, float * hdpi, float * vdpi);
/**
* \brief Get the orientation of a display
*
* \return The orientation of the display, or SDL_ORIENTATION_UNKNOWN if it isn't available.
*
* \sa SDL_GetNumVideoDisplays()
*/
extern DECLSPEC SDL_DisplayOrientation SDLCALL SDL_GetDisplayOrientation(int displayIndex);
/**
* \brief Returns the number of available display modes.
*
* \sa SDL_GetDisplayMode()
*/
extern DECLSPEC int SDLCALL SDL_GetNumDisplayModes(int displayIndex);
/**
* \brief Fill in information about a specific display mode.
*
* \note The display modes are sorted in this priority:
* \li bits per pixel -> more colors to fewer colors
* \li width -> largest to smallest
* \li height -> largest to smallest
* \li refresh rate -> highest to lowest
*
* \sa SDL_GetNumDisplayModes()
*/
extern DECLSPEC int SDLCALL SDL_GetDisplayMode(int displayIndex, int modeIndex,
SDL_DisplayMode * mode);
/**
* \brief Fill in information about the desktop display mode.
*/
extern DECLSPEC int SDLCALL SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode);
/**
* \brief Fill in information about the current display mode.
*/
extern DECLSPEC int SDLCALL SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode);
/**
* \brief Get the closest match to the requested display mode.
*
* \param displayIndex The index of display from which mode should be queried.
* \param mode The desired display mode
* \param closest A pointer to a display mode to be filled in with the closest
* match of the available display modes.
*
* \return The passed in value \c closest, or NULL if no matching video mode
* was available.
*
* The available display modes are scanned, and \c closest is filled in with the
* closest mode matching the requested mode and returned. The mode format and
* refresh_rate default to the desktop mode if they are 0. The modes are
* scanned with size being first priority, format being second priority, and
* finally checking the refresh_rate. If all the available modes are too
* small, then NULL is returned.
*
* \sa SDL_GetNumDisplayModes()
* \sa SDL_GetDisplayMode()
*/
extern DECLSPEC SDL_DisplayMode * SDLCALL SDL_GetClosestDisplayMode(int displayIndex, const SDL_DisplayMode * mode, SDL_DisplayMode * closest);
/**
* \brief Get the display index associated with a window.
*
* \return the display index of the display containing the center of the
* window, or -1 on error.
*/
extern DECLSPEC int SDLCALL SDL_GetWindowDisplayIndex(SDL_Window * window);
/**
* \brief Set the display mode used when a fullscreen window is visible.
*
* By default the window's dimensions and the desktop format and refresh rate
* are used.
*
* \param window The window for which the display mode should be set.
* \param mode The mode to use, or NULL for the default mode.
*
* \return 0 on success, or -1 if setting the display mode failed.
*
* \sa SDL_GetWindowDisplayMode()
* \sa SDL_SetWindowFullscreen()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowDisplayMode(SDL_Window * window,
const SDL_DisplayMode
* mode);
/**
* \brief Fill in information about the display mode used when a fullscreen
* window is visible.
*
* \sa SDL_SetWindowDisplayMode()
* \sa SDL_SetWindowFullscreen()
*/
extern DECLSPEC int SDLCALL SDL_GetWindowDisplayMode(SDL_Window * window,
SDL_DisplayMode * mode);
/**
* \brief Get the pixel format associated with the window.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetWindowPixelFormat(SDL_Window * window);
/**
* \brief Create a window with the specified position, dimensions, and flags.
*
* \param title The title of the window, in UTF-8 encoding.
* \param x The x position of the window, ::SDL_WINDOWPOS_CENTERED, or
* ::SDL_WINDOWPOS_UNDEFINED.
* \param y The y position of the window, ::SDL_WINDOWPOS_CENTERED, or
* ::SDL_WINDOWPOS_UNDEFINED.
* \param w The width of the window, in screen coordinates.
* \param h The height of the window, in screen coordinates.
* \param flags The flags for the window, a mask of any of the following:
* ::SDL_WINDOW_FULLSCREEN, ::SDL_WINDOW_OPENGL,
* ::SDL_WINDOW_HIDDEN, ::SDL_WINDOW_BORDERLESS,
* ::SDL_WINDOW_RESIZABLE, ::SDL_WINDOW_MAXIMIZED,
* ::SDL_WINDOW_MINIMIZED, ::SDL_WINDOW_INPUT_GRABBED,
* ::SDL_WINDOW_ALLOW_HIGHDPI, ::SDL_WINDOW_VULKAN.
*
* \return The created window, or NULL if window creation failed.
*
* If the window is created with the SDL_WINDOW_ALLOW_HIGHDPI flag, its size
* in pixels may differ from its size in screen coordinates on platforms with
* high-DPI support (e.g. iOS and Mac OS X). Use SDL_GetWindowSize() to query
* the client area's size in screen coordinates, and SDL_GL_GetDrawableSize(),
* SDL_Vulkan_GetDrawableSize(), or SDL_GetRendererOutputSize() to query the
* drawable size in pixels.
*
* If the window is created with any of the SDL_WINDOW_OPENGL or
* SDL_WINDOW_VULKAN flags, then the corresponding LoadLibrary function
* (SDL_GL_LoadLibrary or SDL_Vulkan_LoadLibrary) is called and the
* corresponding UnloadLibrary function is called by SDL_DestroyWindow().
*
* If SDL_WINDOW_VULKAN is specified and there isn't a working Vulkan driver,
* SDL_CreateWindow() will fail because SDL_Vulkan_LoadLibrary() will fail.
*
* \note On non-Apple devices, SDL requires you to either not link to the
* Vulkan loader or link to a dynamic library version. This limitation
* may be removed in a future version of SDL.
*
* \sa SDL_DestroyWindow()
* \sa SDL_GL_LoadLibrary()
* \sa SDL_Vulkan_LoadLibrary()
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title,
int x, int y, int w,
int h, Uint32 flags);
/**
* \brief Create an SDL window from an existing native window.
*
* \param data A pointer to driver-dependent window creation data
*
* \return The created window, or NULL if window creation failed.
*
* \sa SDL_DestroyWindow()
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowFrom(const void *data);
/**
* \brief Get the numeric ID of a window, for logging purposes.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetWindowID(SDL_Window * window);
/**
* \brief Get a window from a stored ID, or NULL if it doesn't exist.
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromID(Uint32 id);
/**
* \brief Get the window flags.
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetWindowFlags(SDL_Window * window);
/**
* \brief Set the title of a window, in UTF-8 format.
*
* \sa SDL_GetWindowTitle()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowTitle(SDL_Window * window,
const char *title);
/**
* \brief Get the title of a window, in UTF-8 format.
*
* \sa SDL_SetWindowTitle()
*/
extern DECLSPEC const char *SDLCALL SDL_GetWindowTitle(SDL_Window * window);
/**
* \brief Set the icon for a window.
*
* \param window The window for which the icon should be set.
* \param icon The icon for the window.
*/
extern DECLSPEC void SDLCALL SDL_SetWindowIcon(SDL_Window * window,
SDL_Surface * icon);
/**
* \brief Associate an arbitrary named pointer with a window.
*
* \param window The window to associate with the pointer.
* \param name The name of the pointer.
* \param userdata The associated pointer.
*
* \return The previous value associated with 'name'
*
* \note The name is case-sensitive.
*
* \sa SDL_GetWindowData()
*/
extern DECLSPEC void* SDLCALL SDL_SetWindowData(SDL_Window * window,
const char *name,
void *userdata);
/**
* \brief Retrieve the data pointer associated with a window.
*
* \param window The window to query.
* \param name The name of the pointer.
*
* \return The value associated with 'name'
*
* \sa SDL_SetWindowData()
*/
extern DECLSPEC void *SDLCALL SDL_GetWindowData(SDL_Window * window,
const char *name);
/**
* \brief Set the position of a window.
*
* \param window The window to reposition.
* \param x The x coordinate of the window in screen coordinates, or
* ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED.
* \param y The y coordinate of the window in screen coordinates, or
* ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED.
*
* \note The window coordinate origin is the upper left of the display.
*
* \sa SDL_GetWindowPosition()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowPosition(SDL_Window * window,
int x, int y);
/**
* \brief Get the position of a window.
*
* \param window The window to query.
* \param x Pointer to variable for storing the x position, in screen
* coordinates. May be NULL.
* \param y Pointer to variable for storing the y position, in screen
* coordinates. May be NULL.
*
* \sa SDL_SetWindowPosition()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_Window * window,
int *x, int *y);
/**
* \brief Set the size of a window's client area.
*
* \param window The window to resize.
* \param w The width of the window, in screen coordinates. Must be >0.
* \param h The height of the window, in screen coordinates. Must be >0.
*
* \note Fullscreen windows automatically match the size of the display mode,
* and you should use SDL_SetWindowDisplayMode() to change their size.
*
* The window size in screen coordinates may differ from the size in pixels, if
* the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with
* high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or
* SDL_GetRendererOutputSize() to get the real client area size in pixels.
*
* \sa SDL_GetWindowSize()
* \sa SDL_SetWindowDisplayMode()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowSize(SDL_Window * window, int w,
int h);
/**
* \brief Get the size of a window's client area.
*
* \param window The window to query.
* \param w Pointer to variable for storing the width, in screen
* coordinates. May be NULL.
* \param h Pointer to variable for storing the height, in screen
* coordinates. May be NULL.
*
* The window size in screen coordinates may differ from the size in pixels, if
* the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with
* high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or
* SDL_GetRendererOutputSize() to get the real client area size in pixels.
*
* \sa SDL_SetWindowSize()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowSize(SDL_Window * window, int *w,
int *h);
/**
* \brief Get the size of a window's borders (decorations) around the client area.
*
* \param window The window to query.
* \param top Pointer to variable for storing the size of the top border. NULL is permitted.
* \param left Pointer to variable for storing the size of the left border. NULL is permitted.
* \param bottom Pointer to variable for storing the size of the bottom border. NULL is permitted.
* \param right Pointer to variable for storing the size of the right border. NULL is permitted.
*
* \return 0 on success, or -1 if getting this information is not supported.
*
* \note if this function fails (returns -1), the size values will be
* initialized to 0, 0, 0, 0 (if a non-NULL pointer is provided), as
* if the window in question was borderless.
*/
extern DECLSPEC int SDLCALL SDL_GetWindowBordersSize(SDL_Window * window,
int *top, int *left,
int *bottom, int *right);
/**
* \brief Set the minimum size of a window's client area.
*
* \param window The window to set a new minimum size.
* \param min_w The minimum width of the window, must be >0
* \param min_h The minimum height of the window, must be >0
*
* \note You can't change the minimum size of a fullscreen window, it
* automatically matches the size of the display mode.
*
* \sa SDL_GetWindowMinimumSize()
* \sa SDL_SetWindowMaximumSize()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowMinimumSize(SDL_Window * window,
int min_w, int min_h);
/**
* \brief Get the minimum size of a window's client area.
*
* \param window The window to query.
* \param w Pointer to variable for storing the minimum width, may be NULL
* \param h Pointer to variable for storing the minimum height, may be NULL
*
* \sa SDL_GetWindowMaximumSize()
* \sa SDL_SetWindowMinimumSize()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowMinimumSize(SDL_Window * window,
int *w, int *h);
/**
* \brief Set the maximum size of a window's client area.
*
* \param window The window to set a new maximum size.
* \param max_w The maximum width of the window, must be >0
* \param max_h The maximum height of the window, must be >0
*
* \note You can't change the maximum size of a fullscreen window, it
* automatically matches the size of the display mode.
*
* \sa SDL_GetWindowMaximumSize()
* \sa SDL_SetWindowMinimumSize()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowMaximumSize(SDL_Window * window,
int max_w, int max_h);
/**
* \brief Get the maximum size of a window's client area.
*
* \param window The window to query.
* \param w Pointer to variable for storing the maximum width, may be NULL
* \param h Pointer to variable for storing the maximum height, may be NULL
*
* \sa SDL_GetWindowMinimumSize()
* \sa SDL_SetWindowMaximumSize()
*/
extern DECLSPEC void SDLCALL SDL_GetWindowMaximumSize(SDL_Window * window,
int *w, int *h);
/**
* \brief Set the border state of a window.
*
* This will add or remove the window's SDL_WINDOW_BORDERLESS flag and
* add or remove the border from the actual window. This is a no-op if the
* window's border already matches the requested state.
*
* \param window The window of which to change the border state.
* \param bordered SDL_FALSE to remove border, SDL_TRUE to add border.
*
* \note You can't change the border state of a fullscreen window.
*
* \sa SDL_GetWindowFlags()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowBordered(SDL_Window * window,
SDL_bool bordered);
/**
* \brief Set the user-resizable state of a window.
*
* This will add or remove the window's SDL_WINDOW_RESIZABLE flag and
* allow/disallow user resizing of the window. This is a no-op if the
* window's resizable state already matches the requested state.
*
* \param window The window of which to change the resizable state.
* \param resizable SDL_TRUE to allow resizing, SDL_FALSE to disallow.
*
* \note You can't change the resizable state of a fullscreen window.
*
* \sa SDL_GetWindowFlags()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowResizable(SDL_Window * window,
SDL_bool resizable);
/**
* \brief Show a window.
*
* \sa SDL_HideWindow()
*/
extern DECLSPEC void SDLCALL SDL_ShowWindow(SDL_Window * window);
/**
* \brief Hide a window.
*
* \sa SDL_ShowWindow()
*/
extern DECLSPEC void SDLCALL SDL_HideWindow(SDL_Window * window);
/**
* \brief Raise a window above other windows and set the input focus.
*/
extern DECLSPEC void SDLCALL SDL_RaiseWindow(SDL_Window * window);
/**
* \brief Make a window as large as possible.
*
* \sa SDL_RestoreWindow()
*/
extern DECLSPEC void SDLCALL SDL_MaximizeWindow(SDL_Window * window);
/**
* \brief Minimize a window to an iconic representation.
*
* \sa SDL_RestoreWindow()
*/
extern DECLSPEC void SDLCALL SDL_MinimizeWindow(SDL_Window * window);
/**
* \brief Restore the size and position of a minimized or maximized window.
*
* \sa SDL_MaximizeWindow()
* \sa SDL_MinimizeWindow()
*/
extern DECLSPEC void SDLCALL SDL_RestoreWindow(SDL_Window * window);
/**
* \brief Set a window's fullscreen state.
*
* \return 0 on success, or -1 if setting the display mode failed.
*
* \sa SDL_SetWindowDisplayMode()
* \sa SDL_GetWindowDisplayMode()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowFullscreen(SDL_Window * window,
Uint32 flags);
/**
* \brief Get the SDL surface associated with the window.
*
* \return The window's framebuffer surface, or NULL on error.
*
* A new surface will be created with the optimal format for the window,
* if necessary. This surface will be freed when the window is destroyed.
*
* \note You may not combine this with 3D or the rendering API on this window.
*
* \sa SDL_UpdateWindowSurface()
* \sa SDL_UpdateWindowSurfaceRects()
*/
extern DECLSPEC SDL_Surface * SDLCALL SDL_GetWindowSurface(SDL_Window * window);
/**
* \brief Copy the window surface to the screen.
*
* \return 0 on success, or -1 on error.
*
* \sa SDL_GetWindowSurface()
* \sa SDL_UpdateWindowSurfaceRects()
*/
extern DECLSPEC int SDLCALL SDL_UpdateWindowSurface(SDL_Window * window);
/**
* \brief Copy a number of rectangles on the window surface to the screen.
*
* \return 0 on success, or -1 on error.
*
* \sa SDL_GetWindowSurface()
* \sa SDL_UpdateWindowSurface()
*/
extern DECLSPEC int SDLCALL SDL_UpdateWindowSurfaceRects(SDL_Window * window,
const SDL_Rect * rects,
int numrects);
/**
* \brief Set a window's input grab mode.
*
* \param window The window for which the input grab mode should be set.
* \param grabbed This is SDL_TRUE to grab input, and SDL_FALSE to release input.
*
* If the caller enables a grab while another window is currently grabbed,
* the other window loses its grab in favor of the caller's window.
*
* \sa SDL_GetWindowGrab()
*/
extern DECLSPEC void SDLCALL SDL_SetWindowGrab(SDL_Window * window,
SDL_bool grabbed);
/**
* \brief Get a window's input grab mode.
*
* \return This returns SDL_TRUE if input is grabbed, and SDL_FALSE otherwise.
*
* \sa SDL_SetWindowGrab()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowGrab(SDL_Window * window);
/**
* \brief Get the window that currently has an input grab enabled.
*
* \return This returns the window if input is grabbed, and NULL otherwise.
*
* \sa SDL_SetWindowGrab()
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetGrabbedWindow(void);
/**
* \brief Set the brightness (gamma correction) for a window.
*
* \return 0 on success, or -1 if setting the brightness isn't supported.
*
* \sa SDL_GetWindowBrightness()
* \sa SDL_SetWindowGammaRamp()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowBrightness(SDL_Window * window, float brightness);
/**
* \brief Get the brightness (gamma correction) for a window.
*
* \return The last brightness value passed to SDL_SetWindowBrightness()
*
* \sa SDL_SetWindowBrightness()
*/
extern DECLSPEC float SDLCALL SDL_GetWindowBrightness(SDL_Window * window);
/**
* \brief Set the opacity for a window
*
* \param window The window which will be made transparent or opaque
* \param opacity Opacity (0.0f - transparent, 1.0f - opaque) This will be
* clamped internally between 0.0f and 1.0f.
*
* \return 0 on success, or -1 if setting the opacity isn't supported.
*
* \sa SDL_GetWindowOpacity()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowOpacity(SDL_Window * window, float opacity);
/**
* \brief Get the opacity of a window.
*
* If transparency isn't supported on this platform, opacity will be reported
* as 1.0f without error.
*
* \param window The window in question.
* \param out_opacity Opacity (0.0f - transparent, 1.0f - opaque)
*
* \return 0 on success, or -1 on error (invalid window, etc).
*
* \sa SDL_SetWindowOpacity()
*/
extern DECLSPEC int SDLCALL SDL_GetWindowOpacity(SDL_Window * window, float * out_opacity);
/**
* \brief Sets the window as a modal for another window (TODO: reconsider this function and/or its name)
*
* \param modal_window The window that should be modal
* \param parent_window The parent window
*
* \return 0 on success, or -1 otherwise.
*/
extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window * modal_window, SDL_Window * parent_window);
/**
* \brief Explicitly sets input focus to the window.
*
* You almost certainly want SDL_RaiseWindow() instead of this function. Use
* this with caution, as you might give focus to a window that's completely
* obscured by other windows.
*
* \param window The window that should get the input focus
*
* \return 0 on success, or -1 otherwise.
* \sa SDL_RaiseWindow()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowInputFocus(SDL_Window * window);
/**
* \brief Set the gamma ramp for a window.
*
* \param window The window for which the gamma ramp should be set.
* \param red The translation table for the red channel, or NULL.
* \param green The translation table for the green channel, or NULL.
* \param blue The translation table for the blue channel, or NULL.
*
* \return 0 on success, or -1 if gamma ramps are unsupported.
*
* Set the gamma translation table for the red, green, and blue channels
* of the video hardware. Each table is an array of 256 16-bit quantities,
* representing a mapping between the input and output for that channel.
* The input is the index into the array, and the output is the 16-bit
* gamma value at that index, scaled to the output color precision.
*
* \sa SDL_GetWindowGammaRamp()
*/
extern DECLSPEC int SDLCALL SDL_SetWindowGammaRamp(SDL_Window * window,
const Uint16 * red,
const Uint16 * green,
const Uint16 * blue);
/**
* \brief Get the gamma ramp for a window.
*
* \param window The window from which the gamma ramp should be queried.
* \param red A pointer to a 256 element array of 16-bit quantities to hold
* the translation table for the red channel, or NULL.
* \param green A pointer to a 256 element array of 16-bit quantities to hold
* the translation table for the green channel, or NULL.
* \param blue A pointer to a 256 element array of 16-bit quantities to hold
* the translation table for the blue channel, or NULL.
*
* \return 0 on success, or -1 if gamma ramps are unsupported.
*
* \sa SDL_SetWindowGammaRamp()
*/
extern DECLSPEC int SDLCALL SDL_GetWindowGammaRamp(SDL_Window * window,
Uint16 * red,
Uint16 * green,
Uint16 * blue);
/**
* \brief Possible return values from the SDL_HitTest callback.
*
* \sa SDL_HitTest
*/
typedef enum
{
SDL_HITTEST_NORMAL, /**< Region is normal. No special properties. */
SDL_HITTEST_DRAGGABLE, /**< Region can drag entire window. */
SDL_HITTEST_RESIZE_TOPLEFT,
SDL_HITTEST_RESIZE_TOP,
SDL_HITTEST_RESIZE_TOPRIGHT,
SDL_HITTEST_RESIZE_RIGHT,
SDL_HITTEST_RESIZE_BOTTOMRIGHT,
SDL_HITTEST_RESIZE_BOTTOM,
SDL_HITTEST_RESIZE_BOTTOMLEFT,
SDL_HITTEST_RESIZE_LEFT
} SDL_HitTestResult;
/**
* \brief Callback used for hit-testing.
*
* \sa SDL_SetWindowHitTest
*/
typedef SDL_HitTestResult (SDLCALL *SDL_HitTest)(SDL_Window *win,
const SDL_Point *area,
void *data);
/**
* \brief Provide a callback that decides if a window region has special properties.
*
* Normally windows are dragged and resized by decorations provided by the
* system window manager (a title bar, borders, etc), but for some apps, it
* makes sense to drag them from somewhere else inside the window itself; for
* example, one might have a borderless window that wants to be draggable
* from any part, or simulate its own title bar, etc.
*
* This function lets the app provide a callback that designates pieces of
* a given window as special. This callback is run during event processing
* if we need to tell the OS to treat a region of the window specially; the
* use of this callback is known as "hit testing."
*
* Mouse input may not be delivered to your application if it is within
* a special area; the OS will often apply that input to moving the window or
* resizing the window and not deliver it to the application.
*
* Specifying NULL for a callback disables hit-testing. Hit-testing is
* disabled by default.
*
* Platforms that don't support this functionality will return -1
* unconditionally, even if you're attempting to disable hit-testing.
*
* Your callback may fire at any time, and its firing does not indicate any
* specific behavior (for example, on Windows, this certainly might fire
* when the OS is deciding whether to drag your window, but it fires for lots
* of other reasons, too, some unrelated to anything you probably care about
* _and when the mouse isn't actually at the location it is testing_).
* Since this can fire at any time, you should try to keep your callback
* efficient, devoid of allocations, etc.
*
* \param window The window to set hit-testing on.
* \param callback The callback to call when doing a hit-test.
* \param callback_data An app-defined void pointer passed to the callback.
* \return 0 on success, -1 on error (including unsupported).
*/
extern DECLSPEC int SDLCALL SDL_SetWindowHitTest(SDL_Window * window,
SDL_HitTest callback,
void *callback_data);
/**
* \brief Destroy a window.
*/
extern DECLSPEC void SDLCALL SDL_DestroyWindow(SDL_Window * window);
/**
* \brief Returns whether the screensaver is currently enabled (default off).
*
* \sa SDL_EnableScreenSaver()
* \sa SDL_DisableScreenSaver()
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenSaverEnabled(void);
/**
* \brief Allow the screen to be blanked by a screensaver
*
* \sa SDL_IsScreenSaverEnabled()
* \sa SDL_DisableScreenSaver()
*/
extern DECLSPEC void SDLCALL SDL_EnableScreenSaver(void);
/**
* \brief Prevent the screen from being blanked by a screensaver
*
* \sa SDL_IsScreenSaverEnabled()
* \sa SDL_EnableScreenSaver()
*/
extern DECLSPEC void SDLCALL SDL_DisableScreenSaver(void);
/**
* \name OpenGL support functions
*/
/* @{ */
/**
* \brief Dynamically load an OpenGL library.
*
* \param path The platform dependent OpenGL library name, or NULL to open the
* default OpenGL library.
*
* \return 0 on success, or -1 if the library couldn't be loaded.
*
* This should be done after initializing the video driver, but before
* creating any OpenGL windows. If no OpenGL library is loaded, the default
* library will be loaded upon creation of the first OpenGL window.
*
* \note If you do this, you need to retrieve all of the GL functions used in
* your program from the dynamic library using SDL_GL_GetProcAddress().
*
* \sa SDL_GL_GetProcAddress()
* \sa SDL_GL_UnloadLibrary()
*/
extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path);
/**
* \brief Get the address of an OpenGL function.
*/
extern DECLSPEC void *SDLCALL SDL_GL_GetProcAddress(const char *proc);
/**
* \brief Unload the OpenGL library previously loaded by SDL_GL_LoadLibrary().
*
* \sa SDL_GL_LoadLibrary()
*/
extern DECLSPEC void SDLCALL SDL_GL_UnloadLibrary(void);
/**
* \brief Return true if an OpenGL extension is supported for the current
* context.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GL_ExtensionSupported(const char
*extension);
/**
* \brief Reset all previously set OpenGL context attributes to their default values
*/
extern DECLSPEC void SDLCALL SDL_GL_ResetAttributes(void);
/**
* \brief Set an OpenGL window attribute before window creation.
*
* \return 0 on success, or -1 if the attribute could not be set.
*/
extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value);
/**
* \brief Get the actual value for an attribute from the current context.
*
* \return 0 on success, or -1 if the attribute could not be retrieved.
* The integer at \c value will be modified in either case.
*/
extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int *value);
/**
* \brief Create an OpenGL context for use with an OpenGL window, and make it
* current.
*
* \sa SDL_GL_DeleteContext()
*/
extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_CreateContext(SDL_Window *
window);
/**
* \brief Set up an OpenGL context for rendering into an OpenGL window.
*
* \note The context must have been created with a compatible window.
*/
extern DECLSPEC int SDLCALL SDL_GL_MakeCurrent(SDL_Window * window,
SDL_GLContext context);
/**
* \brief Get the currently active OpenGL window.
*/
extern DECLSPEC SDL_Window* SDLCALL SDL_GL_GetCurrentWindow(void);
/**
* \brief Get the currently active OpenGL context.
*/
extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_GetCurrentContext(void);
/**
* \brief Get the size of a window's underlying drawable in pixels (for use
* with glViewport).
*
* \param window Window from which the drawable size should be queried
* \param w Pointer to variable for storing the width in pixels, may be NULL
* \param h Pointer to variable for storing the height in pixels, may be NULL
*
* This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI
* drawable, i.e. the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a
* platform with high-DPI support (Apple calls this "Retina"), and not disabled
* by the SDL_HINT_VIDEO_HIGHDPI_DISABLED hint.
*
* \sa SDL_GetWindowSize()
* \sa SDL_CreateWindow()
*/
extern DECLSPEC void SDLCALL SDL_GL_GetDrawableSize(SDL_Window * window, int *w,
int *h);
/**
* \brief Set the swap interval for the current OpenGL context.
*
* \param interval 0 for immediate updates, 1 for updates synchronized with the
* vertical retrace. If the system supports it, you may
* specify -1 to allow late swaps to happen immediately
* instead of waiting for the next retrace.
*
* \return 0 on success, or -1 if setting the swap interval is not supported.
*
* \sa SDL_GL_GetSwapInterval()
*/
extern DECLSPEC int SDLCALL SDL_GL_SetSwapInterval(int interval);
/**
* \brief Get the swap interval for the current OpenGL context.
*
* \return 0 if there is no vertical retrace synchronization, 1 if the buffer
* swap is synchronized with the vertical retrace, and -1 if late
* swaps happen immediately instead of waiting for the next retrace.
* If the system can't determine the swap interval, or there isn't a
* valid current context, this will return 0 as a safe default.
*
* \sa SDL_GL_SetSwapInterval()
*/
extern DECLSPEC int SDLCALL SDL_GL_GetSwapInterval(void);
/**
* \brief Swap the OpenGL buffers for a window, if double-buffering is
* supported.
*/
extern DECLSPEC void SDLCALL SDL_GL_SwapWindow(SDL_Window * window);
/**
* \brief Delete an OpenGL context.
*
* \sa SDL_GL_CreateContext()
*/
extern DECLSPEC void SDLCALL SDL_GL_DeleteContext(SDL_GLContext context);
/* @} *//* OpenGL support functions */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_video_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
require 'helper'
class TestRegressionSetColumn07 < Test::Unit::TestCase
def setup
setup_dir_var
end
def teardown
@tempfile.close(true)
end
def test_set_column07
@xlsx = 'set_column07.xlsx'
workbook = WriteXLSX.new(@io)
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
italic = workbook.add_format(:italic => 1)
bold_italic = workbook.add_format(:bold => 1, :italic => 1)
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15]
]
worksheet.write('A1', 'Foo', italic)
worksheet.write('B1', 'Bar', bold)
worksheet.write('A2', data)
worksheet.set_row(12, nil, italic)
worksheet.set_column('F:F', nil, bold)
worksheet.write('F13', nil, bold_italic)
worksheet.insert_image('E12',
File.join(@test_dir, 'regression', 'images/logo.png'))
workbook.close
compare_for_regression
end
end
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.devicefarm.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* A container for account-level settings in AWS Device Farm.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/AccountSettings" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AccountSettings implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The AWS account number specified in the <code>AccountSettings</code> container.
* </p>
*/
private String awsAccountNumber;
/**
* <p>
* Returns the unmetered devices you have purchased or want to purchase.
* </p>
*/
private java.util.Map<String, Integer> unmeteredDevices;
/**
* <p>
* Returns the unmetered remote access devices you have purchased or want to purchase.
* </p>
*/
private java.util.Map<String, Integer> unmeteredRemoteAccessDevices;
/**
* <p>
* The maximum number of minutes a test run executes before it times out.
* </p>
*/
private Integer maxJobTimeoutMinutes;
/**
* <p>
* Information about an AWS account's usage of free trial device minutes.
* </p>
*/
private TrialMinutes trialMinutes;
/**
* <p>
* The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
* <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by
* the <code>ListOfferings</code> command.
* </p>
*/
private java.util.Map<String, Integer> maxSlots;
/**
* <p>
* The default number of minutes (at the account level) a test run executes before it times out. The default value
* is 150 minutes.
* </p>
*/
private Integer defaultJobTimeoutMinutes;
/**
* <p>
* When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public devices,
* Device Farm always signs your apps again.
* </p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm FAQs</i>.
* </p>
*/
private Boolean skipAppResign;
/**
* <p>
* The AWS account number specified in the <code>AccountSettings</code> container.
* </p>
*
* @param awsAccountNumber
* The AWS account number specified in the <code>AccountSettings</code> container.
*/
public void setAwsAccountNumber(String awsAccountNumber) {
this.awsAccountNumber = awsAccountNumber;
}
/**
* <p>
* The AWS account number specified in the <code>AccountSettings</code> container.
* </p>
*
* @return The AWS account number specified in the <code>AccountSettings</code> container.
*/
public String getAwsAccountNumber() {
return this.awsAccountNumber;
}
/**
* <p>
* The AWS account number specified in the <code>AccountSettings</code> container.
* </p>
*
* @param awsAccountNumber
* The AWS account number specified in the <code>AccountSettings</code> container.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withAwsAccountNumber(String awsAccountNumber) {
setAwsAccountNumber(awsAccountNumber);
return this;
}
/**
* <p>
* Returns the unmetered devices you have purchased or want to purchase.
* </p>
*
* @return Returns the unmetered devices you have purchased or want to purchase.
*/
public java.util.Map<String, Integer> getUnmeteredDevices() {
return unmeteredDevices;
}
/**
* <p>
* Returns the unmetered devices you have purchased or want to purchase.
* </p>
*
* @param unmeteredDevices
* Returns the unmetered devices you have purchased or want to purchase.
*/
public void setUnmeteredDevices(java.util.Map<String, Integer> unmeteredDevices) {
this.unmeteredDevices = unmeteredDevices;
}
/**
* <p>
* Returns the unmetered devices you have purchased or want to purchase.
* </p>
*
* @param unmeteredDevices
* Returns the unmetered devices you have purchased or want to purchase.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withUnmeteredDevices(java.util.Map<String, Integer> unmeteredDevices) {
setUnmeteredDevices(unmeteredDevices);
return this;
}
/**
* Add a single UnmeteredDevices entry
*
* @see AccountSettings#withUnmeteredDevices
* @returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings addUnmeteredDevicesEntry(String key, Integer value) {
if (null == this.unmeteredDevices) {
this.unmeteredDevices = new java.util.HashMap<String, Integer>();
}
if (this.unmeteredDevices.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.unmeteredDevices.put(key, value);
return this;
}
/**
* Removes all the entries added into UnmeteredDevices.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings clearUnmeteredDevicesEntries() {
this.unmeteredDevices = null;
return this;
}
/**
* <p>
* Returns the unmetered remote access devices you have purchased or want to purchase.
* </p>
*
* @return Returns the unmetered remote access devices you have purchased or want to purchase.
*/
public java.util.Map<String, Integer> getUnmeteredRemoteAccessDevices() {
return unmeteredRemoteAccessDevices;
}
/**
* <p>
* Returns the unmetered remote access devices you have purchased or want to purchase.
* </p>
*
* @param unmeteredRemoteAccessDevices
* Returns the unmetered remote access devices you have purchased or want to purchase.
*/
public void setUnmeteredRemoteAccessDevices(java.util.Map<String, Integer> unmeteredRemoteAccessDevices) {
this.unmeteredRemoteAccessDevices = unmeteredRemoteAccessDevices;
}
/**
* <p>
* Returns the unmetered remote access devices you have purchased or want to purchase.
* </p>
*
* @param unmeteredRemoteAccessDevices
* Returns the unmetered remote access devices you have purchased or want to purchase.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withUnmeteredRemoteAccessDevices(java.util.Map<String, Integer> unmeteredRemoteAccessDevices) {
setUnmeteredRemoteAccessDevices(unmeteredRemoteAccessDevices);
return this;
}
/**
* Add a single UnmeteredRemoteAccessDevices entry
*
* @see AccountSettings#withUnmeteredRemoteAccessDevices
* @returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings addUnmeteredRemoteAccessDevicesEntry(String key, Integer value) {
if (null == this.unmeteredRemoteAccessDevices) {
this.unmeteredRemoteAccessDevices = new java.util.HashMap<String, Integer>();
}
if (this.unmeteredRemoteAccessDevices.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.unmeteredRemoteAccessDevices.put(key, value);
return this;
}
/**
* Removes all the entries added into UnmeteredRemoteAccessDevices.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings clearUnmeteredRemoteAccessDevicesEntries() {
this.unmeteredRemoteAccessDevices = null;
return this;
}
/**
* <p>
* The maximum number of minutes a test run executes before it times out.
* </p>
*
* @param maxJobTimeoutMinutes
* The maximum number of minutes a test run executes before it times out.
*/
public void setMaxJobTimeoutMinutes(Integer maxJobTimeoutMinutes) {
this.maxJobTimeoutMinutes = maxJobTimeoutMinutes;
}
/**
* <p>
* The maximum number of minutes a test run executes before it times out.
* </p>
*
* @return The maximum number of minutes a test run executes before it times out.
*/
public Integer getMaxJobTimeoutMinutes() {
return this.maxJobTimeoutMinutes;
}
/**
* <p>
* The maximum number of minutes a test run executes before it times out.
* </p>
*
* @param maxJobTimeoutMinutes
* The maximum number of minutes a test run executes before it times out.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withMaxJobTimeoutMinutes(Integer maxJobTimeoutMinutes) {
setMaxJobTimeoutMinutes(maxJobTimeoutMinutes);
return this;
}
/**
* <p>
* Information about an AWS account's usage of free trial device minutes.
* </p>
*
* @param trialMinutes
* Information about an AWS account's usage of free trial device minutes.
*/
public void setTrialMinutes(TrialMinutes trialMinutes) {
this.trialMinutes = trialMinutes;
}
/**
* <p>
* Information about an AWS account's usage of free trial device minutes.
* </p>
*
* @return Information about an AWS account's usage of free trial device minutes.
*/
public TrialMinutes getTrialMinutes() {
return this.trialMinutes;
}
/**
* <p>
* Information about an AWS account's usage of free trial device minutes.
* </p>
*
* @param trialMinutes
* Information about an AWS account's usage of free trial device minutes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withTrialMinutes(TrialMinutes trialMinutes) {
setTrialMinutes(trialMinutes);
return this;
}
/**
* <p>
* The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
* <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by
* the <code>ListOfferings</code> command.
* </p>
*
* @return The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
* <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs
* returned by the <code>ListOfferings</code> command.
*/
public java.util.Map<String, Integer> getMaxSlots() {
return maxSlots;
}
/**
* <p>
* The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
* <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by
* the <code>ListOfferings</code> command.
* </p>
*
* @param maxSlots
* The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
* <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs
* returned by the <code>ListOfferings</code> command.
*/
public void setMaxSlots(java.util.Map<String, Integer> maxSlots) {
this.maxSlots = maxSlots;
}
/**
* <p>
* The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
* <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by
* the <code>ListOfferings</code> command.
* </p>
*
* @param maxSlots
* The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
* <code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs
* returned by the <code>ListOfferings</code> command.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withMaxSlots(java.util.Map<String, Integer> maxSlots) {
setMaxSlots(maxSlots);
return this;
}
/**
* Add a single MaxSlots entry
*
* @see AccountSettings#withMaxSlots
* @returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings addMaxSlotsEntry(String key, Integer value) {
if (null == this.maxSlots) {
this.maxSlots = new java.util.HashMap<String, Integer>();
}
if (this.maxSlots.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.maxSlots.put(key, value);
return this;
}
/**
* Removes all the entries added into MaxSlots.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings clearMaxSlotsEntries() {
this.maxSlots = null;
return this;
}
/**
* <p>
* The default number of minutes (at the account level) a test run executes before it times out. The default value
* is 150 minutes.
* </p>
*
* @param defaultJobTimeoutMinutes
* The default number of minutes (at the account level) a test run executes before it times out. The default
* value is 150 minutes.
*/
public void setDefaultJobTimeoutMinutes(Integer defaultJobTimeoutMinutes) {
this.defaultJobTimeoutMinutes = defaultJobTimeoutMinutes;
}
/**
* <p>
* The default number of minutes (at the account level) a test run executes before it times out. The default value
* is 150 minutes.
* </p>
*
* @return The default number of minutes (at the account level) a test run executes before it times out. The default
* value is 150 minutes.
*/
public Integer getDefaultJobTimeoutMinutes() {
return this.defaultJobTimeoutMinutes;
}
/**
* <p>
* The default number of minutes (at the account level) a test run executes before it times out. The default value
* is 150 minutes.
* </p>
*
* @param defaultJobTimeoutMinutes
* The default number of minutes (at the account level) a test run executes before it times out. The default
* value is 150 minutes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withDefaultJobTimeoutMinutes(Integer defaultJobTimeoutMinutes) {
setDefaultJobTimeoutMinutes(defaultJobTimeoutMinutes);
return this;
}
/**
* <p>
* When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public devices,
* Device Farm always signs your apps again.
* </p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm FAQs</i>.
* </p>
*
* @param skipAppResign
* When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public
* devices, Device Farm always signs your apps again.</p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm
* FAQs</i>.
*/
public void setSkipAppResign(Boolean skipAppResign) {
this.skipAppResign = skipAppResign;
}
/**
* <p>
* When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public devices,
* Device Farm always signs your apps again.
* </p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm FAQs</i>.
* </p>
*
* @return When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public
* devices, Device Farm always signs your apps again.</p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm
* FAQs</i>.
*/
public Boolean getSkipAppResign() {
return this.skipAppResign;
}
/**
* <p>
* When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public devices,
* Device Farm always signs your apps again.
* </p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm FAQs</i>.
* </p>
*
* @param skipAppResign
* When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public
* devices, Device Farm always signs your apps again.</p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm
* FAQs</i>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AccountSettings withSkipAppResign(Boolean skipAppResign) {
setSkipAppResign(skipAppResign);
return this;
}
/**
* <p>
* When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public devices,
* Device Farm always signs your apps again.
* </p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm FAQs</i>.
* </p>
*
* @return When set to <code>true</code>, for private devices, Device Farm does not sign your app again. For public
* devices, Device Farm always signs your apps again.</p>
* <p>
* For more information about how Device Farm re-signs your apps, see <a
* href="https://aws.amazon.com/device-farm/faq/">Do you modify my app?</a> in the <i>AWS Device Farm
* FAQs</i>.
*/
public Boolean isSkipAppResign() {
return this.skipAppResign;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAwsAccountNumber() != null)
sb.append("AwsAccountNumber: ").append(getAwsAccountNumber()).append(",");
if (getUnmeteredDevices() != null)
sb.append("UnmeteredDevices: ").append(getUnmeteredDevices()).append(",");
if (getUnmeteredRemoteAccessDevices() != null)
sb.append("UnmeteredRemoteAccessDevices: ").append(getUnmeteredRemoteAccessDevices()).append(",");
if (getMaxJobTimeoutMinutes() != null)
sb.append("MaxJobTimeoutMinutes: ").append(getMaxJobTimeoutMinutes()).append(",");
if (getTrialMinutes() != null)
sb.append("TrialMinutes: ").append(getTrialMinutes()).append(",");
if (getMaxSlots() != null)
sb.append("MaxSlots: ").append(getMaxSlots()).append(",");
if (getDefaultJobTimeoutMinutes() != null)
sb.append("DefaultJobTimeoutMinutes: ").append(getDefaultJobTimeoutMinutes()).append(",");
if (getSkipAppResign() != null)
sb.append("SkipAppResign: ").append(getSkipAppResign());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AccountSettings == false)
return false;
AccountSettings other = (AccountSettings) obj;
if (other.getAwsAccountNumber() == null ^ this.getAwsAccountNumber() == null)
return false;
if (other.getAwsAccountNumber() != null && other.getAwsAccountNumber().equals(this.getAwsAccountNumber()) == false)
return false;
if (other.getUnmeteredDevices() == null ^ this.getUnmeteredDevices() == null)
return false;
if (other.getUnmeteredDevices() != null && other.getUnmeteredDevices().equals(this.getUnmeteredDevices()) == false)
return false;
if (other.getUnmeteredRemoteAccessDevices() == null ^ this.getUnmeteredRemoteAccessDevices() == null)
return false;
if (other.getUnmeteredRemoteAccessDevices() != null && other.getUnmeteredRemoteAccessDevices().equals(this.getUnmeteredRemoteAccessDevices()) == false)
return false;
if (other.getMaxJobTimeoutMinutes() == null ^ this.getMaxJobTimeoutMinutes() == null)
return false;
if (other.getMaxJobTimeoutMinutes() != null && other.getMaxJobTimeoutMinutes().equals(this.getMaxJobTimeoutMinutes()) == false)
return false;
if (other.getTrialMinutes() == null ^ this.getTrialMinutes() == null)
return false;
if (other.getTrialMinutes() != null && other.getTrialMinutes().equals(this.getTrialMinutes()) == false)
return false;
if (other.getMaxSlots() == null ^ this.getMaxSlots() == null)
return false;
if (other.getMaxSlots() != null && other.getMaxSlots().equals(this.getMaxSlots()) == false)
return false;
if (other.getDefaultJobTimeoutMinutes() == null ^ this.getDefaultJobTimeoutMinutes() == null)
return false;
if (other.getDefaultJobTimeoutMinutes() != null && other.getDefaultJobTimeoutMinutes().equals(this.getDefaultJobTimeoutMinutes()) == false)
return false;
if (other.getSkipAppResign() == null ^ this.getSkipAppResign() == null)
return false;
if (other.getSkipAppResign() != null && other.getSkipAppResign().equals(this.getSkipAppResign()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAwsAccountNumber() == null) ? 0 : getAwsAccountNumber().hashCode());
hashCode = prime * hashCode + ((getUnmeteredDevices() == null) ? 0 : getUnmeteredDevices().hashCode());
hashCode = prime * hashCode + ((getUnmeteredRemoteAccessDevices() == null) ? 0 : getUnmeteredRemoteAccessDevices().hashCode());
hashCode = prime * hashCode + ((getMaxJobTimeoutMinutes() == null) ? 0 : getMaxJobTimeoutMinutes().hashCode());
hashCode = prime * hashCode + ((getTrialMinutes() == null) ? 0 : getTrialMinutes().hashCode());
hashCode = prime * hashCode + ((getMaxSlots() == null) ? 0 : getMaxSlots().hashCode());
hashCode = prime * hashCode + ((getDefaultJobTimeoutMinutes() == null) ? 0 : getDefaultJobTimeoutMinutes().hashCode());
hashCode = prime * hashCode + ((getSkipAppResign() == null) ? 0 : getSkipAppResign().hashCode());
return hashCode;
}
@Override
public AccountSettings clone() {
try {
return (AccountSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.devicefarm.model.transform.AccountSettingsMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| {
"pile_set_name": "Github"
} |
from __future__ import print_function, division
from sympy.combinatorics.perm_groups import PermutationGroup
from sympy.combinatorics.group_constructs import DirectProduct
from sympy.combinatorics.permutations import Permutation
_af_new = Permutation._af_new
def AbelianGroup(*cyclic_orders):
"""
Returns the direct product of cyclic groups with the given orders.
According to the structure theorem for finite abelian groups ([1]),
every finite abelian group can be written as the direct product of finitely
many cyclic groups.
[1] http://groupprops.subwiki.org/wiki/Structure_theorem_for_finitely_generated_abelian_groups
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation.print_cyclic = True
>>> from sympy.combinatorics.named_groups import AbelianGroup
>>> AbelianGroup(3, 4)
PermutationGroup([
Permutation(6)(0, 1, 2),
Permutation(3, 4, 5, 6)])
>>> _.is_group()
False
See Also
========
DirectProduct
"""
groups = []
degree = 0
order = 1
for size in cyclic_orders:
degree += size
order *= size
groups.append(CyclicGroup(size))
G = DirectProduct(*groups)
G._is_abelian = True
G._degree = degree
G._order = order
return G
def AlternatingGroup(n):
"""
Generates the alternating group on ``n`` elements as a permutation group.
For ``n > 2``, the generators taken are ``(0 1 2), (0 1 2 ... n-1)`` for
``n`` odd
and ``(0 1 2), (1 2 ... n-1)`` for ``n`` even (See [1], p.31, ex.6.9.).
After the group is generated, some of its basic properties are set.
The cases ``n = 1, 2`` are handled separately.
Examples
========
>>> from sympy.combinatorics.named_groups import AlternatingGroup
>>> G = AlternatingGroup(4)
>>> G.is_group()
False
>>> a = list(G.generate_dimino())
>>> len(a)
12
>>> all(perm.is_even for perm in a)
True
See Also
========
SymmetricGroup, CyclicGroup, DihedralGroup
References
==========
[1] Armstrong, M. "Groups and Symmetry"
"""
# small cases are special
if n in (1, 2):
return PermutationGroup([Permutation([0])])
a = list(range(n))
a[0], a[1], a[2] = a[1], a[2], a[0]
gen1 = a
if n % 2:
a = list(range(1, n))
a.append(0)
gen2 = a
else:
a = list(range(2, n))
a.append(1)
a.insert(0, 0)
gen2 = a
gens = [gen1, gen2]
if gen1 == gen2:
gens = gens[:1]
G = PermutationGroup([_af_new(a) for a in gens], dups=False)
if n < 4:
G._is_abelian = True
G._is_nilpotent = True
else:
G._is_abelian = False
G._is_nilpotent = False
if n < 5:
G._is_solvable = True
else:
G._is_solvable = False
G._degree = n
G._is_transitive = True
G._is_alt = True
return G
def CyclicGroup(n):
"""
Generates the cyclic group of order ``n`` as a permutation group.
The generator taken is the ``n``-cycle ``(0 1 2 ... n-1)``
(in cycle notation). After the group is generated, some of its basic
properties are set.
Examples
========
>>> from sympy.combinatorics.named_groups import CyclicGroup
>>> G = CyclicGroup(6)
>>> G.is_group()
False
>>> G.order()
6
>>> list(G.generate_schreier_sims(af=True))
[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 0], [2, 3, 4, 5, 0, 1],
[3, 4, 5, 0, 1, 2], [4, 5, 0, 1, 2, 3], [5, 0, 1, 2, 3, 4]]
See Also
========
SymmetricGroup, DihedralGroup, AlternatingGroup
"""
a = list(range(1, n))
a.append(0)
gen = _af_new(a)
G = PermutationGroup([gen])
G._is_abelian = True
G._is_nilpotent = True
G._is_solvable = True
G._degree = n
G._is_transitive = True
G._order = n
return G
def DihedralGroup(n):
r"""
Generates the dihedral group `D_n` as a permutation group.
The dihedral group `D_n` is the group of symmetries of the regular
``n``-gon. The generators taken are the ``n``-cycle ``a = (0 1 2 ... n-1)``
(a rotation of the ``n``-gon) and ``b = (0 n-1)(1 n-2)...``
(a reflection of the ``n``-gon) in cycle rotation. It is easy to see that
these satisfy ``a**n = b**2 = 1`` and ``bab = ~a`` so they indeed generate
`D_n` (See [1]). After the group is generated, some of its basic properties
are set.
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> G = DihedralGroup(5)
>>> G.is_group()
False
>>> a = list(G.generate_dimino())
>>> [perm.cyclic_form for perm in a]
[[], [[0, 1, 2, 3, 4]], [[0, 2, 4, 1, 3]],
[[0, 3, 1, 4, 2]], [[0, 4, 3, 2, 1]], [[0, 4], [1, 3]],
[[1, 4], [2, 3]], [[0, 1], [2, 4]], [[0, 2], [3, 4]],
[[0, 3], [1, 2]]]
See Also
========
SymmetricGroup, CyclicGroup, AlternatingGroup
References
==========
[1] http://en.wikipedia.org/wiki/Dihedral_group
"""
# small cases are special
if n == 1:
return PermutationGroup([Permutation([1, 0])])
if n == 2:
return PermutationGroup([Permutation([1, 0, 3, 2]),
Permutation([2, 3, 0, 1]), Permutation([3, 2, 1, 0])])
a = list(range(1, n))
a.append(0)
gen1 = _af_new(a)
a = list(range(n))
a.reverse()
gen2 = _af_new(a)
G = PermutationGroup([gen1, gen2])
# if n is a power of 2, group is nilpotent
if n & (n-1) == 0:
G._is_nilpotent = True
else:
G._is_nilpotent = False
G._is_abelian = False
G._is_solvable = True
G._degree = n
G._is_transitive = True
G._order = 2*n
return G
def SymmetricGroup(n):
"""
Generates the symmetric group on ``n`` elements as a permutation group.
The generators taken are the ``n``-cycle
``(0 1 2 ... n-1)`` and the transposition ``(0 1)`` (in cycle notation).
(See [1]). After the group is generated, some of its basic properties
are set.
Examples
========
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> G = SymmetricGroup(4)
>>> G.is_group()
False
>>> G.order()
24
>>> list(G.generate_schreier_sims(af=True))
[[0, 1, 2, 3], [1, 2, 3, 0], [2, 3, 0, 1], [3, 1, 2, 0], [0, 2, 3, 1],
[1, 3, 0, 2], [2, 0, 1, 3], [3, 2, 0, 1], [0, 3, 1, 2], [1, 0, 2, 3],
[2, 1, 3, 0], [3, 0, 1, 2], [0, 1, 3, 2], [1, 2, 0, 3], [2, 3, 1, 0],
[3, 1, 0, 2], [0, 2, 1, 3], [1, 3, 2, 0], [2, 0, 3, 1], [3, 2, 1, 0],
[0, 3, 2, 1], [1, 0, 3, 2], [2, 1, 0, 3], [3, 0, 2, 1]]
See Also
========
CyclicGroup, DihedralGroup, AlternatingGroup
References
==========
[1] http://en.wikipedia.org/wiki/Symmetric_group#Generators_and_relations
"""
if n == 1:
G = PermutationGroup([Permutation([0])])
elif n == 2:
G = PermutationGroup([Permutation([1, 0])])
else:
a = list(range(1, n))
a.append(0)
gen1 = _af_new(a)
a = list(range(n))
a[0], a[1] = a[1], a[0]
gen2 = _af_new(a)
G = PermutationGroup([gen1, gen2])
if n < 3:
G._is_abelian = True
G._is_nilpotent = True
else:
G._is_abelian = False
G._is_nilpotent = False
if n < 5:
G._is_solvable = True
else:
G._is_solvable = False
G._degree = n
G._is_transitive = True
G._is_sym = True
return G
def RubikGroup(n):
"""Return a group of Rubik's cube generators.
>>> from sympy.combinatorics.named_groups import RubikGroup
>>> RubikGroup(2).is_group()
False
"""
from sympy.combinatorics.generators import rubik
assert n > 1
return PermutationGroup(rubik(n))
| {
"pile_set_name": "Github"
} |
/***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
* $Id$
*
* Copyright (C) 2006-2007 Adam Gashlin (hcs)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
/* a fun simple elapsed time profiler */
#ifndef _SPC_PROFILER_H_
#define _SPC_PROFILER_H_
#if defined(SPC_PROFILE) && defined(USEC_TIMER)
#ifdef SPC_DEFINE_PROFILER_TIMERS
#define CREATE_TIMER(name) uint32_t spc_timer_##name##_start,\
spc_timer_##name##_total
#else
#define CREATE_TIMER(name) extern uint32_t spc_timer_##name##_start,\
spc_timer_##name##_total
#endif
#define ENTER_TIMER(name) spc_timer_##name##_start=USEC_TIMER
#define EXIT_TIMER(name) spc_timer_##name##_total+=\
(USEC_TIMER-spc_timer_##name##_start)
#define READ_TIMER(name) (spc_timer_##name##_total)
#define RESET_TIMER(name) spc_timer_##name##_total=0
#define PRINT_TIMER_PCT(bname,tname,nstr) ci->fdprintf( \
logfd,"%10ld ",READ_TIMER(bname));\
ci->fdprintf(logfd,"(%3d%%) " nstr "\t",\
((uint64_t)READ_TIMER(bname))*100/READ_TIMER(tname))
CREATE_TIMER(total);
CREATE_TIMER(render);
#if 0
CREATE_TIMER(cpu);
CREATE_TIMER(dsp);
CREATE_TIMER(dsp_pregen);
CREATE_TIMER(dsp_gen);
CREATE_TIMER(dsp_mix);
#endif
void reset_profile_timers(void);
void print_timers(char * path);
#else
#define CREATE_TIMER(name)
#define ENTER_TIMER(name)
#define EXIT_TIMER(name)
#define READ_TIMER(name)
#define RESET_TIMER(name)
#define print_timers(path)
#define reset_profile_timers()
#endif
#endif /* _SPC_PROFILER_H_ */
| {
"pile_set_name": "Github"
} |
/**
* A wrapper around JSLint to drop things into the console
*
* Copyright (C) 2011 Nikolay Nemshilov
*/
var RightJS = require('./right-server.js');
var JSLint = require('./jslint').JSLINT;
var fs = require('fs');
exports.Linter = new RightJS.Class({
extend: {
Options: {
debug: false, // no debug
devel: false, // no console.log s
evil: false, // no evals
passfail: false, // don't stop on errors
onevar: false, // allow more than one 'var' definition
forin: true , // allow for in without ownershipt checks
indent: 2 , // enforce 2 spaces indent
maxerr: 12 , // max number of errors
},
Okays: [
"Move 'var' declarations to the top of the function."
]
},
/**
* Basic constructor
*
* @param {String} the source
* @param {String} the linter options
* @return void
*/
initialize: function(src, options) {
this.source = src;
this.options = options;
},
/**
* Runs the linter
*
* @return {Linter} this
*/
run: function() {
var options = {}, okays = [];
// extracting the additional options
eval(fs.readFileSync(this.options).toString());
JSLint.okays = this.constructor.Okays.concat(okays);
JSLint(
fs.readFileSync(this.source).toString(),
Object.merge(this.constructor.Options, options)
);
this.errors = JSLint.errors.compact();
return this;
},
/**
* Prints out the check report
*
* @return {Linter} this
*/
report: function() {
if (this.errors.empty()) {
console.log("\u001B[32m - JSLint check successfully passed\u001B[0m");
} else {
console.log("\u001B[31m - JSLint check failed in: "+ this.source + "\u001B[0m");
this.errors.each(function(error) {
var report = "\n", j=0, pointer='';
for (; j < error.character-1; j++) { pointer += '-'; }
report += " \u001B[35m"+ error.reason +"\u001B[0m ";
if (error.evidence) {
report += "Line: "+ error.line + ", Char: "+ error.character + "\n";
report += " "+ error.evidence + "\n";
report += " \u001B[33m"+ pointer + "^\u001B[0m";
}
console.log(report);
});
console.log("\n")
}
return this;
}
}); | {
"pile_set_name": "Github"
} |
/// Source : https://leetcode.com/problems/word-ladder/description/
/// Author : liuyubobobo
/// Time : 2017-11-21
/// Updated: 2018-03-27
#include <iostream>
#include <vector>
#include <cassert>
#include <queue>
#include <unordered_map>
using namespace std;
/// Bi-directional BFS
/// No need to calculate all pairs similarity
/// Time Complexity: O(n*n)
/// Space Complexity: O(n)
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
if(find(wordList.begin(), wordList.end(), endWord) == wordList.end())
return 0;
// bi-derectional bfs
unordered_map<string, int> step_s;
unordered_map<string, int> step_t;
queue<string> queue_s;
queue<string> queue_t;
queue_s.push(beginWord);
step_s[beginWord] = 1;
queue_t.push(endWord);
step_t[endWord] = 1;
while(!queue_s.empty() && !queue_t.empty()){
string sWord = queue_s.front();
queue_s.pop();
string tWord = queue_t.front();
queue_t.pop();
for(string word: wordList){
if(step_s.find(word) == step_s.end() && similar(word, sWord)){
step_s[word] = step_s[sWord] + 1;
queue_s.push(word);
}
if(step_t.find(word) == step_t.end() && similar(word, tWord)){
step_t[word] = step_t[tWord] + 1;
queue_t.push(word);
}
}
// check intersection
int res = INT_MAX;
for(string word: wordList)
if(step_s.find(word) != step_s.end() && step_t.find(word) != step_t.end())
res = min(res, step_s[word] + step_t[word] - 1);
if(res != INT_MAX)
return res;
}
return 0;
}
private:
bool similar(const string& word1, const string& word2){
assert(word1 != "" && word1.size() == word2.size() && word1 != word2);
int diff = 0;
for(int i = 0 ; i < word1.size() ; i ++)
if(word1[i] != word2[i]){
diff ++;
if(diff > 1)
return false;
}
return true;
}
};
int main() {
vector<string> vec1 = {"hot","dot","dog","lot","log","cog"};
string beginWord1 = "hit";
string endWord1 = "cog";
cout << Solution().ladderLength(beginWord1, endWord1, vec1) << endl;
// 5
// ---
vector<string> vec2 = {"a","b","c"};
string beginWord2 = "a";
string endWord2 = "c";
cout << Solution().ladderLength(beginWord2, endWord2, vec2) << endl;
// 2
// ---
vector<string> vec3 = {"most","fist","lost","cost","fish"};
string beginWord3 = "lost";
string endWord3 = "cost";
cout << Solution().ladderLength(beginWord3, endWord3, vec3) << endl;
// 2
// ---
vector<string> vec4 = {"hot","dot","dog","lot","log"};
string beginWord4 = "hit";
string endWord4 = "cog";
cout << Solution().ladderLength(beginWord4, endWord4, vec4) << endl;
// 0
return 0;
} | {
"pile_set_name": "Github"
} |
def extractAvertranslationBlogspotCom(item):
'''
Parser for 'avertranslation.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if "WATTT" in item['tags']:
return buildReleaseMessageWithType(item, "WATTT", vol, chp, frag=frag, postfix=postfix)
return False
| {
"pile_set_name": "Github"
} |
package digitalocean
import (
"bytes"
"context"
crand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"regexp"
"strings"
"testing"
"time"
"github.com/digitalocean/godo"
"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
func init() {
resource.AddTestSweepers("digitalocean_certificate", &resource.Sweeper{
Name: "digitalocean_certificate",
F: testSweepCertificate,
})
}
func testSweepCertificate(region string) error {
meta, err := sharedConfigForRegion(region)
if err != nil {
return err
}
client := meta.(*CombinedConfig).godoClient()
opt := &godo.ListOptions{PerPage: 200}
certs, _, err := client.Certificates.List(context.Background(), opt)
if err != nil {
return err
}
for _, c := range certs {
if strings.HasPrefix(c.Name, "certificate-") {
log.Printf("Destroying certificate %s", c.Name)
if _, err := client.Certificates.Delete(context.Background(), c.ID); err != nil {
return err
}
}
}
return nil
}
func TestAccDigitalOceanCertificate_Basic(t *testing.T) {
var cert godo.Certificate
rInt := acctest.RandInt()
privateKeyMaterial, leafCertMaterial, certChainMaterial := generateTestCertMaterial(t)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckDigitalOceanCertificateDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckDigitalOceanCertificateConfig_basic(rInt, privateKeyMaterial, leafCertMaterial, certChainMaterial),
Check: resource.ComposeTestCheckFunc(
testAccCheckDigitalOceanCertificateExists("digitalocean_certificate.foobar", &cert),
resource.TestCheckResourceAttr(
"digitalocean_certificate.foobar", "name", fmt.Sprintf("certificate-%d", rInt)),
resource.TestCheckResourceAttr(
"digitalocean_certificate.foobar", "private_key", HashString(fmt.Sprintf("%s\n", privateKeyMaterial))),
resource.TestCheckResourceAttr(
"digitalocean_certificate.foobar", "leaf_certificate", HashString(fmt.Sprintf("%s\n", leafCertMaterial))),
resource.TestCheckResourceAttr(
"digitalocean_certificate.foobar", "certificate_chain", HashString(fmt.Sprintf("%s\n", certChainMaterial))),
),
},
},
})
}
func TestAccDigitalOceanCertificate_ExpectedErrors(t *testing.T) {
rInt := acctest.RandInt()
privateKeyMaterial, leafCertMaterial, certChainMaterial := generateTestCertMaterial(t)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckDigitalOceanCertificateDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckDigitalOceanCertificateConfig_customNoLeaf(rInt, privateKeyMaterial, certChainMaterial),
ExpectError: regexp.MustCompile("`leaf_certificate` is required for when type is `custom` or empty"),
},
{
Config: testAccCheckDigitalOceanCertificateConfig_customNoKey(rInt, leafCertMaterial, certChainMaterial),
ExpectError: regexp.MustCompile("`private_key` is required for when type is `custom` or empty"),
},
{
Config: testAccCheckDigitalOceanCertificateConfig_noDomains(rInt),
ExpectError: regexp.MustCompile("`domains` is required for when type is `lets_encrypt`"),
},
},
})
}
func testAccCheckDigitalOceanCertificateDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*CombinedConfig).godoClient()
for _, rs := range s.RootModule().Resources {
if rs.Type != "digitalocean_certificate" {
continue
}
_, _, err := client.Certificates.Get(context.Background(), rs.Primary.ID)
if err != nil && !strings.Contains(err.Error(), "404") {
return fmt.Errorf(
"Error waiting for certificate (%s) to be destroyed: %s",
rs.Primary.ID, err)
}
}
return nil
}
func testAccCheckDigitalOceanCertificateExists(n string, cert *godo.Certificate) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No Certificate ID is set")
}
client := testAccProvider.Meta().(*CombinedConfig).godoClient()
c, _, err := client.Certificates.Get(context.Background(), rs.Primary.ID)
if err != nil {
return err
}
if c.ID != rs.Primary.ID {
return fmt.Errorf("Certificate not found")
}
*cert = *c
return nil
}
}
func generateTestCertMaterial(t *testing.T) (string, string, string) {
leafCertMaterial, privateKeyMaterial, err := randTLSCert("Acme Co", "example.com")
if err != nil {
t.Fatalf("Cannot generate test TLS certificate: %s", err)
}
rootCertMaterial, _, err := randTLSCert("Acme Go", "example.com")
if err != nil {
t.Fatalf("Cannot generate test TLS certificate: %s", err)
}
certChainMaterial := fmt.Sprintf("%s\n%s", strings.TrimSpace(rootCertMaterial), leafCertMaterial)
return privateKeyMaterial, leafCertMaterial, certChainMaterial
}
// Based on Terraform's acctest.RandTLSCert, but allows for passing DNS name.
func randTLSCert(orgName string, dnsName string) (string, string, error) {
template := &x509.Certificate{
SerialNumber: big.NewInt(int64(acctest.RandInt())),
Subject: pkix.Name{
Organization: []string{orgName},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: []string{dnsName},
}
privateKey, privateKeyPEM, err := genPrivateKey()
if err != nil {
return "", "", err
}
cert, err := x509.CreateCertificate(crand.Reader, template, template, &privateKey.PublicKey, privateKey)
if err != nil {
return "", "", err
}
certPEM, err := pemEncode(cert, "CERTIFICATE")
if err != nil {
return "", "", err
}
return certPEM, privateKeyPEM, nil
}
func genPrivateKey() (*rsa.PrivateKey, string, error) {
privateKey, err := rsa.GenerateKey(crand.Reader, 1024)
if err != nil {
return nil, "", err
}
privateKeyPEM, err := pemEncode(x509.MarshalPKCS1PrivateKey(privateKey), "RSA PRIVATE KEY")
if err != nil {
return nil, "", err
}
return privateKey, privateKeyPEM, nil
}
func pemEncode(b []byte, block string) (string, error) {
var buf bytes.Buffer
pb := &pem.Block{Type: block, Bytes: b}
if err := pem.Encode(&buf, pb); err != nil {
return "", err
}
return buf.String(), nil
}
func testAccCheckDigitalOceanCertificateConfig_basic(rInt int, privateKeyMaterial, leafCert, certChain string) string {
return fmt.Sprintf(`
resource "digitalocean_certificate" "foobar" {
name = "certificate-%d"
private_key = <<EOF
%s
EOF
leaf_certificate = <<EOF
%s
EOF
certificate_chain = <<EOF
%s
EOF
}`, rInt, privateKeyMaterial, leafCert, certChain)
}
func testAccCheckDigitalOceanCertificateConfig_customNoLeaf(rInt int, privateKeyMaterial, certChain string) string {
return fmt.Sprintf(`
resource "digitalocean_certificate" "foobar" {
name = "certificate-%d"
private_key = <<EOF
%s
EOF
certificate_chain = <<EOF
%s
EOF
}`, rInt, privateKeyMaterial, certChain)
}
func testAccCheckDigitalOceanCertificateConfig_customNoKey(rInt int, leafCert, certChain string) string {
return fmt.Sprintf(`
resource "digitalocean_certificate" "foobar" {
name = "certificate-%d"
leaf_certificate = <<EOF
%s
EOF
certificate_chain = <<EOF
%s
EOF
}`, rInt, leafCert, certChain)
}
func testAccCheckDigitalOceanCertificateConfig_noDomains(rInt int) string {
return fmt.Sprintf(`
resource "digitalocean_certificate" "foobar" {
name = "certificate-%d"
type = "lets_encrypt"
}`, rInt)
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* HIT_START
* BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS -std=c++11
* TEST: %t
* HIT_END
*/
#include "hip/hip_runtime.h"
#include "test_common.h"
int p_iters = 10;
void printSep() {
printf(
"======================================================================================\n");
}
//---
// Test simple H2D copies and back.
// Designed to stress a small number of simple smoke tests
template <typename T = float, class P = HipTest::Unpinned, class C = HipTest::Memcpy>
void simpleVectorAdd(size_t numElements, int iters, hipStream_t stream) {
using HipTest::MemTraits;
std::thread::id pid = std::this_thread::get_id();
printf("test: %s <%s> %s %s\n", __func__, TYPENAME(T), P::str(), C::str());
size_t Nbytes = numElements * sizeof(T);
printf("numElements=%zu Nbytes=%6.2fMB\n", numElements, Nbytes / 1024.0 / 1024.0);
T *A_d, *B_d, *C_d;
T *A_h, *B_h, *C_h;
HipTest::initArrays(&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, P::isPinned);
for (size_t i = 0; i < numElements; i++) {
A_h[i] = 1000.0f;
B_h[i] = 2000.0f;
C_h[i] = -1;
}
MemTraits<C>::Copy(B_d, B_h, Nbytes, hipMemcpyHostToDevice, stream);
MemTraits<C>::Copy(A_d, A_h, Nbytes, hipMemcpyHostToDevice, stream);
MemTraits<C>::Copy(C_d, C_h, Nbytes, hipMemcpyHostToDevice, stream);
HIPCHECK(hipDeviceSynchronize());
for (size_t i = 0; i < numElements; i++) {
A_h[i] = 1.0f;
B_h[i] = 2.0f;
C_h[i] = -1;
}
for (int i = 0; i < iters; i++) {
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numElements);
MemTraits<C>::Copy(A_d, A_h, Nbytes, hipMemcpyHostToDevice, stream);
MemTraits<C>::Copy(B_d, B_h, Nbytes, hipMemcpyHostToDevice, stream);
// HIPCHECK(hipStreamSynchronize(stream));
// This is the null stream?
// hipLaunchKernelGGL(HipTest::vectorADD, dim3(blocks), dim3(threadsPerBlock), 0, 0, A_d, B_d,
// C_d, numElements);
hipLaunchKernelGGL(HipTest::vectorADDReverse, dim3(blocks), dim3(threadsPerBlock), 0, 0,
static_cast<const T*>(A_d), static_cast<const T*>(B_d), C_d, numElements);
MemTraits<C>::Copy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost, stream);
HIPCHECK(hipDeviceSynchronize());
HipTest::checkVectorADD(A_h, B_h, C_h, numElements);
}
HipTest::freeArrays(A_d, B_d, C_d, A_h, B_h, C_h, P::isPinned);
std::cout << " pid" << pid << " success\n";
HIPCHECK(hipDeviceSynchronize());
}
template <typename T, class C>
void test_multiThread_1(std::string testName, hipStream_t stream0, hipStream_t stream1,
bool serialize) {
printSep();
printf("%s\n", __func__);
std::cout << testName << std::endl;
size_t numElements = N;
// Test 2 threads operating on same stream:
std::thread t1(simpleVectorAdd<T, HipTest::Pinned, C>, numElements, p_iters /*iters*/, stream0);
if (serialize) {
t1.join();
}
std::thread t2(simpleVectorAdd<T, HipTest::Pinned, C>, numElements, p_iters /*iters*/, stream1);
if (serialize) {
t2.join();
}
if (!serialize) {
t1.join();
t2.join();
}
HIPCHECK(hipDeviceSynchronize());
};
int main(int argc, char* argv[]) {
N = 8000000;
HipTest::parseStandardArguments(argc, argv, true);
printf("info: set device to %d\n", p_gpuDevice);
HIPCHECK(hipSetDevice(p_gpuDevice));
if (p_tests & 0x1) {
HIPCHECK(hipDeviceReset());
hipStream_t stream;
HIPCHECK(hipStreamCreate(&stream));
simpleVectorAdd<float, HipTest::Pinned, HipTest::MemcpyAsync>(N /*mb*/, 10 /*iters*/,
stream);
simpleVectorAdd<float, HipTest::Pinned, HipTest::Memcpy>(N /*mb*/, 10 /*iters*/, stream);
HIPCHECK(hipStreamDestroy(stream));
}
hipStream_t stream0, stream1;
HIPCHECK(hipStreamCreate(&stream0));
HIPCHECK(hipStreamCreate(&stream1));
if (p_tests & 0x2) {
// Easy tests to verify the test works - these don't allow overlap between the threads:
test_multiThread_1<float, HipTest::MemcpyAsync>("Multithread NULL with serialized", NULL,
NULL, true);
test_multiThread_1<float, HipTest::MemcpyAsync>("Multithread two streams serialized",
stream0, stream1, true);
}
if (p_tests & 0x4) {
// test_multiThread_1<float, HipTest::MemcpyAsync> ("Multithread with NULL stream", NULL,
// NULL, false); test_multiThread_1<float, HipTest::MemcpyAsync> ("Multithread with two
// streams", stream0, stream1, false);
test_multiThread_1<float, HipTest::MemcpyAsync>("Multithread with one stream", stream0,
stream0, false);
}
passed();
}
| {
"pile_set_name": "Github"
} |
/*
Unix SMB/Netbios implementation.
Version 3.0
handle NLTMSSP, server side
Copyright (C) Andrew Tridgell 2001
Copyright (C) Andrew Bartlett 2001-2003
Copyright (C) Andrew Bartlett 2005 (Updated from gensec).
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "../auth/ntlmssp/ntlmssp.h"
#include "../auth/ntlmssp/ntlmssp_private.h"
static void debug_ntlmssp_flags_raw(int level, uint32_t flags)
{
#define _PRINT_FLAG_LINE(v) do { \
if (flags & (v)) { \
DEBUGADD(level, (" " #v "\n")); \
} \
} while (0)
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_UNICODE);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_OEM);
_PRINT_FLAG_LINE(NTLMSSP_REQUEST_TARGET);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_SIGN);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_SEAL);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_DATAGRAM);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_LM_KEY);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_NETWARE);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_NTLM);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_NT_ONLY);
_PRINT_FLAG_LINE(NTLMSSP_ANONYMOUS);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_THIS_IS_LOCAL_CALL);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_ALWAYS_SIGN);
_PRINT_FLAG_LINE(NTLMSSP_TARGET_TYPE_DOMAIN);
_PRINT_FLAG_LINE(NTLMSSP_TARGET_TYPE_SERVER);
_PRINT_FLAG_LINE(NTLMSSP_TARGET_TYPE_SHARE);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_IDENTIFY);
_PRINT_FLAG_LINE(NTLMSSP_REQUEST_NON_NT_SESSION_KEY);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_TARGET_INFO);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_VERSION);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_128);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_KEY_EXCH);
_PRINT_FLAG_LINE(NTLMSSP_NEGOTIATE_56);
}
/**
* Print out the NTLMSSP flags for debugging
* @param neg_flags The flags from the packet
*/
void debug_ntlmssp_flags(uint32_t neg_flags)
{
DEBUG(3,("Got NTLMSSP neg_flags=0x%08x\n", neg_flags));
debug_ntlmssp_flags_raw(4, neg_flags);
}
NTSTATUS ntlmssp_handle_neg_flags(struct ntlmssp_state *ntlmssp_state,
uint32_t flags, const char *name)
{
uint32_t missing_flags = ntlmssp_state->required_flags;
if (flags & NTLMSSP_NEGOTIATE_UNICODE) {
ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_UNICODE;
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_OEM;
ntlmssp_state->unicode = true;
} else {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_UNICODE;
ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_OEM;
ntlmssp_state->unicode = false;
}
/*
* NTLMSSP_NEGOTIATE_NTLM2 (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY)
* has priority over NTLMSSP_NEGOTIATE_LM_KEY
*/
if (!(flags & NTLMSSP_NEGOTIATE_NTLM2)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2;
}
if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
}
if (!(flags & NTLMSSP_NEGOTIATE_LM_KEY)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY;
}
if (!(flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
}
if (!(flags & NTLMSSP_NEGOTIATE_128)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_128;
}
if (!(flags & NTLMSSP_NEGOTIATE_56)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_56;
}
if (!(flags & NTLMSSP_NEGOTIATE_KEY_EXCH)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_KEY_EXCH;
}
if (!(flags & NTLMSSP_NEGOTIATE_SIGN)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SIGN;
}
if (!(flags & NTLMSSP_NEGOTIATE_SEAL)) {
ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SEAL;
}
if ((flags & NTLMSSP_REQUEST_TARGET)) {
ntlmssp_state->neg_flags |= NTLMSSP_REQUEST_TARGET;
}
missing_flags &= ~ntlmssp_state->neg_flags;
if (missing_flags != 0) {
HRESULT hres = HRES_SEC_E_UNSUPPORTED_FUNCTION;
NTSTATUS status = NT_STATUS(HRES_ERROR_V(hres));
DEBUG(1, ("%s: Got %s flags[0x%08x] "
"- possible downgrade detected! "
"missing_flags[0x%08x] - %s\n",
__func__, name,
(unsigned)flags,
(unsigned)missing_flags,
nt_errstr(status)));
debug_ntlmssp_flags_raw(1, missing_flags);
DEBUGADD(4, ("neg_flags[0x%08x]\n",
(unsigned)ntlmssp_state->neg_flags));
debug_ntlmssp_flags_raw(4, ntlmssp_state->neg_flags);
return status;
}
return NT_STATUS_OK;
}
/* Does this blob looks like it could be NTLMSSP? */
bool ntlmssp_blob_matches_magic(const DATA_BLOB *blob)
{
if (blob->length > 8 && memcmp("NTLMSSP\0", blob->data, 8) == 0) {
return true;
} else {
return false;
}
}
const DATA_BLOB ntlmssp_version_blob(void)
{
/*
* This is a simplified version of
*
* enum ndr_err_code err;
* struct ntlmssp_VERSION vers;
*
* ZERO_STRUCT(vers);
* vers.ProductMajorVersion = NTLMSSP_WINDOWS_MAJOR_VERSION_6;
* vers.ProductMinorVersion = NTLMSSP_WINDOWS_MINOR_VERSION_1;
* vers.ProductBuild = 0;
* vers.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
*
* err = ndr_push_struct_blob(&version_blob,
* ntlmssp_state,
* &vers,
* (ndr_push_flags_fn_t)ndr_push_ntlmssp_VERSION);
*
* if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
* data_blob_free(&struct_blob);
* return NT_STATUS_NO_MEMORY;
* }
*/
static const uint8_t version_buffer[8] = {
NTLMSSP_WINDOWS_MAJOR_VERSION_6,
NTLMSSP_WINDOWS_MINOR_VERSION_1,
0x00, 0x00, /* product build */
0x00, 0x00, 0x00, /* reserved */
NTLMSSP_REVISION_W2K3
};
return data_blob_const(version_buffer, ARRAY_SIZE(version_buffer));
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_DEBUGGER_DEVTOOLS_MANAGER_IMPL_H_
#define CONTENT_BROWSER_DEBUGGER_DEVTOOLS_MANAGER_IMPL_H_
#pragma once
#include <map>
#include <string>
#include "base/compiler_specific.h"
#include "base/memory/singleton.h"
#include "content/browser/debugger/devtools_agent_host.h"
#include "content/common/content_export.h"
#include "content/public/browser/devtools_client_host.h"
#include "content/public/browser/devtools_manager.h"
class GURL;
namespace IPC {
class Message;
}
namespace content {
class DevToolsAgentHost;
class RenderViewHost;
// This class is a singleton that manages DevToolsClientHost instances and
// routes messages between developer tools clients and agents.
//
// Methods below that accept inspected RenderViewHost as a parameter are
// just convenience methods that call corresponding methods accepting
// DevToolAgentHost.
class CONTENT_EXPORT DevToolsManagerImpl
: public DevToolsAgentHost::CloseListener,
public DevToolsManager {
public:
// Returns single instance of this class. The instance is destroyed on the
// browser main loop exit so this method MUST NOT be called after that point.
static DevToolsManagerImpl* GetInstance();
DevToolsManagerImpl();
virtual ~DevToolsManagerImpl();
void DispatchOnInspectorFrontend(DevToolsAgentHost* agent_host,
const std::string& message);
void SaveAgentRuntimeState(DevToolsAgentHost* agent_host,
const std::string& state);
// Sends 'Attach' message to the agent using |dest_rvh| in case
// there is a DevToolsClientHost registered for the |inspected_rvh|.
void OnNavigatingToPendingEntry(RenderViewHost* inspected_rvh,
RenderViewHost* dest_rvh,
const GURL& gurl);
void OnCancelPendingNavigation(RenderViewHost* pending,
RenderViewHost* current);
// DevToolsManager implementation
virtual bool DispatchOnInspectorBackend(DevToolsClientHost* from,
const std::string& message) OVERRIDE;
virtual void ContentsReplaced(WebContents* old_contents,
WebContents* new_contents) OVERRIDE;
virtual void CloseAllClientHosts() OVERRIDE;
virtual void AttachClientHost(int client_host_cookie,
DevToolsAgentHost* to_agent) OVERRIDE;
virtual DevToolsClientHost* GetDevToolsClientHostFor(
DevToolsAgentHost* agent_host) OVERRIDE;
virtual DevToolsAgentHost* GetDevToolsAgentHostFor(
DevToolsClientHost* client_host) OVERRIDE;
virtual void RegisterDevToolsClientHostFor(
DevToolsAgentHost* agent_host,
DevToolsClientHost* client_host) OVERRIDE;
virtual void UnregisterDevToolsClientHostFor(
DevToolsAgentHost* agent_host) OVERRIDE;
virtual int DetachClientHost(DevToolsAgentHost* from_agent) OVERRIDE;
virtual void ClientHostClosing(DevToolsClientHost* host) OVERRIDE;
virtual void InspectElement(DevToolsAgentHost* agent_host,
int x, int y) OVERRIDE;
virtual void AddMessageToConsole(DevToolsAgentHost* agent_host,
ConsoleMessageLevel level,
const std::string& message) OVERRIDE;
private:
friend struct DefaultSingletonTraits<DevToolsManagerImpl>;
// DevToolsAgentHost::CloseListener implementation.
virtual void AgentHostClosing(DevToolsAgentHost* host) OVERRIDE;
void BindClientHost(DevToolsAgentHost* agent_host,
DevToolsClientHost* client_host);
void UnbindClientHost(DevToolsAgentHost* agent_host,
DevToolsClientHost* client_host);
// Detaches client host and returns cookie that can be used in
// AttachClientHost.
int DetachClientHost(RenderViewHost* from_rvh);
// Attaches orphan client host to new render view host.
void AttachClientHost(int client_host_cookie,
RenderViewHost* to_rvh);
// These two maps are for tracking dependencies between inspected contents and
// their DevToolsClientHosts. They are useful for routing devtools messages
// and allow us to have at most one devtools client host per contents.
//
// DevToolsManagerImpl starts listening to DevToolsClientHosts when they are
// put into these maps and removes them when they are closing.
typedef std::map<DevToolsAgentHost*, DevToolsClientHost*>
AgentToClientHostMap;
AgentToClientHostMap agent_to_client_host_;
typedef std::map<DevToolsClientHost*, DevToolsAgentHost*>
ClientToAgentHostMap;
ClientToAgentHostMap client_to_agent_host_;
typedef std::map<DevToolsAgentHost*, std::string> AgentRuntimeStates;
AgentRuntimeStates agent_runtime_states_;
typedef std::map<int, std::pair<DevToolsClientHost*, std::string> >
OrphanClientHosts;
OrphanClientHosts orphan_client_hosts_;
int last_orphan_cookie_;
DISALLOW_COPY_AND_ASSIGN(DevToolsManagerImpl);
};
} // namespace content
#endif // CONTENT_BROWSER_DEBUGGER_DEVTOOLS_MANAGER_IMPL_H_
| {
"pile_set_name": "Github"
} |
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
/* Check for automatic takeoff conditions being met using the following sequence:
* 1) Check for adequate GPS lock - if not return false
* 2) Check the gravity compensated longitudinal acceleration against the threshold and start the timer if true
* 3) Wait until the timer has reached the specified value (increments of 0.1 sec) and then check the GPS speed against the threshold
* 4) If the GPS speed is above the threshold and the attitude is within limits then return true and reset the timer
* 5) If the GPS speed and attitude within limits has not been achieved after 2.5 seconds, return false and reset the timer
* 6) If the time lapsed since the last timecheck is greater than 0.2 seconds, return false and reset the timer
* NOTE : This function relies on the TECS 50Hz processing for its acceleration measure.
*/
static bool auto_takeoff_check(void)
{
// this is a more advanced check that relies on TECS
uint32_t now = hal.scheduler->millis();
static bool launchTimerStarted;
static uint32_t last_tkoff_arm_time;
static uint32_t last_check_ms;
uint16_t wait_time_ms = min(uint16_t(g.takeoff_throttle_delay)*100,12700);
// Reset states if process has been interrupted
if (last_check_ms && (now - last_check_ms) > 200) {
gcs_send_text_fmt(PSTR("Timer Interrupted AUTO"));
launchTimerStarted = false;
last_tkoff_arm_time = 0;
last_check_ms = now;
return false;
}
last_check_ms = now;
// Check for bad GPS
if (gps.status() < AP_GPS::GPS_OK_FIX_3D) {
// no auto takeoff without GPS lock
return false;
}
// Check for launch acceleration or timer started. NOTE: relies on TECS 50Hz processing
if (!launchTimerStarted &&
g.takeoff_throttle_min_accel != 0.0f &&
SpdHgt_Controller->get_VXdot() < g.takeoff_throttle_min_accel) {
goto no_launch;
}
// we've reached the acceleration threshold, so start the timer
if (!launchTimerStarted) {
launchTimerStarted = true;
last_tkoff_arm_time = now;
gcs_send_text_fmt(PSTR("Armed AUTO, xaccel = %.1f m/s/s, waiting %.1f sec"),
SpdHgt_Controller->get_VXdot(), wait_time_ms*0.001f);
}
// Only perform velocity check if not timed out
if ((now - last_tkoff_arm_time) > wait_time_ms+100U) {
gcs_send_text_fmt(PSTR("Timeout AUTO"));
goto no_launch;
}
// Check aircraft attitude for bad launch
if (ahrs.pitch_sensor <= -3000 ||
ahrs.pitch_sensor >= 4500 ||
abs(ahrs.roll_sensor) > 3000) {
gcs_send_text_fmt(PSTR("Bad Launch AUTO"));
goto no_launch;
}
// Check ground speed and time delay
if (((gps.ground_speed() > g.takeoff_throttle_min_speed || g.takeoff_throttle_min_speed == 0.0f)) &&
((now - last_tkoff_arm_time) >= wait_time_ms)) {
gcs_send_text_fmt(PSTR("Triggered AUTO, GPSspd = %.1f"), gps.ground_speed());
launchTimerStarted = false;
last_tkoff_arm_time = 0;
return true;
}
// we're not launching yet, but the timer is still going
return false;
no_launch:
launchTimerStarted = false;
last_tkoff_arm_time = 0;
return false;
}
/*
calculate desired bank angle during takeoff, setting nav_roll_cd
*/
static void takeoff_calc_roll(void)
{
if (steer_state.hold_course_cd == -1) {
// we don't yet have a heading to hold - just level
// the wings until we get up enough speed to get a GPS heading
nav_roll_cd = 0;
return;
}
calc_nav_roll();
// during takeoff use the level flight roll limit to
// prevent large course corrections
nav_roll_cd = constrain_int32(nav_roll_cd, -g.level_roll_limit*100UL, g.level_roll_limit*100UL);
}
/*
calculate desired pitch angle during takeoff, setting nav_pitch_cd
*/
static void takeoff_calc_pitch(void)
{
if (auto_state.highest_airspeed < g.takeoff_rotate_speed) {
// we have not reached rotate speed, use a target pitch of 5
// degrees. This should be enough to get the tail off the
// ground, while making it unlikely that overshoot in the
// pitch controller will cause a prop strike
nav_pitch_cd = 500;
return;
}
if (ahrs.airspeed_sensor_enabled()) {
calc_nav_pitch();
if (nav_pitch_cd < auto_state.takeoff_pitch_cd) {
nav_pitch_cd = auto_state.takeoff_pitch_cd;
}
} else {
nav_pitch_cd = ((gps.ground_speed()*100) / (float)g.airspeed_cruise_cm) * auto_state.takeoff_pitch_cd;
nav_pitch_cd = constrain_int32(nav_pitch_cd, 500, auto_state.takeoff_pitch_cd);
}
}
/*
return a tail hold percentage during initial takeoff for a tail
dragger
This can be used either in auto-takeoff or in FBWA mode with
FBWA_TDRAG_CHAN enabled
*/
static int8_t takeoff_tail_hold(void)
{
bool in_takeoff = ((control_mode == AUTO && !auto_state.takeoff_complete) ||
(control_mode == FLY_BY_WIRE_A && auto_state.fbwa_tdrag_takeoff_mode));
if (!in_takeoff) {
// not in takeoff
return 0;
}
if (g.takeoff_tdrag_elevator == 0) {
// no takeoff elevator set
goto return_zero;
}
if (auto_state.highest_airspeed >= g.takeoff_tdrag_speed1) {
// we've passed speed1. We now raise the tail and aim for
// level pitch. Return 0 meaning no fixed elevator setting
goto return_zero;
}
if (ahrs.pitch_sensor > auto_state.initial_pitch_cd + 1000) {
// the pitch has gone up by more then 10 degrees over the
// initial pitch. This may mean the nose is coming up for an
// early liftoff, perhaps due to a bad setting of
// g.takeoff_tdrag_speed1. Go to level flight to prevent a
// stall
goto return_zero;
}
// we are holding the tail down
return g.takeoff_tdrag_elevator;
return_zero:
if (auto_state.fbwa_tdrag_takeoff_mode) {
gcs_send_text_P(SEVERITY_LOW, PSTR("FBWA tdrag off"));
auto_state.fbwa_tdrag_takeoff_mode = false;
}
return 0;
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "ZXParsedResultType.h"
#import "ZXResult.h"
/**
* Abstract class representing the result of decoding a barcode, as more than
* a String -- as some type of structured data. This might be a subclass which represents
* a URL, or an e-mail address. parseResult() will turn a raw
* decoded string into the most appropriate type of structured representation.
*
* Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
* on exception-based mechanisms during parsing.
*/
@interface ZXParsedResult : NSObject
@property (nonatomic, assign, readonly) ZXParsedResultType type;
- (id)initWithType:(ZXParsedResultType)type;
+ (id)parsedResultWithType:(ZXParsedResultType)type;
- (NSString *)displayResult;
+ (void)maybeAppend:(NSString *)value result:(NSMutableString *)result;
+ (void)maybeAppendArray:(NSArray *)value result:(NSMutableString *)result;
@end
| {
"pile_set_name": "Github"
} |
<div class="card">
<div class="card-divider">
<h2 class="card-title">
<%= t ".title" %>
</h2>
</div>
<div class="card-section">
<div class="grid-x grid-margin-x card-grid">
<% templates.each do |newsletter_template| %>
<div class="cell small-6">
<div class="card card--mini" id="<%= newsletter_template.name %>">
<iframe src="<%= preview_newsletter_template_path(newsletter_template.name) %>" class="email-preview newsletter-template-preview">
</iframe>
<div class="card-footer">
<h2 class="card-title">
<%= t newsletter_template.public_name_key %>
<%= link_to(t(".preview_template"), newsletter_template_path(newsletter_template.name), class: "button tiny button--title") %>
<%= link_to(t(".use_template"), new_newsletter_template_newsletter_path(newsletter_template.name), class: "button tiny button--title") %>
</h2>
</div>
</div>
</div>
<% end %>
</div>
</div>
</div>
| {
"pile_set_name": "Github"
} |
using System;
using Xamarin.Forms;
namespace ModalEnforcement
{
public partial class ModalEnforcementModalPage : ContentPage
{
public ModalEnforcementModalPage()
{
InitializeComponent();
}
protected override bool OnBackButtonPressed()
{
if (doneButton.IsEnabled)
{
return base.OnBackButtonPressed();
}
return true;
}
async void OnDoneButtonClicked(object sender, EventArgs args)
{
await Navigation.PopModalAsync();
}
}
}
| {
"pile_set_name": "Github"
} |
/* crypto/dh/dh_check.c */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/bn.h>
#include <openssl/dh.h>
/*-
* Check that p is a safe prime and
* if g is 2, 3 or 5, check that it is a suitable generator
* where
* for 2, p mod 24 == 11
* for 3, p mod 12 == 5
* for 5, p mod 10 == 3 or 7
* should hold.
*/
int DH_check(const DH *dh, int *ret)
{
int ok = 0;
BN_CTX *ctx = NULL;
BN_ULONG l;
BIGNUM *t1 = NULL, *t2 = NULL;
*ret = 0;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
BN_CTX_start(ctx);
t1 = BN_CTX_get(ctx);
if (t1 == NULL)
goto err;
t2 = BN_CTX_get(ctx);
if (t2 == NULL)
goto err;
if (dh->q) {
if (BN_cmp(dh->g, BN_value_one()) <= 0)
*ret |= DH_NOT_SUITABLE_GENERATOR;
else if (BN_cmp(dh->g, dh->p) >= 0)
*ret |= DH_NOT_SUITABLE_GENERATOR;
else {
/* Check g^q == 1 mod p */
if (!BN_mod_exp(t1, dh->g, dh->q, dh->p, ctx))
goto err;
if (!BN_is_one(t1))
*ret |= DH_NOT_SUITABLE_GENERATOR;
}
if (!BN_is_prime_ex(dh->q, BN_prime_checks, ctx, NULL))
*ret |= DH_CHECK_Q_NOT_PRIME;
/* Check p == 1 mod q i.e. q divides p - 1 */
if (!BN_div(t1, t2, dh->p, dh->q, ctx))
goto err;
if (!BN_is_one(t2))
*ret |= DH_CHECK_INVALID_Q_VALUE;
if (dh->j && BN_cmp(dh->j, t1))
*ret |= DH_CHECK_INVALID_J_VALUE;
} else if (BN_is_word(dh->g, DH_GENERATOR_2)) {
l = BN_mod_word(dh->p, 24);
if (l != 11)
*ret |= DH_NOT_SUITABLE_GENERATOR;
}
#if 0
else if (BN_is_word(dh->g, DH_GENERATOR_3)) {
l = BN_mod_word(dh->p, 12);
if (l != 5)
*ret |= DH_NOT_SUITABLE_GENERATOR;
}
#endif
else if (BN_is_word(dh->g, DH_GENERATOR_5)) {
l = BN_mod_word(dh->p, 10);
if ((l != 3) && (l != 7))
*ret |= DH_NOT_SUITABLE_GENERATOR;
} else
*ret |= DH_UNABLE_TO_CHECK_GENERATOR;
if (!BN_is_prime_ex(dh->p, BN_prime_checks, ctx, NULL))
*ret |= DH_CHECK_P_NOT_PRIME;
else if (!dh->q) {
if (!BN_rshift1(t1, dh->p))
goto err;
if (!BN_is_prime_ex(t1, BN_prime_checks, ctx, NULL))
*ret |= DH_CHECK_P_NOT_SAFE_PRIME;
}
ok = 1;
err:
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
return (ok);
}
int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret)
{
int ok = 0;
BIGNUM *tmp = NULL;
BN_CTX *ctx = NULL;
*ret = 0;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
BN_CTX_start(ctx);
tmp = BN_CTX_get(ctx);
if (tmp == NULL || !BN_set_word(tmp, 1))
goto err;
if (BN_cmp(pub_key, tmp) <= 0)
*ret |= DH_CHECK_PUBKEY_TOO_SMALL;
if (BN_copy(tmp, dh->p) == NULL || !BN_sub_word(tmp, 1))
goto err;
if (BN_cmp(pub_key, tmp) >= 0)
*ret |= DH_CHECK_PUBKEY_TOO_LARGE;
if (dh->q != NULL) {
/* Check pub_key^q == 1 mod p */
if (!BN_mod_exp(tmp, pub_key, dh->q, dh->p, ctx))
goto err;
if (!BN_is_one(tmp))
*ret |= DH_CHECK_PUBKEY_INVALID;
}
ok = 1;
err:
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
return (ok);
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.IO;
using WDBXEditor.Archives.Misc;
namespace WDBXEditor.Archives.FileSystem.Structures
{
public class BuildConfig
{
public string[] this[string name]
{
get
{
string[] entry;
if (entries.TryGetValue(name, out entry))
return entry;
return null;
}
}
Dictionary<string, string[]> entries = new Dictionary<string, string[]>();
public BuildConfig(string wowPath, string buildKey)
{
using (var sr = new StreamReader($"{wowPath}/Data/config/{buildKey.GetHexAt(0)}/{buildKey.GetHexAt(2)}/{buildKey}"))
{
while (!sr.EndOfStream)
{
var data = sr.ReadLine().Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (data.Length < 2)
continue;
var key = data[0].Trim();
var value = data[1].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
entries.Add(key, value);
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#pragma once
#include <memory>
#include <string>
#include "arrow/csv/options.h"
#include "arrow/dataset/file_base.h"
#include "arrow/dataset/type_fwd.h"
#include "arrow/dataset/visibility.h"
#include "arrow/status.h"
namespace arrow {
namespace dataset {
/// \brief A FileFormat implementation that reads from and writes to Csv files
class ARROW_DS_EXPORT CsvFileFormat : public FileFormat {
public:
/// Options affecting the parsing of CSV files
csv::ParseOptions parse_options = csv::ParseOptions::Defaults();
std::string type_name() const override { return "csv"; }
Result<bool> IsSupported(const FileSource& source) const override;
/// \brief Return the schema of the file if possible.
Result<std::shared_ptr<Schema>> Inspect(const FileSource& source) const override;
/// \brief Open a file for scanning
Result<ScanTaskIterator> ScanFile(std::shared_ptr<ScanOptions> options,
std::shared_ptr<ScanContext> context,
FileFragment* fragment) const override;
Status WriteFragment(RecordBatchReader*, io::OutputStream*) const override {
return Status::NotImplemented("writing fragment of CsvFileFormat");
}
};
} // namespace dataset
} // namespace arrow
| {
"pile_set_name": "Github"
} |
/*
* intf.c
*
* Network interface operations.
*
* Copyright (c) 2000 Dug Song <[email protected]>
*
* $Id: intf.h,v 1.16 2004/01/13 07:41:09 dugsong Exp $
*/
#ifndef DNET_INTF_H
#define DNET_INTF_H
/*
* Interface entry
*/
#define INTF_NAME_LEN 16
struct intf_entry {
u_int intf_len; /* length of entry */
char intf_name[INTF_NAME_LEN]; /* interface name */
u_short intf_type; /* interface type (r/o) */
u_short intf_flags; /* interface flags */
u_int intf_mtu; /* interface MTU */
struct addr intf_addr; /* interface address */
struct addr intf_dst_addr; /* point-to-point dst */
struct addr intf_link_addr; /* link-layer address */
u_int intf_alias_num; /* number of aliases */
struct addr intf_alias_addrs __flexarr; /* array of aliases */
};
/*
* MIB-II interface types - http://www.iana.org/assignments/ianaiftype-mib
*/
#define INTF_TYPE_OTHER 1 /* other */
#define INTF_TYPE_ETH 6 /* Ethernet */
#define INTF_TYPE_TOKENRING 9 /* Token Ring */
#define INTF_TYPE_FDDI 15 /* FDDI */
#define INTF_TYPE_PPP 23 /* Point-to-Point Protocol */
#define INTF_TYPE_LOOPBACK 24 /* software loopback */
#define INTF_TYPE_SLIP 28 /* Serial Line Interface Protocol */
#define INTF_TYPE_TUN 53 /* proprietary virtual/internal */
/*
* Interface flags
*/
#define INTF_FLAG_UP 0x01 /* enable interface */
#define INTF_FLAG_LOOPBACK 0x02 /* is a loopback net (r/o) */
#define INTF_FLAG_POINTOPOINT 0x04 /* point-to-point link (r/o) */
#define INTF_FLAG_NOARP 0x08 /* disable ARP */
#define INTF_FLAG_BROADCAST 0x10 /* supports broadcast (r/o) */
#define INTF_FLAG_MULTICAST 0x20 /* supports multicast (r/o) */
typedef struct intf_handle intf_t;
typedef int (*intf_handler)(const struct intf_entry *entry, void *arg);
__BEGIN_DECLS
intf_t *intf_open(void);
int intf_get(intf_t *i, struct intf_entry *entry);
int intf_get_src(intf_t *i, struct intf_entry *entry, struct addr *src);
int intf_get_dst(intf_t *i, struct intf_entry *entry, struct addr *dst);
int intf_set(intf_t *i, const struct intf_entry *entry);
int intf_loop(intf_t *i, intf_handler callback, void *arg);
intf_t *intf_close(intf_t *i);
__END_DECLS
#endif /* DNET_INTF_H */
| {
"pile_set_name": "Github"
} |
{
"name": "vinyl",
"description": "A virtual file format",
"version": "0.5.3",
"homepage": "http://github.com/wearefractal/vinyl",
"repository": "git://github.com/wearefractal/vinyl.git",
"author": "Fractal <[email protected]> (http://wearefractal.com/)",
"main": "./index.js",
"files": [
"index.js",
"lib"
],
"dependencies": {
"clone": "^1.0.0",
"clone-stats": "^0.0.1",
"replace-ext": "0.0.1"
},
"devDependencies": {
"buffer-equal": "0.0.1",
"event-stream": "^3.1.0",
"istanbul": "^0.3.0",
"istanbul-coveralls": "^1.0.1",
"jshint": "^2.4.1",
"lodash.templatesettings": "^3.1.0",
"mocha": "^2.0.0",
"rimraf": "^2.2.5",
"should": "^7.0.0"
},
"scripts": {
"test": "mocha && jshint lib",
"coveralls": "istanbul cover _mocha && istanbul-coveralls"
},
"engines": {
"node": ">= 0.9"
},
"license": "MIT"
}
| {
"pile_set_name": "Github"
} |
{
"jsonSchemaSemanticVersion": "1.0.0",
"imports": [
{
"corpusPath": "cdm:/foundations.1.2.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Common.1.0.cdm.json",
"moniker": "base_Common"
},
{
"corpusPath": "/core/operationsCommon/DataEntityView.1.0.cdm.json",
"moniker": "base_DataEntityView"
},
{
"corpusPath": "/core/operationsCommon/Tables/Finance/AccountingFoundation/WorksheetHeader/LedgerJournalTable.1.1.cdm.json"
},
{
"corpusPath": "TMSFreightBillDetail.1.1.cdm.json"
},
{
"corpusPath": "TMSInvoiceLine.1.1.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Tables/Finance/Ledger/Main/CompanyInfo.1.1.cdm.json"
}
],
"definitions": [
{
"entityName": "TMSLedgerJourRef",
"extendsEntity": "base_Common/Common",
"exhibitsTraits": [
{
"traitReference": "is.CDM.entityVersion",
"arguments": [
{
"name": "versionNumber",
"value": "1.1"
}
]
}
],
"hasAttributes": [
{
"name": "RefJournalNum",
"dataType": "TMSRefJournalNum",
"description": ""
},
{
"name": "RefRecId",
"dataType": "RefRecId",
"isNullable": true,
"description": ""
},
{
"name": "RefTableId",
"dataType": "RefTableId",
"isNullable": true,
"description": ""
},
{
"name": "DataAreaId",
"dataType": "string",
"isReadOnly": true
},
{
"entity": {
"entityReference": "LedgerJournalTable"
},
"name": "Relationship_LedgerJournalTableRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
},
{
"entity": {
"entityReference": "TMSFreightBillDetail"
},
"name": "Relationship_TMSFreightBillDetailRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
},
{
"entity": {
"entityReference": "TMSInvoiceLine"
},
"name": "Relationship_TMSInvoiceLineRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
},
{
"entity": {
"entityReference": "CompanyInfo"
},
"name": "Relationship_CompanyRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
}
],
"displayName": "Ledger Journal Reference"
},
{
"dataTypeName": "TMSRefJournalNum",
"extendsDataType": "string"
},
{
"dataTypeName": "RefRecId",
"extendsDataType": "bigInteger"
},
{
"dataTypeName": "RefTableId",
"extendsDataType": "integer"
}
]
} | {
"pile_set_name": "Github"
} |
{ compiler
, jupyterlabAppDir ? null
, nixpkgs ? import <nixpkgs> {}
, packages ? (_: [])
, pythonPackages ? (_: [])
, rtsopts ? "-M3g -N2"
, systemPackages ? (_: [])
}:
let
inherit (builtins) any elem filterSource listToAttrs;
lib = nixpkgs.lib;
cleanSource = name: type: let
baseName = baseNameOf (toString name);
in lib.cleanSourceFilter name type && !(
(type == "directory" && (elem baseName [ ".stack-work" "dist"])) ||
any (lib.flip lib.hasSuffix baseName) [ ".hi" ".ipynb" ".nix" ".sock" ".yaml" ".yml" ]
);
ihaskellSourceFilter = src: name: type: let
relPath = lib.removePrefix (toString src + "/") (toString name);
in cleanSource name type && ( any (lib.flip lib.hasPrefix relPath) [
"src" "main" "html" "Setup.hs" "ihaskell.cabal" "LICENSE"
]);
ihaskell-src = filterSource (ihaskellSourceFilter ./.) ./.;
ipython-kernel-src = filterSource cleanSource ./ipython-kernel;
ghc-parser-src = filterSource cleanSource ./ghc-parser;
ihaskell-display-src = filterSource cleanSource ./ihaskell-display;
displays = self: listToAttrs (
map
(display: { name = "ihaskell-${display}"; value = self.callCabal2nix display "${ihaskell-display-src}/ihaskell-${display}" {}; })
[ "aeson" "blaze" "charts" "diagrams" "gnuplot" "graphviz" "hatex" "juicypixels" "magic" "plot" "rlangqq" "static-canvas" "widgets" ]);
haskellPackages = nixpkgs.haskell.packages."${compiler}".override (old: {
overrides = nixpkgs.lib.composeExtensions (old.overrides or (_: _: {})) (self: super: {
ihaskell = nixpkgs.haskell.lib.overrideCabal (
self.callCabal2nix "ihaskell" ihaskell-src {}) (_drv: {
preCheck = ''
export HOME=$TMPDIR/home
export PATH=$PWD/dist/build/ihaskell:$PATH
export GHC_PACKAGE_PATH=$PWD/dist/package.conf.inplace/:$GHC_PACKAGE_PATH
'';
configureFlags = (_drv.configureFlags or []) ++ [
# otherwise the tests are agonisingly slow and the kernel times out
"--enable-executable-dynamic"
];
doHaddock = false;
});
ghc-parser = self.callCabal2nix "ghc-parser" ghc-parser-src {};
ipython-kernel = self.callCabal2nix "ipython-kernel" ipython-kernel-src {};
inline-r = nixpkgs.haskell.lib.dontCheck super.inline-r;
static-canvas = nixpkgs.haskell.lib.doJailbreak super.static-canvas;
} // displays self);
});
ihaskellEnv = haskellPackages.ghcWithPackages (self: [ self.ihaskell ] ++ packages self);
jupyterlab = nixpkgs.python3.withPackages (ps: [ ps.jupyterlab ] ++ pythonPackages ps);
ihaskellWrapperSh = nixpkgs.writeScriptBin "ihaskell-wrapper" ''
#! ${nixpkgs.stdenv.shell}
export GHC_PACKAGE_PATH="$(echo ${ihaskellEnv}/lib/*/package.conf.d| ${nixpkgs.coreutils}/bin/tr ' ' ':'):$GHC_PACKAGE_PATH"
export PATH="${nixpkgs.stdenv.lib.makeBinPath ([ ihaskellEnv jupyterlab ] ++ systemPackages nixpkgs)}''${PATH:+:}$PATH"
exec ${ihaskellEnv}/bin/ihaskell "$@"
'';
ihaskellJupyterCmdSh = cmd: extraArgs: nixpkgs.writeScriptBin "ihaskell-${cmd}" ''
#! ${nixpkgs.stdenv.shell}
export GHC_PACKAGE_PATH="$(echo ${ihaskellEnv}/lib/*/package.conf.d| ${nixpkgs.coreutils}/bin/tr ' ' ':'):$GHC_PACKAGE_PATH"
export PATH="${nixpkgs.stdenv.lib.makeBinPath ([ ihaskellEnv jupyterlab ] ++ systemPackages nixpkgs)}''${PATH:+:}$PATH"
${ihaskellEnv}/bin/ihaskell install \
-l $(${ihaskellEnv}/bin/ghc --print-libdir) \
--use-rtsopts="${rtsopts}" \
&& ${jupyterlab}/bin/jupyter ${cmd} ${extraArgs} "$@"
'';
appDir = if jupyterlabAppDir != null
then "--app-dir=${jupyterlabAppDir}"
else "";
in
nixpkgs.buildEnv {
name = "ihaskell-with-packages";
buildInputs = [ nixpkgs.makeWrapper ];
paths = [ ihaskellEnv jupyterlab ];
postBuild = ''
ln -s ${ihaskellJupyterCmdSh "lab" appDir}/bin/ihaskell-lab $out/bin/
ln -s ${ihaskellJupyterCmdSh "notebook" ""}/bin/ihaskell-notebook $out/bin/
ln -s ${ihaskellJupyterCmdSh "nbconvert" ""}/bin/ihaskell-nbconvert $out/bin/
ln -s ${ihaskellJupyterCmdSh "console" "--kernel=haskell"}/bin/ihaskell-console $out/bin/
for prg in $out/bin"/"*;do
if [[ -f $prg && -x $prg ]]; then
wrapProgram $prg --set PYTHONPATH "$(echo ${jupyterlab}/lib/*/site-packages)"
fi
done
'';
passthru = {
inherit haskellPackages;
inherit ihaskellEnv;
inherit jupyterlab;
inherit ihaskellJupyterCmdSh;
inherit ihaskellWrapperSh;
ihaskellJsFile = ./. + "/html/kernel.js";
ihaskellLogo64 = ./. + "/html/logo-64x64.svg";
};
}
| {
"pile_set_name": "Github"
} |
0 0 89 0 ihedfm, iddnfm, ihedun, iddnun
0 1 0 1 SP-01--TS-01 incode, ihddfl, ibudfl, icbcfl
0 0 1 0 SP-01--TS-01 hdpr, ddpr, hdsv, ddsv
-1 0 1 0 TS-02
-1 0 1 0 TS-03
-1 0 1 0 TS-04
-1 0 1 0 TS-05
-1 0 1 0 TS-06
-1 0 1 0 TS-07
-1 0 1 0 TS-08
-1 0 1 0 TS-09
-1 0 1 0 TS-10
-1 0 1 0 TS-11
-1 0 1 0 TS-12
-1 0 1 0 TS-13
-1 0 1 0 TS-14
-1 0 1 0 TS-15
-1 0 1 0 TS-16
-1 0 1 0 TS-17
-1 0 1 0 TS-18
-1 0 1 0 TS-19
-1 0 1 0 TS-20
-1 0 1 0 TS-21
-1 0 1 0 TS-22
-1 0 1 0 TS-23
-1 0 1 0 TS-24
-1 0 1 0 TS-25
-1 0 1 0 TS-26
-1 0 1 0 TS-27
-1 0 1 0 TS-28
-1 0 1 0 TS-29
-1 0 1 0 TS-30
-1 0 1 0 TS-31
-1 0 1 0 TS-32
-1 0 1 0 TS-33
-1 0 1 0 TS-34
-1 0 1 0 TS-35
-1 0 1 0 TS-36
-1 0 1 0 TS-37
-1 0 1 0 TS-38
-1 0 1 0 TS-39
-1 0 1 0 TS-40
-1 0 1 0 TS-41
-1 0 1 0 TS-42
-1 0 1 0 TS-43
-1 0 1 0 TS-44
-1 0 1 0 TS-45
-1 0 1 0 TS-46
-1 0 1 0 TS-47
-1 0 1 0 TS-48
-1 0 1 0 TS-49
-1 0 1 0 TS-50
-1 0 1 0 TS-51
-1 0 1 0 TS-52
-1 0 1 0 TS-53
-1 0 1 0 TS-54
-1 0 1 0 TS-55
-1 0 1 0 TS-56
-1 0 1 0 TS-57
-1 0 1 0 TS-58
-1 0 1 0 TS-59
-1 0 1 0 TS-60
-1 0 1 0 TS-61
-1 0 1 0 TS-62
-1 0 1 0 TS-63
-1 0 1 0 TS-64
-1 0 1 0 TS-65
-1 0 1 0 TS-66
-1 0 1 0 TS-67
-1 0 1 0 TS-68
-1 0 1 0 TS-69
-1 0 1 0 TS-70
-1 0 1 0 TS-71
-1 0 1 0 TS-72
-1 0 1 0 TS-73
-1 0 1 0 TS-74
-1 0 1 0 TS-75
-1 0 1 0 TS-76
-1 0 1 0 TS-77
-1 0 1 0 TS-78
-1 0 1 0 TS-79
-1 0 1 0 TS-80
-1 0 1 0 TS-81
-1 0 1 0 TS-82
-1 0 1 0 TS-83
-1 0 1 0 TS-84
-1 0 1 0 TS-85
-1 0 1 0 TS-86
-1 0 1 0 TS-87
-1 0 1 0 TS-88
-1 0 1 0 TS-89
-1 0 1 0 TS-90
-1 0 1 0 TS-91
-1 0 1 0 TS-92
-1 0 1 0 TS-93
-1 0 1 0 TS-94
-1 0 1 0 TS-95
-1 0 1 0 TS-96
-1 0 1 0 TS-97
-1 0 1 0 TS-98
-1 0 1 0 TS-99
-1 0 1 0 TS-100
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html>
<body>
<span style="border-left: 80px solid blue;">א12345</span>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/**
* This file is autogenerated by nRFgo Studio 1.17.1.3252
*/
#ifndef SETUP_MESSAGES_H__
#define SETUP_MESSAGES_H__
#include "hal_platform.h"
#include "aci.h"
#define SETUP_ID 0
#define SETUP_FORMAT 3 /** nRF8001 D */
#define ACI_DYNAMIC_DATA_SIZE 122
/* Service: Gap - Characteristic: Device name - Pipe: SET */
#define PIPE_GAP_DEVICE_NAME_SET 1
#define PIPE_GAP_DEVICE_NAME_SET_MAX_SIZE 7
/* Service: HelloTest - Characteristic: TestChar - Pipe: RX */
#define PIPE_HELLOTEST_TESTCHAR_RX 2
#define PIPE_HELLOTEST_TESTCHAR_RX_MAX_SIZE 3
#define NUMBER_OF_PIPES 2
#define SERVICES_PIPE_TYPE_MAPPING_CONTENT {\
{ACI_STORE_LOCAL, ACI_SET}, \
{ACI_STORE_LOCAL, ACI_RX}, \
}
#define GAP_PPCP_MAX_CONN_INT 0xffff /**< Maximum connection interval as a multiple of 1.25 msec , 0xFFFF means no specific value requested */
#define GAP_PPCP_MIN_CONN_INT 0xffff /**< Minimum connection interval as a multiple of 1.25 msec , 0xFFFF means no specific value requested */
#define GAP_PPCP_SLAVE_LATENCY 0
#define GAP_PPCP_CONN_TIMEOUT 0xffff /** Connection Supervision timeout multiplier as a multiple of 10msec, 0xFFFF means no specific value requested */
#define NB_SETUP_MESSAGES 16
#define SETUP_MESSAGES_CONTENT {\
{0x00,\
{\
0x07,0x06,0x00,0x00,0x03,0x02,0x42,0x07,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x02,0x01,0x01,0x00,0x00,0x06,0x00,0x01,\
0xd0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x10,0x1c,0xaa,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\
0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x14,0x03,0x90,0x01,0x64,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x10,0x38,0x02,0xff,0x02,0x58,0x05,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\
0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\
},\
},\
{0x00,\
{\
0x05,0x06,0x10,0x54,0x00,0x00,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x20,0x00,0x04,0x04,0x02,0x02,0x00,0x01,0x28,0x00,0x01,0x00,0x18,0x04,0x04,0x05,0x05,0x00,\
0x02,0x28,0x03,0x01,0x0e,0x03,0x00,0x00,0x2a,0x04,0x14,0x07,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x20,0x1c,0x07,0x00,0x03,0x2a,0x00,0x01,0x6d,0x79,0x5f,0x70,0x72,0x6f,0x6a,0x04,0x04,0x05,\
0x05,0x00,0x04,0x28,0x03,0x01,0x02,0x05,0x00,0x01,0x2a,0x06,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x20,0x38,0x04,0x03,0x02,0x00,0x05,0x2a,0x01,0x01,0x00,0x00,0x04,0x04,0x05,0x05,0x00,0x06,\
0x28,0x03,0x01,0x02,0x07,0x00,0x04,0x2a,0x06,0x04,0x09,0x08,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x20,0x54,0x00,0x07,0x2a,0x04,0x01,0xff,0xff,0xff,0xff,0x00,0x00,0xff,0xff,0x04,0x04,0x02,\
0x02,0x00,0x08,0x28,0x00,0x01,0x01,0x18,0x04,0x04,0x10,0x10,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x20,0x70,0x00,0x09,0x28,0x00,0x01,0xb8,0xd0,0x2d,0x81,0x63,0x29,0xef,0x96,0x8a,0x4d,0x55,\
0xb3,0xaa,0xff,0xb2,0x5a,0x04,0x04,0x13,0x13,0x00,0x0a,0x28,\
},\
},\
{0x00,\
{\
0x1f,0x06,0x20,0x8c,0x03,0x01,0x04,0x0b,0x00,0xb8,0xd0,0x2d,0x81,0x63,0x29,0xef,0x96,0x8a,0x4d,0x55,\
0xb3,0x05,0x00,0xb2,0x5a,0x44,0x10,0x03,0x00,0x00,0x0b,0x00,\
},\
},\
{0x00,\
{\
0x09,0x06,0x20,0xa8,0x05,0x02,0x00,0x00,0x00,0x00,\
},\
},\
{0x00,\
{\
0x17,0x06,0x40,0x00,0x2a,0x00,0x01,0x00,0x80,0x04,0x00,0x03,0x00,0x00,0x00,0x05,0x02,0x00,0x08,0x04,\
0x00,0x0b,0x00,0x00,\
},\
},\
{0x00,\
{\
0x13,0x06,0x50,0x00,0xb8,0xd0,0x2d,0x81,0x63,0x29,0xef,0x96,0x8a,0x4d,0x55,0xb3,0x00,0x00,0xb2,0x5a,\
},\
},\
{0x00,\
{\
0x09,0x06,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\
},\
},\
{0x00,\
{\
0x06,0x06,0xf0,0x00,0x03,0x5b,0x6b,\
},\
},\
}
#endif
| {
"pile_set_name": "Github"
} |
{
"swagger": "2.0",
"info": {
"title": "external/nodes/nodes.proto",
"version": "version not set"
},
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/api/v0/nodes": {
"post": {
"summary": "Create a Node",
"description": "Creates a node and adds it to the Chef Automate node manager.\nRequires a FQDN or IP address, a user-specified name, and a ssh or winrm credential reference.\nUseful for creating nodes for the purpose of running compliance scan jobs.\n\nExample:\n```\n{\n\"name\": \"my-vagrant-node\",\n\"manager\":\"automate\",\n\"target_config\": {\n\"backend\":\"ssh\",\n\"host\":\"localhost\",\n\"secrets\":[\"b75195e5-a173-4502-9f59-d949adfe2c38\"],\n\"port\": 22\n},\n\"tags\": [\n{ \"key\":\"test-node\", \"value\":\"is amazing\" }\n]\n}\n```\n\nAuthorization Action:\n```\ninfra:nodes:create\n```",
"operationId": "NodesService_Create",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Id"
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Node"
}
}
],
"tags": [
"NodesService"
]
}
},
"/api/v0/nodes/bulk-create": {
"post": {
"summary": "Bulk Create Nodes",
"description": "Creates multiple nodes from a list of node data.\n`hosts` field is required. Multiple hosts may be defined in this field.\n\nExample:\n```\n{\n\"name_prefix\": \"000-my-ssh-node\",\n\"manager\":\"automate\",\n\"target_config\": {\n\"backend\":\"ssh\",\n\"hosts\":[\"localhost\",\"127.0.0.1\"],\n\"secrets\":[\"b75195e5-a173-4502-9f59-d949adfe2c38\"],\n\"port\": 22\n},\n\"tags\": [\n{ \"key\":\"test-node\", \"value\":\"is-amazing\" },\n]\n}\n```\n\nAuthorization Action:\n```\ninfra:nodes:create\n```",
"operationId": "NodesService_BulkCreate",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Ids"
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Nodes"
}
}
],
"tags": [
"NodesService"
]
}
},
"/api/v0/nodes/delete": {
"post": {
"summary": "Bulk Delete Nodes by Filter",
"description": "Deletes a set of nodes that match a filter.\nAvailable filters: account_id, last_contact, manager_id, manager_type, name, platform_name,\nplatform_release, region, source_id, state, statechange_timerange, status,\nlast_run_timerange, last_scan_timerange, last_run_status, last_scan_status,\nlast_run_penultimate_status, last_scan_penultimate_status\n\nExample:\n```\n{\"filters\": [{\"key\": \"name\", \"values\": [\"vj*\"]}]}'\n```\n\nAuthorization Action:\n```\ninfra:nodes:delete\n```",
"operationId": "NodesService_BulkDelete",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.BulkDeleteResponse"
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Query"
}
}
],
"tags": [
"NodesService"
]
}
},
"/api/v0/nodes/delete/ids": {
"post": {
"summary": "Bulk Delete Nodes by ID",
"description": "Deletes a set of nodes given a list of IDs.\nInvalid IDs will be ignored.\n\nAuthorization Action:\n```\ninfra:nodes:delete\n```",
"operationId": "NodesService_BulkDeleteById",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.BulkDeleteResponse"
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Ids"
}
}
],
"tags": [
"NodesService"
]
}
},
"/api/v0/nodes/id/{id}": {
"get": {
"summary": "Show Node Details",
"description": "Returns the details for a node given the node ID.\n\nAuthorization Action:\n```\ninfra:nodes:get\n```",
"operationId": "NodesService_Read",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Node"
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "id",
"description": "Unique node ID (UUID)",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"NodesService"
]
},
"delete": {
"summary": "Delete a Node",
"description": "Deletes the node with the node ID.\n\nAuthorization Action:\n```\ninfra:nodes:delete\n```",
"operationId": "NodesService_Delete",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"properties": {}
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "id",
"description": "Unique node ID (UUID)",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"NodesService"
]
},
"put": {
"summary": "Update Node",
"description": "This PUT operation overwrites ALL node details and requires the complete set of node details,\nconsisting of a FQDN or IP address, a user-specified name, and the ID for an ssh or winrm credential.\nSubstitute the desired values for the existing node details in the PUT message.\n\nAuthorization Action:\n```\ninfra:nodes:update\n```",
"operationId": "NodesService_Update",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"properties": {}
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "id",
"description": "Unique node ID (UUID).",
"in": "path",
"required": true,
"type": "string"
},
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Node"
}
}
],
"tags": [
"NodesService"
]
}
},
"/api/v0/nodes/rerun/id/{id}": {
"get": {
"summary": "List Node Status",
"description": "Use this to run an `inspec detect` job on the node, which updates the status to reflect that the node is reachable or unreachable.\n\nAuthorization Action:\n```\ninfra:nodes:rerun\n```",
"operationId": "NodesService_Rerun",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.RerunResponse"
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "id",
"description": "Unique node ID (UUID)",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"NodesService"
]
}
},
"/api/v0/nodes/search": {
"post": {
"summary": "List and Filter Nodes",
"description": "Makes a list of nodes.\nSupports filtering, pagination, and sorting.\nAdding a filter narrows the list of nodes to only those that match the filter or filters.\nSupported filters:\naccount_id, last_contact, manager_id, manager_type, name, platform_name,\nplatform_release, region, source_id, state, statechange_timerange, status,\nlast_run_timerange, last_scan_timerange, last_run_status, last_scan_status,\nlast_run_penultimate_status, last_scan_penultimate_status\n\nExample:\n```\n{\n\"filters\":[\n{\"key\": \"last_scan_status\", \"values\": [\"FAILED\"]},\n{\"key\": \"last_scan_penultimate_status\", \"values\": [\"PASSED\"]},\n{\"key\": \"name\", \"values\": [\"MyNode*\"]}\n],\n\"page\":1, \"per_page\":100,\n\"sort\":\"status\", \"order\":\"ASC\"\n}\n```\n\nAuthorization Action:\n```\ninfra:nodes:list\n```",
"operationId": "NodesService_List",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Nodes"
}
},
"default": {
"description": "An unexpected error response",
"schema": {
"$ref": "#/definitions/grpc.gateway.runtime.Error"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Query"
}
}
],
"tags": [
"NodesService"
]
}
}
},
"definitions": {
"chef.automate.api.common.query.Filter": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Field to filter on."
},
"exclude": {
"type": "boolean",
"format": "boolean",
"description": "Include matches for this filter.(boolean)\n`true` (default) *includes* all nodes that match this filter. \n`false` *excludes* all nodes that match this filter."
},
"values": {
"type": "array",
"items": {
"type": "string"
},
"description": "Field values to filter on."
}
}
},
"chef.automate.api.common.query.Kv": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Tag key."
},
"value": {
"type": "string",
"description": "Tag value."
}
}
},
"chef.automate.api.nodes.v1.BulkDeleteResponse": {
"type": "object",
"properties": {
"names": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of deleted nodes, by name."
}
}
},
"chef.automate.api.nodes.v1.Id": {
"type": "object",
"properties": {
"id": {
"type": "string",
"title": "Unique node ID (UUID)"
}
}
},
"chef.automate.api.nodes.v1.Ids": {
"type": "object",
"properties": {
"ids": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of node UUIDs."
}
}
},
"chef.automate.api.nodes.v1.LastContactData": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Chef Infra run report ID or InSpec scan report ID."
},
"status": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.LastContactData.Status",
"description": "Last node report status."
},
"penultimate_status": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.LastContactData.Status",
"description": "Next-to-last node status report."
},
"end_time": {
"type": "string",
"format": "date-time",
"description": "Last node report endtime."
}
},
"description": "Most recent node data from the latest Chef Infra run and InSpec scan."
},
"chef.automate.api.nodes.v1.LastContactData.Status": {
"type": "string",
"enum": [
"UNKNOWN",
"PASSED",
"FAILED",
"SKIPPED"
],
"default": "UNKNOWN"
},
"chef.automate.api.nodes.v1.Node": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Unique node ID (UUID)."
},
"name": {
"type": "string",
"description": "User-specified node name."
},
"platform": {
"type": "string",
"description": "Node platform."
},
"platform_version": {
"type": "string",
"description": "Node platform version."
},
"manager": {
"type": "string",
"description": "Node manager (automate, aws-ec2, aws-api, azure-vm, azure-api, gcp)."
},
"tags": {
"type": "array",
"items": {
"$ref": "#/definitions/chef.automate.api.common.query.Kv"
},
"description": "Node tags."
},
"last_contact": {
"type": "string",
"format": "date-time",
"description": "Timestamp of the last `detect` or `exec` job."
},
"status": {
"type": "string",
"description": "Node status (unreachable, reachable, unknown)."
},
"last_job": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.ResultsRow",
"description": "Results of the last compliance scan job for this node."
},
"target_config": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.TargetConfig",
"description": "Node configuration for ssh or winrm."
},
"manager_ids": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of manager IDs for the node."
},
"connection_error": {
"type": "string",
"description": "Last connection error received when trying to contact the node."
},
"state": {
"type": "string",
"description": "Last known node state (running, stopped, terminated)."
},
"name_prefix": {
"type": "string",
"description": "Prefix for node name. The full node name is the prefix + the host."
},
"projects": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of projects associated with the node."
},
"run_data": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.LastContactData",
"description": "Most recent node data from the last Chef Infra run results."
},
"scan_data": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.LastContactData",
"description": "Most recent compliance scan data for the node from the last InSpec scan."
}
},
"description": "Node information."
},
"chef.automate.api.nodes.v1.Nodes": {
"type": "object",
"properties": {
"nodes": {
"type": "array",
"items": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Node"
},
"description": "List of nodes."
},
"total": {
"type": "integer",
"format": "int32",
"description": "Total number of nodes in the system."
},
"total_unreachable": {
"type": "integer",
"format": "int32",
"description": "Total number of unreachable nodes in the system."
},
"total_reachable": {
"type": "integer",
"format": "int32",
"description": "Total number of reachable nodes in the system."
},
"total_unknown": {
"type": "integer",
"format": "int32",
"description": "Total number of unknown nodes in the system."
}
}
},
"chef.automate.api.nodes.v1.Query": {
"type": "object",
"properties": {
"filters": {
"type": "array",
"items": {
"$ref": "#/definitions/chef.automate.api.common.query.Filter"
},
"description": "Use filters to limit the set of nodes to delete."
},
"order": {
"$ref": "#/definitions/chef.automate.api.nodes.v1.Query.OrderType"
},
"sort": {
"type": "string",
"description": "Sort the results on a specific field."
},
"page": {
"type": "integer",
"format": "int32",
"description": "The number of result pages to return."
},
"per_page": {
"type": "integer",
"format": "int32",
"description": "The number of results on each page."
}
}
},
"chef.automate.api.nodes.v1.Query.OrderType": {
"type": "string",
"enum": [
"ASC",
"DESC"
],
"default": "ASC",
"description": "Return the results in ascending or descending order."
},
"chef.automate.api.nodes.v1.RerunResponse": {
"type": "object"
},
"chef.automate.api.nodes.v1.ResultsRow": {
"type": "object",
"properties": {
"node_id": {
"type": "string",
"description": "Unique node ID."
},
"report_id": {
"type": "string",
"description": "Unique ID of the report generated by the InSpec scan."
},
"status": {
"type": "string",
"description": "Status of the report (failed, success, skipped)."
},
"result": {
"type": "string",
"description": "Error message returned after several failed attempts to contact a node."
},
"job_id": {
"type": "string",
"description": "Unique ID of the scan job that generated the report."
},
"start_time": {
"type": "string",
"format": "date-time",
"description": "Start time on the report."
},
"end_time": {
"type": "string",
"format": "date-time",
"description": "End time on the report."
}
},
"description": "Summary of the last Chef InSpec scan job run on the node."
},
"chef.automate.api.nodes.v1.TargetConfig": {
"type": "object",
"properties": {
"secrets": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of credential IDs for a node."
},
"backend": {
"type": "string",
"description": "Node backend type (ssh, winrm, aws, ssm, azure, gcp)."
},
"host": {
"type": "string",
"description": "Node FQDN or IP address."
},
"port": {
"type": "integer",
"format": "int32",
"title": "ssh or winrm connection port"
},
"sudo": {
"type": "boolean",
"format": "boolean",
"description": "Uses `sudo` (boolean)."
},
"ssl": {
"type": "boolean",
"format": "boolean",
"description": "Check ssl (boolean)."
},
"self_signed": {
"type": "boolean",
"format": "boolean",
"description": "Allow self-signed certificate (boolean)."
},
"user": {
"type": "string",
"description": "Username from the credential ID for this node."
},
"sudo_options": {
"type": "string",
"description": "Sudo options to use when accessing the node."
},
"hosts": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of hostnames (FQDN or IP address) for bulk creating nodes."
}
},
"description": "Details for ssh/winrm access of the node."
},
"google.protobuf.Any": {
"type": "object",
"properties": {
"type_url": {
"type": "string"
},
"value": {
"type": "string",
"format": "byte"
}
}
},
"grpc.gateway.runtime.Error": {
"type": "object",
"properties": {
"error": {
"type": "string"
},
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"details": {
"type": "array",
"items": {
"$ref": "#/definitions/google.protobuf.Any"
}
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.TestClient.PublishTestResults;
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Microsoft.VisualStudio.Services.Agent.Worker.TestResults
{
public interface IParser : IExtension
{
string Name { get; }
TestDataProvider ParseTestResultFiles(IExecutionContext executionContext, TestRunContext testRunContext, List<string> testResultsFiles);
}
public abstract class Parser : AgentService
{
public Type ExtensionType => typeof(IParser);
public abstract string Name { get; }
protected abstract ITestResultParser GetTestResultParser(IExecutionContext executionContext);
public TestDataProvider ParseTestResultFiles(IExecutionContext executionContext, TestRunContext testRunContext, List<string> testResultsFiles)
{
ArgUtil.NotNull(executionContext, nameof(executionContext));
if (string.IsNullOrEmpty(Name))
{
executionContext.Warning("Test runner name is null or empty");
return null;
}
// Create test result parser object based on the test Runner provided
var testResultParser = GetTestResultParser(executionContext);
if (testResultParser == null)
{
return null;
}
// Parse with the corresponding testResultParser object
return ParseFiles(executionContext, testRunContext, testResultsFiles, testResultParser);
}
private TestDataProvider ParseFiles(IExecutionContext executionContext, TestRunContext testRunContext, List<string> testResultsFiles, ITestResultParser testResultParser)
{
if (testResultParser == null)
{
return null;
}
TestDataProvider testDataProvider = null;
try
{
// Parse test results files
testDataProvider = testResultParser.ParseTestResultFiles(testRunContext, testResultsFiles);
}
catch (Exception ex)
{
executionContext.Write("Failed to parse result files: ", ex.ToString());
}
return testDataProvider;
}
}
public class JUnitParser : Parser, IParser
{
public override string Name => "JUnit";
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")]
protected override ITestResultParser GetTestResultParser(IExecutionContext executionContext)
{
var traceListener = new CommandTraceListener(executionContext);
return new JUnitResultParser(traceListener);
}
}
public class XUnitParser : Parser, IParser
{
public override string Name => "XUnit";
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")]
protected override ITestResultParser GetTestResultParser(IExecutionContext executionContext)
{
var traceListener = new CommandTraceListener(executionContext);
return new XUnitResultParser(traceListener);
}
}
public class TrxParser : Parser, IParser
{
public override string Name => "VSTest";
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")]
protected override ITestResultParser GetTestResultParser(IExecutionContext executionContext)
{
var traceListener = new CommandTraceListener(executionContext);
return new TrxResultParser(traceListener);
}
}
public class NUnitParser : Parser, IParser
{
public override string Name => "NUnit";
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")]
protected override ITestResultParser GetTestResultParser(IExecutionContext executionContext)
{
var traceListener = new CommandTraceListener(executionContext);
return new NUnitResultParser(traceListener);
}
}
public class CTestParser : Parser, IParser
{
public override string Name => "CTest";
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")]
protected override ITestResultParser GetTestResultParser(IExecutionContext executionContext)
{
var traceListener = new CommandTraceListener(executionContext);
return new CTestResultParser(traceListener);
}
}
public class ContainerStructureTestParser: Parser, IParser
{
public override string Name => "ContainerStructure";
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")]
protected override ITestResultParser GetTestResultParser(IExecutionContext executionContext)
{
var traceListener = new CommandTraceListener(executionContext);
return new ContainerStructureTestResultParser(traceListener);
}
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- **************************************************************** -->
<!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * -->
<!-- * i.e. only iterate & print data where possible. Thanks, Jez. * -->
<!-- **************************************************************** -->
<html>
<head>
<!-- Generated by groovydoc (2.3.3) on Tue Jul 01 09:50:59 CEST 2014 -->
<title>OsgiPluginConvention (Gradle API 2.0)</title>
<meta name="date" content="2014-07-01">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<body class="center">
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="OsgiPluginConvention (Gradle API 2.0)";
}
//-->
</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="../../../../../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">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/plugins/osgi/OsgiPluginConvention" target="_top">Frames</a></li>
<li><a href="OsgiPluginConvention.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#constructor_summary">Constructor</a></li> <li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#constructor_detail">Constructor</a></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">
<div class="subTitle">Package: <strong>org.gradle.api.plugins.osgi</strong></div>
<h2 title="[Java] Class OsgiPluginConvention" class="title">[Java] Class OsgiPluginConvention</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><ul class="inheritance"></ul></li><li>org.gradle.api.plugins.osgi.OsgiPluginConvention
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<p> Is mixed in into the project when applying the <a href='../../../../../org/gradle/api/plugins/osgi/OsgiPlugin.html' title='OsgiPlugin'>OsgiPlugin</a> .
</p>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== NESTED CLASS SUMMARY =========== -->
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<!-- =========== FIELD SUMMARY =========== -->
<!-- =========== PROPERTY SUMMARY =========== -->
<!-- =========== ELEMENT SUMMARY =========== -->
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary"><!-- --></a>
<h3>Constructor Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructors Summary table">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Constructor and description</th>
</tr>
<tr class="altColor">
<td class="colFirst">
<code><a href="#OsgiPluginConvention(ProjectInternal)">OsgiPluginConvention</a></strong>
(<a href='../../../../../ProjectInternal.html'>ProjectInternal</a> project)</code><br></td>
</tr>
</table>
</ul>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary"><!-- --></a>
<h3>Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Methods Summary table">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Type</th>
<th class="colLast" scope="col">Name and description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html'>OsgiManifest</a></strong></code></td>
<td class="colLast"><code><strong><a href="#osgiManifest()">osgiManifest</a></strong>()</code><br>Creates a new instance of <a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html' title='OsgiManifest'>OsgiManifest</a>. </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html'>OsgiManifest</a></strong></code></td>
<td class="colLast"><code><strong><a href="#osgiManifest(groovy.lang.Closure)">osgiManifest</a></strong>(<a href='http://groovy.codehaus.org/gapi/groovy/lang/Closure.html' title='Closure'>Closure</a> closure)</code><br>Creates and configures a new instance of an <a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html' title='OsgiManifest'>OsgiManifest</a> . </td>
</tr>
</table>
</ul>
</li>
<li class="blockList"><a name="method_summary"><!-- --></a>
<h3>Inherited Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Inherited Methods Summary table">
<caption><span>Inherited Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Methods inherited from class</th>
<th class="colLast" scope="col">Name</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html' title='Object'>Object</a></strong></code></td>
<td class="colLast"><code><a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait(long, int)' title='wait'>wait</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait(long)' title='wait'>wait</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait()' title='wait'>wait</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)' title='equals'>equals</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#toString()' title='toString'>toString</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#hashCode()' title='hashCode'>hashCode</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#getClass()' title='getClass'>getClass</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#notify()' title='notify'>notify</a>, <a href='http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#notifyAll()' title='notifyAll'>notifyAll</a></code></td>
</tr>
</table>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- =========== CONSTRUCTOR DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="OsgiPluginConvention(ProjectInternal)"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>public <strong>OsgiPluginConvention</strong>(<a href='../../../../../ProjectInternal.html'>ProjectInternal</a> project)</h4>
<p></p>
</li>
</ul>
</li>
</ul>
<!-- =========== METHOD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="osgiManifest()"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>public <a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html'>OsgiManifest</a> <strong>osgiManifest</strong>()</h4>
<p> Creates a new instance of <a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html' title='OsgiManifest'>OsgiManifest</a>. The returned object is preconfigured with:
<pre>
version: project.version
name: project.archivesBaseName
symbolicName: project.group + "." + project.archivesBaseName (see below for exceptions to this rule)
</pre>
The symbolic name is usually the group + "." + archivesBaseName, with the following exceptions
<ul>
<li>if group has only one section (no dots) and archivesBaseName is not null then the
first package name with classes is returned. eg. commons-logging:commons-logging ->
org.apache.commons.logging</li>
<li>if archivesBaseName is equal to last section of group then group is returned. eg.
org.gradle:gradle -> org.gradle</li>
<li>if archivesBaseName starts with last section of group that portion is removed. eg.
org.gradle:gradle-core -> org.gradle.core</li>
</ul>
</p>
</li>
</ul>
<a name="osgiManifest(groovy.lang.Closure)"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>public <a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html'>OsgiManifest</a> <strong>osgiManifest</strong>(<a href='http://groovy.codehaus.org/gapi/groovy/lang/Closure.html' title='Closure'>Closure</a> closure)</h4>
<p> Creates and configures a new instance of an <a href='../../../../../org/gradle/api/plugins/osgi/OsgiManifest.html' title='OsgiManifest'>OsgiManifest</a> . The closure configures
the new manifest instance before it is returned.
</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</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="../../../../../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">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/plugins/osgi/OsgiPluginConvention" target="_top">Frames</a></li>
<li><a href="OsgiPluginConvention.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#constructor_summary">Constructor</a></li> <li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#constructor_detail">Constructor</a></li> <li><a href="#method_detail">Method</a></li>
</ul>
</div>
<p>Gradle API 2.0</p>
<a name="skip-navbar_bottom">
<!-- -->
</a>
</div>
</div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
nyaggle.hyper_parameters
--------------------------
.. automodule:: nyaggle.hyper_parameters
:members:
:imported-members:
| {
"pile_set_name": "Github"
} |
package gophercloud
import (
"encoding/json"
"fmt"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
// BuildRequestBody builds a map[string]interface from the given `struct`. If
// parent is not the empty string, the final map[string]interface returned will
// encapsulate the built one
//
func BuildRequestBody(opts interface{}, parent string) (map[string]interface{}, error) {
optsValue := reflect.ValueOf(opts)
if optsValue.Kind() == reflect.Ptr {
optsValue = optsValue.Elem()
}
optsType := reflect.TypeOf(opts)
if optsType.Kind() == reflect.Ptr {
optsType = optsType.Elem()
}
optsMap := make(map[string]interface{})
if optsValue.Kind() == reflect.Struct {
//fmt.Printf("optsValue.Kind() is a reflect.Struct: %+v\n", optsValue.Kind())
for i := 0; i < optsValue.NumField(); i++ {
v := optsValue.Field(i)
f := optsType.Field(i)
if f.Name != strings.Title(f.Name) {
//fmt.Printf("Skipping field: %s...\n", f.Name)
continue
}
//fmt.Printf("Starting on field: %s...\n", f.Name)
zero := isZero(v)
//fmt.Printf("v is zero?: %v\n", zero)
// if the field has a required tag that's set to "true"
if requiredTag := f.Tag.Get("required"); requiredTag == "true" {
//fmt.Printf("Checking required field [%s]:\n\tv: %+v\n\tisZero:%v\n", f.Name, v.Interface(), zero)
// if the field's value is zero, return a missing-argument error
if zero {
// if the field has a 'required' tag, it can't have a zero-value
err := ErrMissingInput{}
err.Argument = f.Name
return nil, err
}
}
if xorTag := f.Tag.Get("xor"); xorTag != "" {
//fmt.Printf("Checking `xor` tag for field [%s] with value %+v:\n\txorTag: %s\n", f.Name, v, xorTag)
xorField := optsValue.FieldByName(xorTag)
var xorFieldIsZero bool
if reflect.ValueOf(xorField.Interface()) == reflect.Zero(xorField.Type()) {
xorFieldIsZero = true
} else {
if xorField.Kind() == reflect.Ptr {
xorField = xorField.Elem()
}
xorFieldIsZero = isZero(xorField)
}
if !(zero != xorFieldIsZero) {
err := ErrMissingInput{}
err.Argument = fmt.Sprintf("%s/%s", f.Name, xorTag)
err.Info = fmt.Sprintf("Exactly one of %s and %s must be provided", f.Name, xorTag)
return nil, err
}
}
if orTag := f.Tag.Get("or"); orTag != "" {
//fmt.Printf("Checking `or` tag for field with:\n\tname: %+v\n\torTag:%s\n", f.Name, orTag)
//fmt.Printf("field is zero?: %v\n", zero)
if zero {
orField := optsValue.FieldByName(orTag)
var orFieldIsZero bool
if reflect.ValueOf(orField.Interface()) == reflect.Zero(orField.Type()) {
orFieldIsZero = true
} else {
if orField.Kind() == reflect.Ptr {
orField = orField.Elem()
}
orFieldIsZero = isZero(orField)
}
if orFieldIsZero {
err := ErrMissingInput{}
err.Argument = fmt.Sprintf("%s/%s", f.Name, orTag)
err.Info = fmt.Sprintf("At least one of %s and %s must be provided", f.Name, orTag)
return nil, err
}
}
}
if v.Kind() == reflect.Struct || (v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct) {
if zero {
//fmt.Printf("value before change: %+v\n", optsValue.Field(i))
if jsonTag := f.Tag.Get("json"); jsonTag != "" {
jsonTagPieces := strings.Split(jsonTag, ",")
if len(jsonTagPieces) > 1 && jsonTagPieces[1] == "omitempty" {
if v.CanSet() {
if !v.IsNil() {
if v.Kind() == reflect.Ptr {
v.Set(reflect.Zero(v.Type()))
}
}
//fmt.Printf("value after change: %+v\n", optsValue.Field(i))
}
}
}
continue
}
//fmt.Printf("Calling BuildRequestBody with:\n\tv: %+v\n\tf.Name:%s\n", v.Interface(), f.Name)
_, err := BuildRequestBody(v.Interface(), f.Name)
if err != nil {
return nil, err
}
}
}
//fmt.Printf("opts: %+v \n", opts)
b, err := json.Marshal(opts)
if err != nil {
return nil, err
}
//fmt.Printf("string(b): %s\n", string(b))
err = json.Unmarshal(b, &optsMap)
if err != nil {
return nil, err
}
//fmt.Printf("optsMap: %+v\n", optsMap)
if parent != "" {
optsMap = map[string]interface{}{parent: optsMap}
}
//fmt.Printf("optsMap after parent added: %+v\n", optsMap)
return optsMap, nil
}
// Return an error if the underlying type of 'opts' isn't a struct.
return nil, fmt.Errorf("Options type is not a struct.")
}
// EnabledState is a convenience type, mostly used in Create and Update
// operations. Because the zero value of a bool is FALSE, we need to use a
// pointer instead to indicate zero-ness.
type EnabledState *bool
// Convenience vars for EnabledState values.
var (
iTrue = true
iFalse = false
Enabled EnabledState = &iTrue
Disabled EnabledState = &iFalse
)
// IPVersion is a type for the possible IP address versions. Valid instances
// are IPv4 and IPv6
type IPVersion int
const (
// IPv4 is used for IP version 4 addresses
IPv4 IPVersion = 4
// IPv6 is used for IP version 6 addresses
IPv6 IPVersion = 6
)
// IntToPointer is a function for converting integers into integer pointers.
// This is useful when passing in options to operations.
func IntToPointer(i int) *int {
return &i
}
/*
MaybeString is an internal function to be used by request methods in individual
resource packages.
It takes a string that might be a zero value and returns either a pointer to its
address or nil. This is useful for allowing users to conveniently omit values
from an options struct by leaving them zeroed, but still pass nil to the JSON
serializer so they'll be omitted from the request body.
*/
func MaybeString(original string) *string {
if original != "" {
return &original
}
return nil
}
/*
MaybeInt is an internal function to be used by request methods in individual
resource packages.
Like MaybeString, it accepts an int that may or may not be a zero value, and
returns either a pointer to its address or nil. It's intended to hint that the
JSON serializer should omit its field.
*/
func MaybeInt(original int) *int {
if original != 0 {
return &original
}
return nil
}
/*
func isUnderlyingStructZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Ptr:
return isUnderlyingStructZero(v.Elem())
default:
return isZero(v)
}
}
*/
var t time.Time
func isZero(v reflect.Value) bool {
//fmt.Printf("\n\nchecking isZero for value: %+v\n", v)
switch v.Kind() {
case reflect.Ptr:
if v.IsNil() {
return true
}
return false
case reflect.Func, reflect.Map, reflect.Slice:
return v.IsNil()
case reflect.Array:
z := true
for i := 0; i < v.Len(); i++ {
z = z && isZero(v.Index(i))
}
return z
case reflect.Struct:
if v.Type() == reflect.TypeOf(t) {
if v.Interface().(time.Time).IsZero() {
return true
}
return false
}
z := true
for i := 0; i < v.NumField(); i++ {
z = z && isZero(v.Field(i))
}
return z
}
// Compare other types directly:
z := reflect.Zero(v.Type())
//fmt.Printf("zero type for value: %+v\n\n\n", z)
return v.Interface() == z.Interface()
}
/*
BuildQueryString is an internal function to be used by request methods in
individual resource packages.
It accepts a tagged structure and expands it into a URL struct. Field names are
converted into query parameters based on a "q" tag. For example:
type struct Something {
Bar string `q:"x_bar"`
Baz int `q:"lorem_ipsum"`
}
instance := Something{
Bar: "AAA",
Baz: "BBB",
}
will be converted into "?x_bar=AAA&lorem_ipsum=BBB".
The struct's fields may be strings, integers, or boolean values. Fields left at
their type's zero value will be omitted from the query.
*/
func BuildQueryString(opts interface{}) (*url.URL, error) {
optsValue := reflect.ValueOf(opts)
if optsValue.Kind() == reflect.Ptr {
optsValue = optsValue.Elem()
}
optsType := reflect.TypeOf(opts)
if optsType.Kind() == reflect.Ptr {
optsType = optsType.Elem()
}
params := url.Values{}
if optsValue.Kind() == reflect.Struct {
for i := 0; i < optsValue.NumField(); i++ {
v := optsValue.Field(i)
f := optsType.Field(i)
qTag := f.Tag.Get("q")
// if the field has a 'q' tag, it goes in the query string
if qTag != "" {
tags := strings.Split(qTag, ",")
// if the field is set, add it to the slice of query pieces
if !isZero(v) {
loop:
switch v.Kind() {
case reflect.Ptr:
v = v.Elem()
goto loop
case reflect.String:
params.Add(tags[0], v.String())
case reflect.Int:
params.Add(tags[0], strconv.FormatInt(v.Int(), 10))
case reflect.Bool:
params.Add(tags[0], strconv.FormatBool(v.Bool()))
case reflect.Slice:
switch v.Type().Elem() {
case reflect.TypeOf(0):
for i := 0; i < v.Len(); i++ {
params.Add(tags[0], strconv.FormatInt(v.Index(i).Int(), 10))
}
default:
for i := 0; i < v.Len(); i++ {
params.Add(tags[0], v.Index(i).String())
}
}
}
} else {
// Otherwise, the field is not set.
if len(tags) == 2 && tags[1] == "required" {
// And the field is required. Return an error.
return nil, fmt.Errorf("Required query parameter [%s] not set.", f.Name)
}
}
}
}
return &url.URL{RawQuery: params.Encode()}, nil
}
// Return an error if the underlying type of 'opts' isn't a struct.
return nil, fmt.Errorf("Options type is not a struct.")
}
/*
BuildHeaders is an internal function to be used by request methods in
individual resource packages.
It accepts an arbitrary tagged structure and produces a string map that's
suitable for use as the HTTP headers of an outgoing request. Field names are
mapped to header names based in "h" tags.
type struct Something {
Bar string `h:"x_bar"`
Baz int `h:"lorem_ipsum"`
}
instance := Something{
Bar: "AAA",
Baz: "BBB",
}
will be converted into:
map[string]string{
"x_bar": "AAA",
"lorem_ipsum": "BBB",
}
Untagged fields and fields left at their zero values are skipped. Integers,
booleans and string values are supported.
*/
func BuildHeaders(opts interface{}) (map[string]string, error) {
optsValue := reflect.ValueOf(opts)
if optsValue.Kind() == reflect.Ptr {
optsValue = optsValue.Elem()
}
optsType := reflect.TypeOf(opts)
if optsType.Kind() == reflect.Ptr {
optsType = optsType.Elem()
}
optsMap := make(map[string]string)
if optsValue.Kind() == reflect.Struct {
for i := 0; i < optsValue.NumField(); i++ {
v := optsValue.Field(i)
f := optsType.Field(i)
hTag := f.Tag.Get("h")
// if the field has a 'h' tag, it goes in the header
if hTag != "" {
tags := strings.Split(hTag, ",")
// if the field is set, add it to the slice of query pieces
if !isZero(v) {
switch v.Kind() {
case reflect.String:
optsMap[tags[0]] = v.String()
case reflect.Int:
optsMap[tags[0]] = strconv.FormatInt(v.Int(), 10)
case reflect.Bool:
optsMap[tags[0]] = strconv.FormatBool(v.Bool())
}
} else {
// Otherwise, the field is not set.
if len(tags) == 2 && tags[1] == "required" {
// And the field is required. Return an error.
return optsMap, fmt.Errorf("Required header not set.")
}
}
}
}
return optsMap, nil
}
// Return an error if the underlying type of 'opts' isn't a struct.
return optsMap, fmt.Errorf("Options type is not a struct.")
}
// IDSliceToQueryString takes a slice of elements and converts them into a query
// string. For example, if name=foo and slice=[]int{20, 40, 60}, then the
// result would be `?name=20&name=40&name=60'
func IDSliceToQueryString(name string, ids []int) string {
str := ""
for k, v := range ids {
if k == 0 {
str += "?"
} else {
str += "&"
}
str += fmt.Sprintf("%s=%s", name, strconv.Itoa(v))
}
return str
}
// IntWithinRange returns TRUE if an integer falls within a defined range, and
// FALSE if not.
func IntWithinRange(val, min, max int) bool {
return val > min && val < max
}
| {
"pile_set_name": "Github"
} |
---
external help file: Microsoft.Azure.PowerShell.Cmdlets.Consumption.dll-Help.xml
Module Name: Az.Billing
online version: https://docs.microsoft.com/en-us/powershell/module/az.billing/get-azconsumptionmarketplace
schema: 2.0.0
---
# Get-AzConsumptionMarketplace
## SYNOPSIS
Get marketplaces of the subscription.
## SYNTAX
```
Get-AzConsumptionMarketplace [-BillingPeriodName <String>] [-EndDate <DateTime>] [-InstanceId <String>]
[-InstanceName <String>] [-ResourceGroup <String>] [-StartDate <DateTime>] [-Top <Int32>]
[-DefaultProfile <IAzureContextContainer>] [<CommonParameters>]
```
## DESCRIPTION
The **Get-AzConsumptionMarketplace** cmdlet gets marketplaces of the subscription.
## EXAMPLES
### Example 1: Get marketplaces usage
```powershell
PS C:\> Get-AzConsumptionMarketplace -Top 10
BillingPeriodId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201807-1
ConsumedQuantity: 24
Currency: USD
Id: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201807-1/providers/Microsoft.Consumption/marketplaces/018b7291-57a5-e194-65ea-28c3f1db76aa
InstanceId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/resourceGroups/TESTRG1/providers/Microsoft.Compute/virtualMachines/TestVM
InstanceName: TestVM
IsEstimated: false
Name: 018b7291-57a5-e194-65ea-28c3f1db76aa
OfferName: 2b380487-dc18-4e5d-981f-1ee2cc59e776
PretaxCost: 0
ResourceRate: 0
SubscriptionGuid: 6b74c45b-9597-4939-a202-36b2ee8fbb3d
Type: Microsoft.Consumption/usageDetails
UsageEnd: 2018-04-29T00:00:00Z
UsageStart: 2018-04-28T00:00:00Z
```
### Example 2: Get marketplace usage with date range
```powershell
PS C:\> Get-AzConsumptionMarketplace -StartDate 2018-01-03 -EndDate 2018-01-20 -Top 10
BillingPeriodId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201803-1
ConsumedQuantity: 24
Currency: USD
Id: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201803-1/providers/Microsoft.Consumption/marketplaces/0ec2bd1e-1cd6-0c75-3661-eaf3f635df33
InstanceId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/resourceGroups/TESTRG1/providers/Microsoft.Compute/virtualMachines/TestVM
InstanceName: TestVM
IsEstimated: false
Name: 0ec2bd1e-1cd6-0c75-3661-eaf3f635df33
OfferName: 2b380487-dc18-4e5d-981f-1ee2cc59e776
PretaxCost: 0
ResourceRate: 0
SubscriptionGuid: 6b74c45b-9597-4939-a202-36b2ee8fbb3d
Type: Microsoft.Consumption/usageDetails
UsageEnd: 2018-01-04T00:00:00Z
UsageStart: 2018-01-03T00:00:00Z
```
### Example 3: Get marketplace usage of BillingPeriodName
```powershell
PS C:\> Get-AzConsumptionMarketplace -BillingPeriodName 201801-1 -Top 10
BillingPeriodId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201801-1
ConsumedQuantity: 24
Currency: USD
Id: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201801-1/providers/Microsoft.Consumption/marketplaces/ea82233a-9f76-7eaa-4478-42bd61cf6287
InstanceId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/resourceGroups/TESTRG1/providers/Microsoft.Compute/virtualMachines/TestVM
InstanceName: TestVM
IsEstimated: false
Name: ea82233a-9f76-7eaa-4478-42bd61cf6287
OfferName: 2b380487-dc18-4e5d-981f-1ee2cc59e776
PretaxCost: 0
ResourceRate: 0
SubscriptionGuid: 6b74c45b-9597-4939-a202-36b2ee8fbb3d
Type: Microsoft.Consumption/usageDetails
UsageEnd: 2017-10-29T00:00:00Z
UsageStart: 2017-10-28T00:00:00Z
```
### Example 4: Get marketplace usage with InstanceName filter
```powershell
PS C:\> Get-AzConsumptionMarketplace -InstanceName TestVM -Top 10
BillingPeriodId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201807-1
ConsumedQuantity: 24
Currency: USD
Id: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/providers/Microsoft.Billing/billingPeriods/201807-1/providers/Microsoft.Consumption/marketplaces/018b7291-57a5-e194-65ea-28c3f1db76aa
InstanceId: subscriptions/6b74c45b-9597-4939-a202-36b2ee8fbb3d/resourceGroups/TESTRG1/providers/Microsoft.Compute/virtualMachines/TestVM
InstanceName: TestVM
IsEstimated: false
Name: 018b7291-57a5-e194-65ea-28c3f1db76aa
OfferName: 2b380487-dc18-4e5d-981f-1ee2cc59e776
PretaxCost: 0
ResourceRate: 0
SubscriptionGuid: 6b74c45b-9597-4939-a202-36b2ee8fbb3d
Type: Microsoft.Consumption/usageDetails
UsageEnd: 2018-04-29T00:00:00Z
UsageStart: 2018-04-28T00:00:00Z
```
## PARAMETERS
### -BillingPeriodName
Name of a specific billing period to get the marketplace that associate with.
```yaml
Type: System.String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with Azure.
```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzContext, AzureRmContext, AzureCredential
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EndDate
The end date (in UTC) of the marketplaces to filter.
```yaml
Type: System.Nullable`1[System.DateTime]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -InstanceId
The instance id of the marketplaces to filter.
```yaml
Type: System.String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -InstanceName
The instance name of the marketplaces to filter.
```yaml
Type: System.String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResourceGroup
The resource group of the marketplaces to filter.
```yaml
Type: System.String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -StartDate
The start date (in UTC) of the marketplaces to filter.
```yaml
Type: System.Nullable`1[System.DateTime]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Top
Determine the maximum number of records to return.
```yaml
Type: System.Nullable`1[System.Int32]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### None
## OUTPUTS
### Microsoft.Azure.Commands.Consumption.Models.PSMarketplace
## NOTES
## RELATED LINKS
| {
"pile_set_name": "Github"
} |
<map id="gov.nasa.jpl.componentaction.ISFSubsystem.getSourceComp" name="gov.nasa.jpl.componentaction.ISFSubsystem.getSourceComp">
<area shape="rect" id="node2" href="$classgov_1_1nasa_1_1jpl_1_1componentaction_1_1_i_s_f_subsystem.html#a2860b5135b693b6e31e1115281ca8b24" title="gov.nasa.jpl.componentaction.\lISFSubsystem.getSourceConnEnd" alt="" coords="262,5,490,43"/>
<area shape="rect" id="node5" href="$classgov_1_1nasa_1_1jpl_1_1componentaction_1_1_i_s_f_subsystem.html#a4044ed4b73d4df7aa66400ac4057ce3c" title="gov.nasa.jpl.componentaction.\lISFSubsystem.getCompName" alt="" coords="275,67,477,106"/>
<area shape="rect" id="node3" href="$classgov_1_1nasa_1_1jpl_1_1componentaction_1_1_i_s_f_subsystem.html#a8d892025f44c008c6afd8c263ce6f458" title="gov.nasa.jpl.componentaction.\lISFSubsystem.getConnEnd" alt="" coords="538,5,739,43"/>
<area shape="rect" id="node4" href="$classgov_1_1nasa_1_1jpl_1_1componentaction_1_1_utils.html#afb67c5cdf8debaca7812864e86685fd9" title="gov.nasa.jpl.componentaction.\lUtils.throwConnectorException" alt="" coords="788,5,991,43"/>
</map>
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
namespace PrestaShop\PrestaShop\Core\Grid\Query;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use PrestaShop\PrestaShop\Core\Feature\FeatureInterface;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;
use PrestaShop\PrestaShop\Core\Multistore\MultistoreContextCheckerInterface;
/**
* Class CategoryQueryBuilder builds search & count queries for categories grid.
*/
final class CategoryQueryBuilder extends AbstractDoctrineQueryBuilder
{
/**
* @var int
*/
private $contextLangId;
/**
* @var int
*/
private $contextShopId;
/**
* @var int|null
*
* Can be null for backward-compatibility
*/
private $rootCategoryId;
/**
* @var DoctrineSearchCriteriaApplicator
*/
private $searchCriteriaApplicator;
/**
* @var MultistoreContextCheckerInterface
*/
private $multistoreContextChecker;
/**
* @var FeatureInterface
*/
private $multistoreFeature;
/**
* @param Connection $connection
* @param string $dbPrefix
* @param DoctrineSearchCriteriaApplicator $searchCriteriaApplicator
* @param int $contextLangId
* @param int $contextShopId
* @param MultistoreContextCheckerInterface $multistoreContextChecker
* @param FeatureInterface $multistoreFeature
* @param int|null $rootCategoryId
*/
public function __construct(
Connection $connection,
$dbPrefix,
DoctrineSearchCriteriaApplicator $searchCriteriaApplicator,
$contextLangId,
$contextShopId,
MultistoreContextCheckerInterface $multistoreContextChecker,
FeatureInterface $multistoreFeature,
$rootCategoryId = null
) {
parent::__construct($connection, $dbPrefix);
$this->contextLangId = $contextLangId;
$this->contextShopId = $contextShopId;
$this->rootCategoryId = $rootCategoryId;
$this->searchCriteriaApplicator = $searchCriteriaApplicator;
$this->multistoreContextChecker = $multistoreContextChecker;
$this->multistoreFeature = $multistoreFeature;
}
/**
* {@inheritdoc}
*/
public function getSearchQueryBuilder(SearchCriteriaInterface $searchCriteria)
{
$qb = $this->getQueryBuilder($searchCriteria->getFilters());
$qb->select('c.id_category, c.id_parent, c.active, cl.name, cl.description, cs.position');
$this->searchCriteriaApplicator
->applyPagination($searchCriteria, $qb)
->applySorting($searchCriteria, $qb);
return $qb;
}
/**
* {@inheritdoc}
*/
public function getCountQueryBuilder(SearchCriteriaInterface $searchCriteria)
{
$qb = $this->getQueryBuilder($searchCriteria->getFilters());
$qb->select('COUNT(c.id_category)');
return $qb;
}
/**
* Get generic query builder.
*
* @param array $filters
*
* @return QueryBuilder
*/
private function getQueryBuilder(array $filters)
{
$qb = $this->connection
->createQueryBuilder()
->from($this->dbPrefix . 'category', 'c')
->setParameter('context_lang_id', $this->contextLangId)
->setParameter('context_shop_id', $this->contextShopId);
$qb->leftJoin(
'c',
$this->dbPrefix . 'category_lang',
'cl',
$this->multistoreFeature->isUsed() && $this->multistoreContextChecker->isSingleShopContext() ?
'c.id_category = cl.id_category AND cl.id_lang = :context_lang_id AND cl.id_shop = :context_shop_id' :
'c.id_category = cl.id_category AND cl.id_lang = :context_lang_id AND cl.id_shop = c.id_shop_default'
);
$qb->leftJoin(
'c',
$this->dbPrefix . 'category_shop',
'cs',
$this->multistoreContextChecker->isSingleShopContext() ?
'c.id_category = cs.id_category AND cs.id_shop = :context_shop_id' :
'c.id_category = cs.id_category AND cs.id_shop = c.id_shop_default'
);
foreach ($filters as $filterName => $filterValue) {
if ('id_category' === $filterName) {
$qb->andWhere("c.id_category = :$filterName");
$qb->setParameter($filterName, $filterValue);
continue;
}
// exclude root category from search results
if ($this->rootCategoryId !== null) {
$qb->andWhere('c.id_category != :root_category_id');
$qb->setParameter('root_category_id', $this->rootCategoryId);
}
if ('name' === $filterName) {
$qb->andWhere("cl.name LIKE :$filterName");
$qb->setParameter($filterName, '%' . $filterValue . '%');
continue;
}
if ('description' === $filterName) {
$qb->andWhere("cl.description LIKE :$filterName");
$qb->setParameter($filterName, '%' . $filterValue . '%');
continue;
}
if ('position' === $filterName) {
// When filtering by position,
// value must be decreased by 1,
// since position value in database starts at 0,
// but for user display positions are increased by 1.
if (is_numeric($filterValue)) {
--$filterValue;
} else {
$filterValue = null;
}
$qb->andWhere("cs.position = :$filterName");
$qb->setParameter($filterName, $filterValue);
continue;
}
if ('active' === $filterName) {
$qb->andWhere("c.active = :$filterName");
$qb->setParameter($filterName, $filterValue);
continue;
}
if ('id_category_parent' === $filterName) {
if ($this->isSearchRequestOnHomeCategory($filters)) {
continue;
}
$qb->andWhere("c.id_parent = :$filterName");
$qb->setParameter($filterName, $filterValue);
continue;
}
}
if ($this->multistoreFeature->isUsed() && $this->multistoreContextChecker->isSingleShopContext()) {
$qb->andWhere('cs.id_shop = :context_shop_id');
}
return $qb;
}
/**
* @param array $filters
*
* @return bool
*/
private function isSearchRequestOnHomeCategory(array $filters)
{
return isset($filters['is_home_category'], $filters['is_search_request'])
&& $filters['is_home_category'] === true && $filters['is_search_request'] === true;
}
}
| {
"pile_set_name": "Github"
} |
(function () {
'use strict';
angular.module('adminApplication').service('ResourceService', function($http, $q) {
return {
listTemplates: function() {
return $http.get('/admin/api/overridable-template/');
},
getTemplateBody: function(name, locale) {
return $http.get('/admin/api/overridable-template/'+name+'/'+locale);
},
getMetadataForOrganizationResource: function(orgId, name) {
return $http.get('/admin/api/resource-organization/'+orgId+'/'+name+'/metadata');
},
getOrganizationResource: function(orgId, name) {
return $http.get('/admin/api/resource-organization/'+orgId+'/'+name);
},
uploadOrganizationFile: function(orgId, file) {
return $http.post('/admin/api/resource-organization/'+orgId+'/', file);
},
deleteOrganizationFile: function(orgId, name) {
return $http.delete('/admin/api/resource-organization/'+orgId+'/'+name);
},
/**/
getMetadataForEventResource: function(orgId, eventId, name) {
return $http.get('/admin/api/resource-event/'+orgId+'/'+eventId+'/'+name+'/metadata');
},
getEventResource: function(orgId, eventId, name) {
return $http.get('/admin/api/resource-event/'+orgId+'/'+eventId+'/'+name);
},
uploadFile: function(orgId, eventId, file) {
return $http.post('/admin/api/resource-event/'+orgId+'/'+eventId+'/', file);
},
deleteFile: function(orgId, eventId, name) {
return $http.delete('/admin/api/resource-event/'+orgId+'/'+eventId+'/'+name);
},
preview: function(orgId, eventId, name, locale, file) {
return $http.post('/admin/api/overridable-template/'+name+'/'+locale+'/preview?organizationId='+orgId+(eventId !== undefined ? '&eventId='+eventId : ''), file, {responseType: 'blob'}).then(function(res) {
var contentType = res.headers('Content-Type');
if(contentType.startsWith('text/plain')) {
var reader = new FileReader();
var promise = $q(function(resolve, reject) {
reader.onloadend = function() {
resolve({download: false, text: reader.result})
}
});
reader.readAsText(res.data);
return promise;
}
var fileName = res.headers('content-disposition').match(/filename=(.*)$/)[1];
var finalFile = new File([res.data], fileName, {type: contentType});
var fileUrl = URL.createObjectURL(finalFile);
var a = document.createElement('a');
//for FF, we must append the element: https://stackoverflow.com/a/32226068
document.body.appendChild(a);
a.href = fileUrl;
a.download = fileName;
a.click();
setTimeout(function(){
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
return {download: true}
});
}
};
});
})(); | {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-02-07 15:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pyscada', '0052_auto_20181207_1019'),
]
operations = [
migrations.AlterField(
model_name='variable',
name='value_class',
field=models.CharField(choices=[('FLOAT32', 'REAL (FLOAT32)'), ('FLOAT32', 'SINGLE (FLOAT32)'), ('FLOAT32', 'FLOAT32'), ('UNIXTIMEF32', 'UNIXTIMEF32'), ('FLOAT64', 'LREAL (FLOAT64)'), ('FLOAT64', 'FLOAT (FLOAT64)'), ('FLOAT64', 'DOUBLE (FLOAT64)'), ('FLOAT64', 'FLOAT64'), ('FLOAT48', 'FLOAT48'), ('UNIXTIMEF64', 'UNIXTIMEF64'), ('INT64', 'INT64'), ('UINT64', 'UINT64'), ('UNIXTIMEI64', 'UNIXTIMEI64'), ('UNIXTIMEI32', 'UNIXTIMEI32'), ('INT32', 'INT32'), ('UINT32', 'DWORD (UINT32)'), ('UINT32', 'UINT32'), ('INT16', 'INT (INT16)'), ('INT16', 'INT16'), ('UINT16', 'WORD (UINT16)'), ('UINT16', 'UINT (UINT16)'), ('UINT16', 'UINT16'), ('BOOLEAN', 'BOOL (BOOLEAN)'), ('BOOLEAN', 'BOOLEAN')], default='FLOAT64', max_length=15, verbose_name='value_class'),
),
]
| {
"pile_set_name": "Github"
} |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#ifndef XCSOAR_EVENT_IDLE_HPP
#define XCSOAR_EVENT_IDLE_HPP
#include "Util/Compiler.h"
/**
* Check whether the user is currently inactive.
*
* When the user is currently interacting with XCSoar, we should
* attempt to reduce UI latency, for example by reducing rendering
* details.
*
* @return true if the user has been idle for at the specified number
* of milliseconds or more
*/
gcc_pure
bool
IsUserIdle(unsigned duration_ms);
/**
* Acts as if the user had just interacted with XCSoar.
*/
void
ResetUserIdle();
#endif
| {
"pile_set_name": "Github"
} |
/*
* remainder.c
* cLibm
*
* Written by Jon Okada, started on December 7th, 1992.
* Modified by Paul Finlayson (PAF) for MathLib v2.
* Modified by A. Sazegari (ali) for MathLib v3.
* Modified and ported by Robert A. Murley (ram) for Mac OS X.
* Modified for cLibm, fixed a few edge cases, rewrote local_ funcs by Ian Ollmann.
*
* Copyright 2007 Apple Inc. All rights reserved.
*
*/
#include <math.h>
#include <float.h>
#include <stdint.h>
#ifdef ARMLIBM_SET_FLAGS
#include "required_arithmetic.h"
#endif
static inline int local_ilogb( double x ) __attribute__ ((always_inline));
static inline int local_ilogb( double x )
{
union{ double d; uint64_t u;}u = {x};
u.u &= 0x7fffffffffffffffULL;
int32_t exp = (int32_t) (u.u >> 52);
if( __builtin_expect( (uint32_t) exp - 1U >= 2046, 0 ) )
{ // +-denorm, the other possibilities: +0 +-inf, NaN are screend out by caller
u.u |= 0x3ff0000000000000ULL;
u.d -= 1.0;
exp = (int32_t) (u.u >> 52);
return exp - (1023+1022);
}
return exp - 1023;
}
static inline double local_scalbn( double x, int n );
static inline double local_scalbn( double x, int n )
{
union{ uint64_t u; double d;} u;
uint32_t absn = n >> (8*sizeof(n)-1);
absn = (n ^ absn) - absn;
if( absn > 1022 )
{
// step = copysign( 1022, n )
int signMask = n >> (8 * sizeof( int ) - 1);
int step = (1022 ^ signMask) - signMask;
u.u = ( (int64_t) step + 1023ULL) << 52;
if( n < 0 )
{
do
{
x *= u.d;
n -= step;
}while( n < -1022 );
}
else
{
do
{
x *= u.d;
n -= step;
}while( n > 1022 );
}
}
//create 2**n in double
u.u = ( (int64_t) n + 1023ULL) << 52;
//scale by appropriate power of 2
x *= u.d;
//return result
return x;
}
double remainder( double x, double y )
{
// deal with NaN
if( x != x || y != y )
return x + y;
//x = Inf or y = 0, return Invalid per IEEE-754
double fabsx = __builtin_fabs(x);
if( fabsx == __builtin_inf() || 0.0 == y )
{
#ifdef ARMLIBM_SET_FLAGS
return required_add_double( __builtin_inf(), -__builtin_inf() ); //set invalid
#else
return __builtin_nan("");
#endif
}
//handle trivial case
double fabsy = __builtin_fabs(y);
if( fabsy == __builtin_inf() || 0.0 == x )
{
#ifdef ARMLIBM_SET_FLAGS
required_add_double( fabsx, 0.0 ); // signal underflow (that is, no flag set,
// but exception occurs if unmasked) if x is denorm
#endif
return x;
}
//we have to work
int32_t iquo = 0;
int32_t iscx = local_ilogb(fabsx);
int32_t iscy = local_ilogb(fabsy);
int32_t idiff = iscx - iscy;
double x1, y1, z;
x1 = fabsx;
y1 = fabsy;
if( idiff >= 0 )
{
int32_t i;
if( idiff )
{
y1 = local_scalbn( y1, -iscy );
x1 = local_scalbn( x1, -iscx );
for( i = idiff; i != 0; i-- )
{
if( x1 >= y1 )
{
x1 -= y1;
iquo += 1;
}
iquo += iquo;
x1 += x1;
}
x1 = local_scalbn( x1, iscy );
}
if( x1 >= fabsy )
{
x1 -= fabsy;
iquo += 1;
}
}
if( x1 < 0x1.0p1022 )
{
z = x1 + x1;
if( (z > fabsy) || ((z == fabsy) & ((iquo & 1) != 0 )))
x1 -= fabsy;
}
else
{
// x1 is only this large if y is even bigger, so we can safely divide y by 2
double halfy = 0.5*fabsy;
if( (x1 > halfy) || ((x1 == halfy) & ((iquo & 1) != 0 )))
x1 -= fabsy;
}
if( x < 0 )
x1 = -x1;
return x1;
}
| {
"pile_set_name": "Github"
} |
const initialFieldState = {
focus: false,
pending: false,
pristine: true,
submitted: false,
submitFailed: false,
retouched: false,
touched: false,
valid: true,
validating: false,
validated: false,
validity: {},
errors: {},
intents: [],
};
export default initialFieldState;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.gis.geoprotocol.json
import jetbrains.datalore.base.json.*
import jetbrains.datalore.base.spatial.GeoRectangle
import jetbrains.datalore.base.typedGeometry.Generic
import jetbrains.datalore.base.typedGeometry.Vec
import jetbrains.gis.geoprotocol.Boundaries
import jetbrains.gis.geoprotocol.Boundary
import jetbrains.gis.geoprotocol.Fragment
import jetbrains.gis.geoprotocol.GeoResponse
import jetbrains.gis.geoprotocol.GeoResponse.*
import jetbrains.gis.geoprotocol.json.ResponseKeys.BOUNDARY
import jetbrains.gis.geoprotocol.json.ResponseKeys.CENTROID
import jetbrains.gis.geoprotocol.json.ResponseKeys.DATA
import jetbrains.gis.geoprotocol.json.ResponseKeys.FEATURES
import jetbrains.gis.geoprotocol.json.ResponseKeys.FRAGMENTS
import jetbrains.gis.geoprotocol.json.ResponseKeys.HIGHLIGHTS
import jetbrains.gis.geoprotocol.json.ResponseKeys.ID
import jetbrains.gis.geoprotocol.json.ResponseKeys.LAT
import jetbrains.gis.geoprotocol.json.ResponseKeys.LEVEL
import jetbrains.gis.geoprotocol.json.ResponseKeys.LIMIT
import jetbrains.gis.geoprotocol.json.ResponseKeys.LON
import jetbrains.gis.geoprotocol.json.ResponseKeys.MESSAGE
import jetbrains.gis.geoprotocol.json.ResponseKeys.NAME
import jetbrains.gis.geoprotocol.json.ResponseKeys.NAMESAKE_COUNT
import jetbrains.gis.geoprotocol.json.ResponseKeys.NAMESAKE_EXAMPLES
import jetbrains.gis.geoprotocol.json.ResponseKeys.NAMESAKE_NAME
import jetbrains.gis.geoprotocol.json.ResponseKeys.NAMESAKE_PARENTS
import jetbrains.gis.geoprotocol.json.ResponseKeys.POSITION
import jetbrains.gis.geoprotocol.json.ResponseKeys.QUERY
import jetbrains.gis.geoprotocol.json.ResponseKeys.STATUS
object ResponseJsonFormatter {
fun format(response: GeoResponse): Obj {
if (response is SuccessGeoResponse) {
return success(response)
}
if (response is AmbiguousGeoResponse) {
return ambiguous(response)
}
return if (response is ErrorGeoResponse) {
error(response)
} else error(ErrorGeoResponse("Unknown response: " + response::class.toString()))
}
private fun success(response: SuccessGeoResponse): Obj {
return FluentObject()
.put(STATUS, ResponseStatus.SUCCESS)
.put(MESSAGE, "OK")
.put(DATA,
FluentObject()
.put(LEVEL, response.featureLevel)
.put(FEATURES, FluentArray()
.addAll(response.features.map { feature ->
FluentObject()
.put(QUERY, feature.request)
.put(ID, feature.id)
.put(NAME, feature.name)
.putRemovable(HIGHLIGHTS, stringArray(feature.highlights))
.putRemovable(LIMIT, formatRect(feature.limit))
.putRemovable(POSITION, formatRect(feature.position))
.putRemovable(CENTROID, formatPoint(feature.centroid))
.putRemovable(BOUNDARY, formatGeometry(feature.boundary))
.putRemovable(FRAGMENTS, formatFragments(feature.fragments))
})
)
)
.get()
}
private fun error(response: ErrorGeoResponse): Obj {
return FluentObject()
.put(STATUS, ResponseStatus.ERROR)
.put(MESSAGE, response.message)
.get()
}
private fun ambiguous(response: AmbiguousGeoResponse): Obj {
return FluentObject()
.put(STATUS, ResponseStatus.AMBIGUOUS)
.put(MESSAGE, "Ambiguous")
.put(DATA, FluentObject()
.put(LEVEL, response.featureLevel)
.put(FEATURES, FluentArray()
.addAll(response.features.map { feature ->
FluentObject()
.put(QUERY, feature.request)
.put(NAMESAKE_COUNT, feature.namesakeCount)
.put(NAMESAKE_EXAMPLES, FluentArray()
.addAll(feature.namesakes.map { namesake ->
FluentObject()
.put(NAMESAKE_NAME, namesake.name)
.put(NAMESAKE_PARENTS, FluentArray()
.addAll(namesake.parents.map { parent ->
FluentObject()
.put(NAMESAKE_NAME, parent.name)
.put(LEVEL, parent.level)
})
)
})
)
})
)
).get()
}
private fun stringArray(v: List<String>?): FluentArray? {
return if (v == null || v.isEmpty()) null else FluentArray(v)
}
private fun formatRect(v: GeoRectangle?): FluentObject? {
return when (v) {
null -> null
else -> ProtocolJsonHelper.formatGeoRectangle(v)
}
}
private fun formatPoint(v: Vec<Generic>?): FluentValue? {
return v?.let { FluentObject()
.put(LON, it.x)
.put(LAT, it.y)
}
}
private fun formatGeometry(boundary: Boundary<Generic>?): FluentPrimitive? {
return boundary?.let { FluentPrimitive(boundaryToString(it)) }
}
private fun boundaryToString(boundary: Boundary<Generic>): String {
return Boundaries.getRawData(boundary)
}
private fun formatFragments(fragments: List<Fragment>?): FluentObject? {
return fragments?.let {
val obj = FluentObject()
for (fragment in fragments) {
val boundaries = FluentArray()
for (boundary in fragment.boundaries) {
boundaries.add(boundaryToString(boundary))
}
obj.put(fragment.key.key, boundaries)
}
return obj
}
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: e6ee1422834e7c24ca13f09a1eea892a
NativeFormatImporter:
userData:
| {
"pile_set_name": "Github"
} |
package de.fhg.iais.roberta.visitor.validate;
import de.fhg.iais.roberta.components.Configuration;
public final class NxtBrickValidatorVisitor extends AbstractBrickValidatorVisitor {
public NxtBrickValidatorVisitor(Configuration brickConfiguration) {
super(brickConfiguration);
}
}
| {
"pile_set_name": "Github"
} |

# PLAY IT HERE: [http://ncase.me/crowds/](http://ncase.me/crowds/)
*The Wisdom and/or Madness of Crowds* is dedicated to the public domain,
and was possible thanks to these open source/Creative Commons resources:
**Music:** ["Friends 2018" and "Friends 2068"](http://freemusicarchive.org/music/Komiku/Tale_on_the_Late/) by Komiku (CC Zero)
**Free Sound Effects:**
* [Pencil Scratching](https://freesound.org/people/JasonElrod/sounds/85485/) by JasonElrod (CC BY)
* [Long Confetti](https://freesound.org/people/dmjames/sounds/140095/) by dmjames (CC Zero)
* [Short Confetti](https://freesound.org/people/beerre/sounds/344965/) by beerre (CC Zero)
* [Various button sounds](https://freesound.org/people/Owdeo/sounds/116653/) by Owdeo (CC BY-NC)
* [Contagion spreading](https://freesound.org/people/UnderlinedDesigns/sounds/191766/) by UnderlinedDesigns (CC Zero)
* [Cut connection](https://freesound.org/people/megashroom/sounds/390167/) by megashroom (CC Zero)
* [Can't cut connection](https://freesound.org/people/johnnypanic/sounds/36280/) by johnnypanic (CC BY)
* [Ending Windchimes](https://freesound.org/people/InspectorJ/sounds/353194/) by InspectorJ (CC BY)
* [Sandbox: Add Peep](https://freesound.org/people/greenvwbeetle/sounds/244654/) by greenvwbeetle (CC Zero)
* [Sandbox: Move Peep](https://freesound.org/people/ermfilm/sounds/130013/) by ermfilm (CC BY)
* [Sandbox: Delete Peep](https://freesound.org/people/Bash360/sounds/214854/) by Bash360 (CC Zero)
* [Sandbox: Clear All](https://freesound.org/people/dogfishkid/sounds/399303/) by dogfishkid (CC BY)
**Open Source Libraries:**
* [Howler.js](https://howlerjs.com/) for the audio
* [MinPubSub](https://github.com/daniellmb/MinPubSub) for publish/subscribe
* [iNoBounce](https://github.com/lazd/iNoBounce/) for making iOS stop acting like a such a jerk
**Font:** [Patrick Hand](https://fonts.google.com/specimen/Patrick+Hand) by Patrick Wagesreiter
# HOW TO TRANSLATE THIS THING
**[IMPORTANT:
BEFORE YOU MAKE A TRANSLATION, CHECK THE "ISSUES" TAB ABOVE,
TO SEE IF SOMEONE ELSE IS ALREADY WORKING ON IT.
If so, maybe you can collaborate!
And if no one else is, PLEASE CREATE A NEW ISSUE in this repo
so that others know you're working on it!]**
**Translations done so far:**
[Deutsch](http://ncase.me/crowds/de.html)
[Português](http://ncase.me/crowds/pt.html)
[Italiano](http://ncase.me/crowds/it.html)
[Français](http://ncase.me/crowds/fr.html)
[Español (Castellano)](http://ncase.me/crowds/es.html)
[Русский](http://ncase.me/crowds/ru.html)
[Українська](http://ncase.me/crowds/uk.html)
[Vietnamese](http://ncase.me/crowds/vi.html)
[简体中文](http://ncase.me/crowds/zh-CN.html)
[繁體中文](http://ncase.me/crowds/zh-TW.html)
[日本語](http://ncase.me/crowds/ja.html)
[Español (Mexicano)](http://ncase.me/crowds/es-MX.html)
[Čeština](http://ncase.me/crowds/cs.html)
[Nederlands](http://ncase.me/crowds/nl.html)
**Step 1)** Clone this repo!
**Step 2)** Look up the two-letter code of the language you're translating to here:
[https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
**Step 3)** *COPY* `index.html`, and name the copy [your-two-letter-code].html.
For example: `de.html`, `ar.html`, `zh.html`, etc...
**Step 4)** Translate *THAT* page (it's about 3600+ words). Do NOT modify the original `index.html`!
Also, please feel free to credit yourself as a translator :)
**Step 5)** Add one line to the end of `translations.txt` so that the game "knows" your translation exists.
(more specific instructions will be inside that file)
**Step 6)** Send a **Pull Request** so I can make your translation go live!
**Step 7)** 🎉 fweeeee
# PUBLIC DOMAIN "LICENSE"
[Creative Commons Zero](https://github.com/ncase/trust/blob/gh-pages/LICENSE): it's a public domain dedication, so basically, do whatever you want! Attribution is super appreciated, but I'm not gonna send legal goons after you or anything.
| {
"pile_set_name": "Github"
} |
#include "tommath.h"
#ifdef BN_MP_ABS_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis
*
* LibTomMath is a library that provides multiple-precision
* integer arithmetic as well as number theoretic functionality.
*
* The library was designed directly after the MPI library by
* Michael Fromberger but has been written from scratch with
* additional optimizations in place.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, [email protected], http://libtom.org
*/
/* b = |a|
*
* Simple function copies the input and fixes the sign to positive
*/
int
mp_abs (mp_int * a, mp_int * b)
{
int res;
/* copy a to b */
if (a != b) {
if ((res = mp_copy (a, b)) != MP_OKAY) {
return res;
}
}
/* force the sign of b to positive */
b->sign = MP_ZPOS;
return MP_OKAY;
}
#endif
/* $Source: /cvs/libtom/libtommath/bn_mp_abs.c,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2006/12/28 01:25:13 $ */
| {
"pile_set_name": "Github"
} |
//
// Prefix header for all source files of the 'HelloWorld' target in the 'HelloWorld' project
//
#import <Availability.h>
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iOS SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
| {
"pile_set_name": "Github"
} |
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
],
"stopSpecOnExpectationFailure": false,
"random": true
}
| {
"pile_set_name": "Github"
} |
/*!
* jQuery UI CSS Framework 1.8.19
*
* Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Theming/API
*/
/* Layout helpers
----------------------------------*/
.ui-helper-hidden { display: none; }
.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; }
.ui-helper-clearfix:after { clear: both; }
.ui-helper-clearfix { zoom: 1; }
.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
/* Interaction Cues
----------------------------------*/
.ui-state-disabled { cursor: default !important; }
/* Icons
----------------------------------*/
/* states and images */
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
/* Misc visuals
----------------------------------*/
/* Overlays */
.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>Api Documentation</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap.min.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/prettify.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap-responsive.min.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/application.css'/>
<!-- IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div id='container'>
<ul class='breadcrumb'>
<li>
<a href='../../../apidoc/v2.nl_NL.html'>Foreman v2</a>
<span class='divider'>/</span>
</li>
<li>
<a href='../../../apidoc/v2/provisioning_templates.nl_NL.html'>
Provisioning templates
</a>
<span class='divider'>/</span>
</li>
<li class='active'>destroy</li>
<li class='pull-right'>
[ <a href="../../../apidoc/v2/provisioning_templates/destroy.ca.html">ca</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.cs_CZ.html">cs_CZ</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.de.html">de</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.en.html">en</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.en_GB.html">en_GB</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.es.html">es</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.fr.html">fr</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.gl.html">gl</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.it.html">it</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.ja.html">ja</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.ko.html">ko</a> | <b><a href="../../../apidoc/v2/provisioning_templates/destroy.nl_NL.html">nl_NL</a></b> | <a href="../../../apidoc/v2/provisioning_templates/destroy.pl.html">pl</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.pt_BR.html">pt_BR</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.ru.html">ru</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.sv_SE.html">sv_SE</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.zh_CN.html">zh_CN</a> | <a href="../../../apidoc/v2/provisioning_templates/destroy.zh_TW.html">zh_TW</a> ]
</li>
</ul>
<div class='page-header'>
<h1>
DELETE /api/provisioning_templates/:id
<br>
<small>Verwijder een uitroltemplate</small>
</h1>
</div>
<div>
<h2><span class="translation_missing" title="translation missing: nl-NL.apipie.examples">Examples</span></h2>
<pre class="prettyprint">DELETE /api/provisioning_templates/1007981701-centos5_3_pxelinux
{
"provisioning_template": {}
}
422
{
"error": {
"id": 1007981701,
"errors": {
"base": [
"centos5_3_pxelinux is used by Redhat 6.1 - ",
"centos5_3_pxelinux is used by Ubuntu 10.10 - "
]
},
"full_messages": [
"centos5_3_pxelinux is used by Redhat 6.1 - ",
"centos5_3_pxelinux is used by Ubuntu 10.10 - "
]
}
}</pre>
<h2><span class="translation_missing" title="translation missing: nl-NL.apipie.params">Params</span></h2>
<table class='table'>
<thead>
<tr>
<th><span class="translation_missing" title="translation missing: nl-NL.apipie.param_name">Param Name</span></th>
<th><span class="translation_missing" title="translation missing: nl-NL.apipie.description">Description</span></th>
</tr>
</thead>
<tbody>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>location_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: nl-NL.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Set the current location context for the request</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>organization_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: nl-NL.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Set the current organization context for the request</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>id </strong><br>
<small>
<span class="translation_missing" title="translation missing: nl-NL.apipie.required">Required</span>
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an identifier, string from 1 to 128 characters containing only alphanumeric characters, space, underscore(_), hypen(-) with no leading or trailing space.</p>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<hr>
<footer></footer>
</div>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/jquery.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/bootstrap-collapse.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/prettify.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/apipie.js'></script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.thoughtcrime.ssl.pinning"
android:versionCode="1"
android:versionName="1.0.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
</manifest>
| {
"pile_set_name": "Github"
} |
package edu.stanford.bmir.protege.web.server.index;
import edu.stanford.bmir.protege.web.server.change.OntologyChange;
import javax.annotation.Nonnull;
import java.util.List;
/**
* Matthew Horridge
* Stanford Center for Biomedical Informatics Research
* 2019-09-10
*/
public interface RootIndex {
/**
* Minimizes and filters the specified list of changes to changes that actually
* result in mutation of project ontologies.
* @param changes The list of desired changes.
* @return A list of changes that will have an effect on project ontologies.
*/
@Nonnull
List<OntologyChange> getEffectiveChanges(@Nonnull List<OntologyChange> changes);
}
| {
"pile_set_name": "Github"
} |
package redis_test
import (
"net"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"gopkg.in/redis.v3"
)
var _ = Describe("newConnDialer with bad connection", func() {
It("should return an error", func() {
dialer := redis.NewConnDialer(&redis.Options{
Dialer: func() (net.Conn, error) {
return &badConn{}, nil
},
MaxRetries: 3,
Password: "password",
DB: 1,
})
_, err := dialer()
Expect(err).To(MatchError("bad connection"))
})
})
| {
"pile_set_name": "Github"
} |
Good morning
| {
"pile_set_name": "Github"
} |
/*
Copyright 2013 Google Inc. All Rights Reserved.
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.
*/
'use strict';
/**
* @fileoverview Handle search box for TSView landing page. Depends on jQuery.
*/
(function() {
var autocompleteCache = {};
$(document).ready(function() {
$('#search-input-box').autocomplete(
{source: function(request, response) {
var term = request.term;
if (term in autocompleteCache) {
response(autocompleteCache[term]);
return;
}
$.getJSON('dir/v1/' + term + '*',
function(data, status, xhr) {
autocompleteCache[term] = data.names;
response(data.names);
});
},
delay: 100, // In millis.
select: function(event, ui) {
$('#search-input-box').val(ui.item.value);
$('#search-form').submit();
}
});
$('#search-input-box').focus();
$('#search-input-box').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
var searchValue = $.trim($('#search-input-box').val());
if ((searchValue.charAt(0) == '+') && (searchValue.length > 2)) {
var srcArray = searchValue.substr(1).split(',');
for (var i = 0; i < srcArray.length; i++) {
srcArray[i] = encodeURIComponent($.trim(srcArray[i]));
}
var srcComponent = srcArray.join('&src=');
var locationToLoad = '//' + window.location.host + '/v#src=' +
srcComponent + '&last_pts=15&visibility=1';
window.location.href = locationToLoad;
return;
}
$('#spinner').show();
$('#search-form').submit();
}
});
});
})();
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='UTF-8'?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gu</groupId>
<artifactId>management-internal_2.9.2</artifactId>
<packaging>jar</packaging>
<description>management-internal</description>
<version>5.26</version>
<name>management-internal</name>
<organization>
<name>com.gu</name>
</organization>
<dependencies>
<dependency>
<groupId>com.gu</groupId>
<artifactId>management_2.9.2</artifactId>
<version>5.26</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.specs2</groupId>
<artifactId>specs2_2.9.2</artifactId>
<version>1.12.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.scala-incubator.io</groupId>
<artifactId>scala-io-file_2.9.2</artifactId>
<version>0.4.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>SonatypeOSSReleases</id>
<name>Sonatype OSS Releases</name>
<url>https://oss.sonatype.org/content/repositories/releases/</url>
<layout>default</layout>
</repository>
</repositories>
</project> | {
"pile_set_name": "Github"
} |
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="PBIWebApp.SiteMaster" %>
<!DOCTYPE html>
<title>Power BI - Web sample</title>
<html lang="en">
<body>
<form runat="server">
<div>
<asp:ContentPlaceHolder ID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/master.css" type="text/css" />
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
| {
"pile_set_name": "Github"
} |
const path = require('path');
const express = require('express');
const fs = require('fs-extra');
const handler = require('serve-handler');
const partition = require('lodash/partition');
const { blue, bold, underline, yellow, red } = require('chalk');
const didYouMean = require('didyoumean2').default;
const {
port,
paths,
initialPath,
routes,
sites,
useDevServerMiddleware,
httpsDevServer,
} = require('../context');
const { checkHosts, getAppHosts } = require('../lib/hosts');
const allocatePort = require('../lib/allocatePort');
const openBrowser = require('../lib/openBrowser');
const getSiteForHost = require('../lib/getSiteForHost');
const resolveEnvironment = require('../lib/resolveEnvironment');
const args = require('../config/args');
const track = require('../telemetry');
const createServer = require('../lib/createServer');
const prefferedSite = args.site;
(async () => {
track.count('serve');
const targetFolderExists = fs.existsSync(paths.target);
if (!targetFolderExists) {
console.log(
red(
`${bold('sku build')} must be run before running ${bold('sku serve')}`,
),
);
process.exit(1);
}
const availableSites = sites.map(({ name }) => name);
if (prefferedSite && !availableSites.some((site) => prefferedSite === site)) {
console.log(red(`Unknown site '${bold(prefferedSite)}'`));
const suggestedSite = didYouMean(prefferedSite, availableSites);
if (suggestedSite) {
console.log(`Did you mean '${bold(suggestedSite)}'?`);
}
process.exit(1);
}
if (
paths.publicPath.startsWith('http') ||
paths.publicPath.startsWith('//')
) {
console.log(
red('sku serve not supported when publicPath is on a separate domain.'),
);
process.exit(1);
}
await checkHosts();
const appHosts = getAppHosts();
const availablePort = await allocatePort({
port: args.port || port.client,
host: '0.0.0.0',
});
console.log(blue(`sku serve`));
const environment = resolveEnvironment();
const [invalidRoutes, validRoutes] = partition(
routes,
({ route }) => route.indexOf(':') > -1,
);
if (invalidRoutes.length > 0) {
console.log(yellow(`Invalid dynamic routes:\n`));
invalidRoutes.forEach(({ route }) => {
console.log(yellow(underline(route)));
});
console.log(
yellow(
`\n${bold(
'sku serve',
)} doesn't support dynamic routes using ':' style syntax.\nPlease upgrade your routes to use '$' instead.`,
),
);
}
const app = express();
if (useDevServerMiddleware) {
const devServerMiddleware = require(paths.devServerMiddleware);
if (devServerMiddleware && typeof devServerMiddleware === 'function') {
devServerMiddleware(app);
}
}
app.use((request, response) => {
const [hostname] = request.headers.host.split(':');
const site = getSiteForHost(hostname, prefferedSite) || '';
const rewrites = validRoutes.map(({ route }) => {
const normalisedRoute = route
.split('/')
.map((part) => {
if (part.startsWith('$')) {
// Path is dynamic, map part to * match
return '*';
}
return part;
})
.join('/');
return {
source: normalisedRoute,
destination: path.join(environment, site, route, 'index.html'),
};
});
if (paths.publicPath !== '/') {
rewrites.push({
source: path.join(paths.publicPath, ':asset+.:extension'),
destination: '/:asset.:extension',
});
}
return handler(request, response, {
rewrites,
public: paths.relativeTarget,
directoryListing: false,
headers: [
{
source: '**/*.*',
headers: [
{
key: 'Access-Control-Allow-Origin',
value: '*',
},
],
},
],
});
});
const server = await createServer(app);
app.on('error', console.error);
server.listen(availablePort, () => {
const proto = httpsDevServer ? 'https' : 'http';
const url = `${proto}://${appHosts[0]}:${availablePort}${initialPath}`;
console.log();
const sitesWithHosts = sites.filter((site) => site.host);
if (sitesWithHosts.length > 0) {
sitesWithHosts.forEach((site) => {
const siteUrl = `${proto}://${site.host}:${availablePort}${initialPath}`;
console.log(
blue(`${bold(site.name)} site available at ${underline(siteUrl)}`),
);
});
} else {
console.log(blue(`Started server on ${underline(url)}`));
}
console.log();
openBrowser(url);
});
})();
| {
"pile_set_name": "Github"
} |
class CreateActiveAdminComments < ActiveRecord::Migration
def self.up
create_table :active_admin_comments do |t|
t.string :namespace
t.text :body
t.string :resource_id, null: false, limit: 50
t.string :resource_type, null: false, limit: 50
t.references :author, polymorphic: true
t.timestamps
end
add_index :active_admin_comments, [:namespace]
add_index :active_admin_comments, [:author_type, :author_id]
add_index :active_admin_comments, [:resource_type, :resource_id]
end
def self.down
drop_table :active_admin_comments
end
end
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import "IPropertyScrollViewController.h"
#import "NSTextViewDelegate-Protocol.h"
@class NSString;
@interface TPropertyTextViewController : IPropertyScrollViewController <NSTextViewDelegate>
{
unsigned long long _maxChars;
}
@property(nonatomic) unsigned long long maxChars; // @synthesize maxChars=_maxChars;
- (void)textDidEndEditing:(id)arg1;
- (void)nodesWillChange;
- (int)applyValueToNodes:(id)arg1;
- (void)flush;
- (BOOL)textView:(id)arg1 shouldChangeTextInRange:(struct _NSRange)arg2 replacementString:(id)arg3;
- (void)setSubview:(id)arg1;
- (void)aboutToTearDown;
- (void)initCommon;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| {
"pile_set_name": "Github"
} |
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB::Client
include Msf::Auxiliary::Dos
def initialize(info = {})
super(update_info(info,
'Name' => 'Samba lsa_io_privilege_set Heap Overflow',
'Description' => %q{
This module triggers a heap overflow in the LSA RPC service
of the Samba daemon.
},
'Author' => [ 'hdm' ],
'License' => MSF_LICENSE,
'References' =>
[
['CVE', '2007-2446'],
['OSVDB', '34699'],
]
))
register_options(
[
OptString.new('SMBPIPE', [ true, "The pipe name to use", 'LSARPC']),
])
end
def run
pipe = datastore['SMBPIPE'].downcase
print_status("Connecting to the SMB service...")
connect()
smb_login()
datastore['DCERPC::fake_bind_multi'] = false
handle = dcerpc_handle('12345778-1234-abcd-ef00-0123456789ab', '0.0', 'ncacn_np', ["\\#{pipe}"])
print_status("Binding to #{handle} ...")
dcerpc_bind(handle)
print_status("Bound to #{handle} ...")
# Linux: Needs heap magic to work around glibc (or TALLOC mode for 3.0.20+)
# Mac OS X: PC control via memcpy to stack ptr
# Solaris: PC control via memcpy to stack ptr
stub = lsa_open_policy(dcerpc)
stub << NDR.long(1)
stub << NDR.long(0xffffffff)
stub << NDR.long(0x100)
stub << "X" * 0x100
print_status("Calling the vulnerable function...")
begin
# LsarAddPrivilegesToAccount
dcerpc.call(0x13, stub)
rescue Rex::Proto::DCERPC::Exceptions::NoResponse
print_good('Server did not respond, this is expected')
rescue => e
if e.to_s =~ /STATUS_PIPE_DISCONNECTED/
print_good('Server disconnected, this is expected')
else
raise e
end
end
disconnect
end
end
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl -w
BEGIN {
use FindBin;
push @INC, $FindBin::Bin. "/../ext/";
};
use utf8;
use strict;
# The Init
my $static_list_index_length = 199;
my $MAX_LEN_UNIT_NAME = 0;
my $COUNT_UNITS = 0;
my $ENUM_NAME = "mycss_units_type";
my $ENUM_PREFIX = "MyCSS_UNIT_TYPE_";
my $INDEX_NAME = "mycss_units_index_name";
my $STATIC_NAME = "mycss_units_index_static_for_search";
my $DEFINE_INDEX_LEN_NAME = "MyCSS_UNITS_STATIC_INDEX_FOR_SEARCH_SIZE";
# The Code
my $units = load_units("data/units.txt");
print_units_enum_and_periods($units);
#print_units_index($units);
#print_ubnit_index_entries_count();
my $result = create_result($units, $static_list_index_length);
#test_result($units);
#my $static_list = create_static_list_index($result);
#print $static_list, "\n";
sub create_result {
my ($units, $index_length) = @_;
my $result = {};
foreach my $prefix (keys %$units) {
foreach my $unit (@{$units->{$prefix}}) {
my $id = get_index_id($unit, $index_length);
push @{$result->{$id}}, [$unit, length($unit), $prefix];
$MAX_LEN_UNIT_NAME = length($unit) if $MAX_LEN_UNIT_NAME < length($unit);
$COUNT_UNITS++;
}
}
$result;
}
sub test_result {
my ($units) = @_;
my $op = [0, undef];
foreach my $idx (1..1024) {
my $result = create_result($units, $idx);
my $res_max = test_result_max_value($result, 0);
if(!defined($op->[1]) || $op->[1] > $res_max) {
$op->[0] = $idx;
$op->[1] = $res_max;
}
}
print "Best:\n";
print $op->[0], ": ", $op->[1], "\n";
}
sub test_result_max_value {
my ($res, $is_print) = @_;
my $max = 0;
foreach my $id (sort {scalar(@{$res->{$a}}) <=> scalar(@{$res->{$b}})} keys %$res) {
print "$id: ", scalar(@{$res->{$id}}), "\n" if $is_print;
$max = scalar(@{$res->{$id}}) if $max < scalar(@{$res->{$id}});
}
$max;
}
sub get_index_id {
use bytes;
my @chars = split //, $_[0];
my $f = ord(lc($chars[0]));
my $l = ord(lc($chars[-1]));
((($f * $l * scalar(@chars))) % $_[1]) + 1;
}
sub create_sub_static_list_index {
my ($result, $struct, $offset) = @_;
my @list_sorted = sort {$a->[1] <=> $b->[1]} @$result[0..$#$result];
foreach my $i (1..$#list_sorted) {
my $cur = $offset;
$offset++;
push @$struct, "\t{".
'"'. $list_sorted[$i]->[0] .'", '. $list_sorted[$i]->[1] .', '.
name_to_enum($list_sorted[$i]->[2]). "_" . uc($list_sorted[$i]->[0]), ', '.
($i < $#list_sorted ? $offset : 0) .", $cur},\n";
}
$offset;
}
sub create_static_list_index {
my ($result) = @_;
my @res;
my $struct = [];
my $offset = $static_list_index_length + 1;
foreach my $i (0..$static_list_index_length)
{
if(exists $result->{$i}) {
my $id = 0;
if(scalar @{$result->{$i}} > 1) {
$offset = create_sub_static_list_index($result->{$i}, $struct, $offset);
$id = $offset - (@{$result->{$i}} - 1);
}
my @list_sorted = sort {$a->[1] <=> $b->[1]} @{$result->{$i}}[0..$#{$result->{$i}}];
push @res, "\t{".
'"'. $list_sorted[0]->[0] .'", '. $list_sorted[0]->[1] .', '.
name_to_enum(uc($list_sorted[0]->[0])), ', '.
"$id, $i},\n";
}
else {
push @res, "\t{NULL, 0, MyCSS_UNIT_TYPE_UNDEF, 0, 0},\n";
}
}
"static const mycss_units_index_static_entry_t $STATIC_NAME\[] = \n{\n". join("", @res, @$struct) ."};\n"
}
sub print_units_enum_and_periods {
my ($units) = @_;
my $idx = 1;
my $periods = {};
print "enum $ENUM_NAME {\n";
print "\t", name_to_enum("undef"), " = 0x00,\n";
foreach my $prefix (sort {$a cmp $b} keys %$units)
{
if ($prefix =~ /^length/) {
$periods->{length}->{min} = $idx unless exists $periods->{length};
}
$periods->{$prefix}->{min} = $idx;
foreach my $unit (sort {$a cmp $b} @{$units->{$prefix}}) {
print "\t", name_to_enum($unit), " = ", sprintf("0x%02x", $idx++), ",\n";
}
if ($prefix =~ /^length/) {
$periods->{length}->{max} = ($idx - 1);
}
$periods->{$prefix}->{max} = ($idx - 1);
}
print "\t", name_to_enum("last_entry"), " = ", sprintf("0x%02x", ++$idx), ",\n";
print "}\ntypedef $ENUM_NAME\_t;\n\n";
foreach my $prefix (sort {$a cmp $b} keys %$periods) {
my $strict_name = $prefix;
$strict_name =~ s/-/_/g;
print "#define mycss_units_is_$strict_name\_type(type) (type >= ", $periods->{$prefix}->{min}, " && type <= ", $periods->{$prefix}->{max}, ")\n";
}
}
sub print_units_index {
my ($units) = @_;
my $idx = 0;
print "static const char * $INDEX_NAME\[", ($COUNT_UNITS + 2) ,"] = {\n";
print '"", ';
foreach my $prefix (sort {$a cmp $b} keys %$units)
{
foreach my $unit (sort {$a cmp $b} @{$units->{$prefix}}) {
print qq~"$unit", ~;
print "\n" unless ++$idx % 10;
}
}
print "NULL,\n";
print "}\n";
}
sub print_ubnit_index_entries_count {
print "#define $DEFINE_INDEX_LEN_NAME ", $static_list_index_length, "\n";
}
sub name_to_enum {
my ($name) = @_;
$name =~ s/[-]+/_/g;
$name = $ENUM_PREFIX. uc($name);
$name;
}
sub load_units {
my ($filename) = @_;
my $res = {};
open my $fh, "<", $filename or die "Can't load $filename: $!";
binmode $fh, ":utf8";
while (my $line = <$fh>) {
$line =~ s/^\s+//;
$line =~ s/\s+$//;
my ($key, $val) = split /\s*:\s*/, $line, 2;
$res->{$key} = [split /\s*,\s*/, $val];
}
close $fh;
$res;
}
| {
"pile_set_name": "Github"
} |
package com.central.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author zlt
* 密码工具类
*/
public class DefaultPasswordConfig {
/**
* 装配BCryptPasswordEncoder用户密码的匹配
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
| {
"pile_set_name": "Github"
} |
---
aliases: ["/engine/misc/deprecated/"]
description: "Deprecated Features."
keywords: "docker, documentation, about, technology, deprecate"
---
<!-- This file is maintained within the docker/cli GitHub
repository at https://github.com/docker/cli/. Make all
pull requests against that repo. If you see this file in
another repository, consider it read-only there, as it will
periodically be overwritten by the definitive file. Pull
requests which include edits to this file in other repositories
will be rejected.
-->
# Deprecated Engine Features
The following list of features are deprecated in Engine.
To learn more about Docker Engine's deprecation policy,
see [Feature Deprecation Policy](https://docs.docker.com/engine/#feature-deprecation-policy).
### Reserved namespaces in engine labels
**Deprecated in Release: v18.06.0**
The namespaces `com.docker.*`, `io.docker.*`, and `org.dockerproject.*` in engine labels
were always documented to be reserved, but there was never any enforcement.
Usage of these namespaces will now cause a warning in the engine logs to discourage their
use, and will error instead in 18.12 and above.
### Asynchronous `service create` and `service update`
**Deprecated In Release: v17.05.0**
**Disabled by default in release: [v17.10](https://github.com/docker/docker-ce/releases/tag/v17.10.0-ce)**
Docker 17.05.0 added an optional `--detach=false` option to make the
`docker service create` and `docker service update` work synchronously. This
option will be enabled by default in Docker 17.10, at which point the `--detach`
flag can be used to use the previous (asynchronous) behavior.
The default for this option will also be changed accordingly for `docker service rollback`
and `docker service scale` in Docker 17.10.
### `-g` and `--graph` flags on `dockerd`
**Deprecated In Release: v17.05.0**
The `-g` or `--graph` flag for the `dockerd` or `docker daemon` command was
used to indicate the directory in which to store persistent data and resource
configuration and has been replaced with the more descriptive `--data-root`
flag.
These flags were added before Docker 1.0, so will not be _removed_, only
_hidden_, to discourage their use.
### Top-level network properties in NetworkSettings
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
**Target For Removal In Release: v17.12**
When inspecting a container, `NetworkSettings` contains top-level information
about the default ("bridge") network;
`EndpointID`, `Gateway`, `GlobalIPv6Address`, `GlobalIPv6PrefixLen`, `IPAddress`,
`IPPrefixLen`, `IPv6Gateway`, and `MacAddress`.
These properties are deprecated in favor of per-network properties in
`NetworkSettings.Networks`. These properties were already "deprecated" in
docker 1.9, but kept around for backward compatibility.
Refer to [#17538](https://github.com/docker/docker/pull/17538) for further
information.
### `filter` param for `/images/json` endpoint
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
**Target For Removal In Release: v17.12**
The `filter` param to filter the list of image by reference (name or name:tag) is now implemented as a regular filter, named `reference`.
### `repository:shortid` image references
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
**Removed In Release: v17.12**
The `repository:shortid` syntax for referencing images is very little used,
collides with tag references, and can be confused with digest references.
Support for the `repository:shortid` notation to reference images was removed
in Docker 17.12.
### `docker daemon` subcommand
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
**Removed In Release: v17.12**
The daemon is moved to a separate binary (`dockerd`), and should be used instead.
### Duplicate keys with conflicting values in engine labels
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
**Removed In Release: v17.12**
When setting duplicate keys with conflicting values, an error will be produced, and the daemon
will fail to start.
### `MAINTAINER` in Dockerfile
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
`MAINTAINER` was an early very limited form of `LABEL` which should be used instead.
### API calls without a version
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
**Target For Removal In Release: v17.12**
API versions should be supplied to all API calls to ensure compatibility with
future Engine versions. Instead of just requesting, for example, the URL
`/containers/json`, you must now request `/v1.25/containers/json`.
### Backing filesystem without `d_type` support for overlay/overlay2
**Deprecated In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
**Removed In Release: v17.12**
The overlay and overlay2 storage driver does not work as expected if the backing
filesystem does not support `d_type`. For example, XFS does not support `d_type`
if it is formatted with the `ftype=0` option.
Starting with Docker 17.12, new installations will not support running overlay2 on
a backing filesystem without `d_type` support. For existing installations that upgrade
to 17.12, a warning will be printed.
Please also refer to [#27358](https://github.com/docker/docker/issues/27358) for
further information.
### Three arguments form in `docker import`
**Deprecated In Release: [v0.6.7](https://github.com/docker/docker/releases/tag/v0.6.7)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
The `docker import` command format `file|URL|- [REPOSITORY [TAG]]` is deprecated since November 2013. It's no more supported.
### `-h` shorthand for `--help`
**Deprecated In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
**Target For Removal In Release: v17.09**
The shorthand (`-h`) is less common than `--help` on Linux and cannot be used
on all subcommands (due to it conflicting with, e.g. `-h` / `--hostname` on
`docker create`). For this reason, the `-h` shorthand was not printed in the
"usage" output of subcommands, nor documented, and is now marked "deprecated".
### `-e` and `--email` flags on `docker login`
**Deprecated In Release: [v1.11.0](https://github.com/docker/docker/releases/tag/v1.11.0)**
**Removed In Release: [v17.06](https://github.com/docker/docker-ce/releases/tag/v17.06.0-ce)**
The docker login command is removing the ability to automatically register for an account with the target registry if the given username doesn't exist. Due to this change, the email flag is no longer required, and will be deprecated.
### Separator (`:`) of `--security-opt` flag on `docker run`
**Deprecated In Release: [v1.11.0](https://github.com/docker/docker/releases/tag/v1.11.0)**
**Target For Removal In Release: v17.06**
The flag `--security-opt` doesn't use the colon separator(`:`) anymore to divide keys and values, it uses the equal symbol(`=`) for consistency with other similar flags, like `--storage-opt`.
### `/containers/(id or name)/copy` endpoint
**Deprecated In Release: [v1.8.0](https://github.com/docker/docker/releases/tag/v1.8.0)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
The endpoint `/containers/(id or name)/copy` is deprecated in favor of `/containers/(id or name)/archive`.
### Ambiguous event fields in API
**Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
The fields `ID`, `Status` and `From` in the events API have been deprecated in favor of a more rich structure.
See the events API documentation for the new format.
### `-f` flag on `docker tag`
**Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
To make tagging consistent across the various `docker` commands, the `-f` flag on the `docker tag` command is deprecated. It is not longer necessary to specify `-f` to move a tag from one image to another. Nor will `docker` generate an error if the `-f` flag is missing and the specified tag is already in use.
### HostConfig at API container start
**Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
Passing an `HostConfig` to `POST /containers/{name}/start` is deprecated in favor of
defining it at container creation (`POST /containers/create`).
### `--before` and `--since` flags on `docker ps`
**Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
The `docker ps --before` and `docker ps --since` options are deprecated.
Use `docker ps --filter=before=...` and `docker ps --filter=since=...` instead.
### `--automated` and `--stars` flags on `docker search`
**Deprecated in Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
**Target For Removal In Release: v17.09**
The `docker search --automated` and `docker search --stars` options are deprecated.
Use `docker search --filter=is-automated=...` and `docker search --filter=stars=...` instead.
### Driver Specific Log Tags
**Deprecated In Release: [v1.9.0](https://github.com/docker/docker/releases/tag/v1.9.0)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
Log tags are now generated in a standard way across different logging drivers.
Because of which, the driver specific log tag options `syslog-tag`, `gelf-tag` and
`fluentd-tag` have been deprecated in favor of the generic `tag` option.
```bash
{% raw %}
docker --log-driver=syslog --log-opt tag="{{.ImageName}}/{{.Name}}/{{.ID}}"
{% endraw %}
```
### LXC built-in exec driver
**Deprecated In Release: [v1.8.0](https://github.com/docker/docker/releases/tag/v1.8.0)**
**Removed In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
The built-in LXC execution driver, the lxc-conf flag, and API fields have been removed.
### Old Command Line Options
**Deprecated In Release: [v1.8.0](https://github.com/docker/docker/releases/tag/v1.8.0)**
**Removed In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
The flags `-d` and `--daemon` are deprecated in favor of the `daemon` subcommand:
docker daemon -H ...
The following single-dash (`-opt`) variant of certain command line options
are deprecated and replaced with double-dash options (`--opt`):
docker attach -nostdin
docker attach -sig-proxy
docker build -no-cache
docker build -rm
docker commit -author
docker commit -run
docker events -since
docker history -notrunc
docker images -notrunc
docker inspect -format
docker ps -beforeId
docker ps -notrunc
docker ps -sinceId
docker rm -link
docker run -cidfile
docker run -dns
docker run -entrypoint
docker run -expose
docker run -link
docker run -lxc-conf
docker run -n
docker run -privileged
docker run -volumes-from
docker search -notrunc
docker search -stars
docker search -t
docker search -trusted
docker tag -force
The following double-dash options are deprecated and have no replacement:
docker run --cpuset
docker run --networking
docker ps --since-id
docker ps --before-id
docker search --trusted
**Deprecated In Release: [v1.5.0](https://github.com/docker/docker/releases/tag/v1.5.0)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
The single-dash (`-help`) was removed, in favor of the double-dash `--help`
docker -help
docker [COMMAND] -help
### `--run` flag on docker commit
**Deprecated In Release: [v0.10.0](https://github.com/docker/docker/releases/tag/v0.10.0)**
**Removed In Release: [v1.13.0](https://github.com/docker/docker/releases/tag/v1.13.0)**
The flag `--run` of the docker commit (and its short version `-run`) were deprecated in favor
of the `--changes` flag that allows to pass `Dockerfile` commands.
### Interacting with V1 registries
**Disabled By Default In Release: v17.06**
**Removed In Release: v17.12**
Version 1.8.3 added a flag (`--disable-legacy-registry=false`) which prevents the
docker daemon from `pull`, `push`, and `login` operations against v1
registries. Though enabled by default, this signals the intent to deprecate
the v1 protocol.
Support for the v1 protocol to the public registry was removed in 1.13. Any
mirror configurations using v1 should be updated to use a
[v2 registry mirror](https://docs.docker.com/registry/recipes/mirror/).
Starting with Docker 17.12, support for V1 registries has been removed, and the
`--disable-legacy-registry` flag can no longer be used, and `dockerd` will fail to
start when set.
### `--disable-legacy-registry` override daemon option
**Disabled In Release: v17.12**
**Target For Removal In Release: v18.03**
The `--disable-legacy-registry` flag was disabled in Docker 17.12 and will print
an error when used. For this error to be printed, the flag itself is still present,
but hidden. The flag will be removed in Docker 18.03.
### Docker Content Trust ENV passphrase variables name change
**Deprecated In Release: [v1.9.0](https://github.com/docker/docker/releases/tag/v1.9.0)**
**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
Since 1.9, Docker Content Trust Offline key has been renamed to Root key and the Tagging key has been renamed to Repository key. Due to this renaming, we're also changing the corresponding environment variables
- DOCKER_CONTENT_TRUST_OFFLINE_PASSPHRASE is now named DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE
- DOCKER_CONTENT_TRUST_TAGGING_PASSPHRASE is now named DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE
### `--api-enable-cors` flag on dockerd
**Deprecated In Release: [v1.6.0](https://github.com/docker/docker/releases/tag/v1.6.0)**
**Removed In Release: [v17.09](https://github.com/docker/docker-ce/releases/tag/v17.09.0-ce)**
The flag `--api-enable-cors` is deprecated since v1.6.0. Use the flag
`--api-cors-header` instead.
| {
"pile_set_name": "Github"
} |
.\" **************************************************************************
.\" * _ _ ____ _
.\" * Project ___| | | | _ \| |
.\" * / __| | | | |_) | |
.\" * | (__| |_| | _ <| |___
.\" * \___|\___/|_| \_\_____|
.\" *
.\" * Copyright (C) 1998 - 2017, Daniel Stenberg, <[email protected]>, et al.
.\" *
.\" * This software is licensed as described in the file COPYING, which
.\" * you should have received as part of this distribution. The terms
.\" * are also available at https://curl.haxx.se/docs/copyright.html.
.\" *
.\" * You may opt to use, copy, modify, merge, publish, distribute and/or sell
.\" * copies of the Software, and permit persons to whom the Software is
.\" * furnished to do so, under the terms of the COPYING file.
.\" *
.\" * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
.\" * KIND, either express or implied.
.\" *
.\" **************************************************************************
.\"
.TH CURLOPT_FAILONERROR 3 "May 30, 2017" "libcurl 7.58.0" "curl_easy_setopt options"
.SH NAME
CURLOPT_FAILONERROR \- request failure on HTTP response >= 400
.SH SYNOPSIS
#include <curl/curl.h>
CURLcode curl_easy_setopt(CURL *handle, CURLOPT_FAILONERROR, long fail);
.SH DESCRIPTION
A long parameter set to 1 tells the library to fail the request if the HTTP
code returned is equal to or larger than 400. The default action would be to
return the page normally, ignoring that code.
This method is not fail-safe and there are occasions where non-successful
response codes will slip through, especially when authentication is involved
(response codes 401 and 407).
You might get some amounts of headers transferred before this situation is
detected, like when a "100-continue" is received as a response to a POST/PUT
and a 401 or 407 is received immediately afterwards.
When this option is used and an error is detected, it will cause the
connection to get closed and \fICURLE_HTTP_RETURNED_ERROR\fP is returned.
.SH DEFAULT
0, do not fail on error
.SH PROTOCOLS
HTTP
.SH EXAMPLE
.nf
CURL *curl = curl_easy_init();
if(curl) {
CURLcode ret;
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
ret = curl_easy_perform(curl);
if(ret == CURLE_HTTP_RETURNED_ERROR) {
/* a HTTP response error problem */
}
}
.fi
.SH AVAILABILITY
Along with HTTP.
.SH RETURN VALUE
Returns CURLE_OK if HTTP is enabled, and CURLE_UNKNOWN_OPTION if not.
.SH "SEE ALSO"
.BR CURLOPT_HTTP200ALIASES "(3), " CURLOPT_KEEP_SENDING_ON_ERROR "(3), "
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2020 Microsoft Corporation
*
* Author: Alan Jowett
*
* This file is part of ocserv.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <config.h>
#include <unistd.h>
#include <cjose/cjose.h>
#include <jansson.h>
#include <string.h>
cjose_jwk_t *create_key(const char *kid)
{
cjose_err err;
cjose_jwk_t *key = cjose_jwk_create_EC_random(CJOSE_JWK_EC_P_256, &err);
if (!key) {
return NULL;
}
if (!cjose_jwk_set_kid(key, kid, strlen(kid), &err)) {
return NULL;
}
return key;
}
json_t *create_oidc_config(const char *openid_configuration_url,
const char *user_name_claim, const char *audience,
const char *issuer)
{
bool result = false;
json_t *config = json_object();
json_t *required_claims = json_object();
if (json_object_set_new
(config, "openid_configuration_url",
json_string(openid_configuration_url))) {
goto cleanup;
}
if (json_object_set_new
(config, "user_name_claim", json_string(user_name_claim))) {
goto cleanup;
}
if (json_object_set_new(required_claims, "aud", json_string(audience))) {
goto cleanup;
}
if (json_object_set_new(required_claims, "iss", json_string(issuer))) {
goto cleanup;
}
if (json_object_set_new(config, "required_claims", required_claims)) {
goto cleanup;
}
if (json_object_set_new(config, "minimum_jwk_refresh_time", json_integer(0))) {
goto cleanup;
}
required_claims = NULL;
result = true;
cleanup:
if (!result && config) {
json_decref(config);
config = NULL;
}
return config;
}
json_t *create_openid_configuration(char *key_url)
{
json_t *config = json_object();
if (json_object_set_new(config, "jwks_uri", json_string(key_url))) {
json_decref(config);
return NULL;
}
return config;
}
json_t *create_keys(cjose_jwk_t * key)
{
cjose_err err;
json_t *keys_json = json_object();
json_t *keys_array = json_array();
json_t *key_json;
const char *key_str = cjose_jwk_to_json(key, false, &err);
key_json = json_loads(key_str, 0, NULL);
json_array_append_new(keys_array, key_json);
json_object_set_new(keys_json, "keys", keys_array);
return keys_json;
}
json_t *create_header(const char *typ, const char *alg, const char *kid)
{
json_t *header_json = json_object();
if (typ) {
json_object_set_new(header_json, "typ", json_string(typ));
}
if (alg) {
json_object_set_new(header_json, "alg", json_string(alg));
}
if (kid) {
json_object_set_new(header_json, "kid", json_string(kid));
}
return header_json;
}
json_t *create_claims(const char *audience, const char *issuer,
json_int_t issued_at, json_int_t not_before,
json_int_t expires, const char *preferred_user_name)
{
json_t *claims_json = json_object();
if (audience) {
json_object_set_new(claims_json, "aud", json_string(audience));
}
if (issuer) {
json_object_set_new(claims_json, "iss", json_string(issuer));
}
if (issued_at) {
json_object_set_new(claims_json, "iat",
json_integer(issued_at));
}
if (not_before) {
json_object_set_new(claims_json, "nbf",
json_integer(not_before));
}
if (expires) {
json_object_set_new(claims_json, "exp", json_integer(expires));
}
if (preferred_user_name) {
json_object_set_new(claims_json, "preferred_username",
json_string(preferred_user_name));
}
return claims_json;
}
cjose_jws_t *create_jws(cjose_jwk_t * key, json_t * header, json_t * claims)
{
cjose_err err;
char *claims_str = json_dumps(claims, 0);
cjose_jws_t *jws =
cjose_jws_sign(key, header, (const uint8_t *)claims_str,
strlen(claims_str), &err);
free(claims_str);
return jws;
}
bool write_jws_to_file(cjose_jws_t * jws, const char *file)
{
cjose_err err;
const char *jws_str;
FILE *f = fopen(file, "w");
if (!cjose_jws_export(jws, &jws_str, &err)) {
fclose(f);
return false;
}
fprintf(f, "%s", jws_str);
fclose(f);
return true;
}
void generate_token(const char *output_folder, const char *token_name,
cjose_jwk_t * key, const char *typ, const char *alg,
const char *kid, const char *audience, const char *issuer,
const char *user_name, json_int_t issued_at,
json_int_t not_before, json_int_t expires)
{
char token_file[1024];
snprintf(token_file, sizeof(token_file), "%s/%s.token", output_folder,
token_name);
json_t *header = create_header(typ, alg, kid);
json_t *claims =
create_claims(audience, issuer, issued_at, not_before, expires,
user_name);
cjose_jws_t *jws = create_jws(key, header, claims);
write_jws_to_file(jws, token_file);
cjose_jws_release(jws);
json_decref(header);
json_decref(claims);
}
void generate_config_files(const char *output_folder, cjose_jwk_t * key,
const char *expected_audience,
const char *expected_issuer,
const char *user_name_claim)
{
char oidc_config_file[1024];
char openid_configuration_file[1024];
char keys_file[1024];
char openid_configuration_uri[1024];
char keys_uri[1024];
int retval;
retval =
snprintf(oidc_config_file, sizeof(oidc_config_file), "%s/oidc.json",
output_folder);
retval =
snprintf(openid_configuration_file,
sizeof(openid_configuration_file),
"%s/openid-configuration.json", output_folder);
if (retval < 0 || retval > sizeof(openid_configuration_file)) {
exit(1);
}
retval =
snprintf(keys_file, sizeof(keys_file), "%s/keys.json",
output_folder);
if (retval < 0 || retval > sizeof(openid_configuration_file)) {
exit(1);
}
retval =
snprintf(openid_configuration_uri, sizeof(openid_configuration_uri),
"file://localhost%s", openid_configuration_file);
if (retval < 0 || retval > sizeof(openid_configuration_file)) {
exit(1);
}
retval =
snprintf(keys_uri, sizeof(keys_uri), "file://localhost%s",
keys_file);
if (retval < 0 || retval > sizeof(openid_configuration_file)) {
exit(1);
}
json_t *oidc_config =
create_oidc_config(openid_configuration_uri, "preferred_username",
"SomeAudience", "SomeIssuer");
json_t *openid_configuration = create_openid_configuration(keys_uri);
json_t *keys = create_keys(key);
json_dump_file(oidc_config, oidc_config_file, 0);
json_dump_file(openid_configuration, openid_configuration_file, 0);
json_dump_file(keys, keys_file, 0);
json_decref(oidc_config);
json_decref(openid_configuration);
json_decref(keys);
}
int main(int argc, char **argv)
{
char working_directory[1024];
const char audience[] = "SomeAudience";
const char issuer[] = "SomeIssuer";
const char user_name_claim[] = "preferred_user_name";
char kid[64];
const char user_name[] = "SomeUser";
const char typ[] = "JWT";
const char alg[] = "ES256";
time_t now = time(NULL);
snprintf(kid, sizeof(kid), "key_%ld", now);
if (!getcwd(working_directory, sizeof(working_directory))) {
return 1;
}
strncat(working_directory, "/data", sizeof(working_directory)-1);
working_directory[sizeof(working_directory)-1] = 0;
cjose_jwk_t *key = create_key(kid);
generate_config_files(working_directory, key, audience, issuer,
user_name_claim);
generate_token(working_directory, "success_good", key, typ, alg, kid,
audience, issuer, user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_expired", key, typ, alg, kid,
audience, issuer, user_name, now - 7260, now - 7260,
now - 3600);
generate_token(working_directory, "fail_bad_typ", key, "FOO", alg, kid,
audience, issuer, user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_bad_alg", key, typ, "FOO", kid,
audience, issuer, user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_wrong_kid", key, typ, alg,
"FOO", audience, issuer, user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_wrong_aud", key, typ, alg, kid,
"FOO", issuer, user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_wrong_iss", key, typ, alg, kid,
audience, "FOO", user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_missing_aud", key, typ, alg,
kid, NULL, issuer, user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_missing_iss", key, typ, alg,
kid, audience, NULL, user_name, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_missing_user", key, typ, alg,
kid, audience, issuer, NULL, now - 60, now - 60,
now + 3600);
generate_token(working_directory, "fail_missing_iat", key, typ, alg,
kid, audience, issuer, user_name, 0, now - 60,
now + 3600);
generate_token(working_directory, "fail_missing_nbf", key, typ, alg,
kid, audience, issuer, user_name, now - 60, 0,
now + 3600);
generate_token(working_directory, "fail_missing_exp", key, typ, alg,
kid, audience, issuer, user_name, now - 60, now - 60, 0);
return 0;
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.cluster.health;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.health.ClusterIndexHealth;
import org.elasticsearch.cluster.health.ClusterStateHealth;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import io.crate.common.unit.TimeValue;
import org.elasticsearch.transport.TransportResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
public class ClusterHealthResponse extends TransportResponse {
private final String clusterName;
private final int numberOfPendingTasks;
private final int numberOfInFlightFetch;
private final int delayedUnassignedShards;
private final TimeValue taskMaxWaitingTime;
private final ClusterStateHealth clusterStateHealth;
private ClusterHealthStatus clusterHealthStatus;
private boolean timedOut = false;
public ClusterHealthResponse(String clusterName, String[] concreteIndices, ClusterState clusterState, int numberOfPendingTasks,
int numberOfInFlightFetch, int delayedUnassignedShards, TimeValue taskMaxWaitingTime) {
this.clusterName = clusterName;
this.numberOfPendingTasks = numberOfPendingTasks;
this.numberOfInFlightFetch = numberOfInFlightFetch;
this.delayedUnassignedShards = delayedUnassignedShards;
this.taskMaxWaitingTime = taskMaxWaitingTime;
this.clusterStateHealth = new ClusterStateHealth(clusterState, concreteIndices);
this.clusterHealthStatus = clusterStateHealth.getStatus();
}
public String getClusterName() {
return clusterName;
}
public int getActiveShards() {
return clusterStateHealth.getActiveShards();
}
public int getRelocatingShards() {
return clusterStateHealth.getRelocatingShards();
}
public int getActivePrimaryShards() {
return clusterStateHealth.getActivePrimaryShards();
}
public int getInitializingShards() {
return clusterStateHealth.getInitializingShards();
}
public int getUnassignedShards() {
return clusterStateHealth.getUnassignedShards();
}
public int getNumberOfNodes() {
return clusterStateHealth.getNumberOfNodes();
}
public int getNumberOfDataNodes() {
return clusterStateHealth.getNumberOfDataNodes();
}
public int getNumberOfPendingTasks() {
return this.numberOfPendingTasks;
}
public int getNumberOfInFlightFetch() {
return this.numberOfInFlightFetch;
}
/**
* The number of unassigned shards that are currently being delayed (for example,
* due to node leaving the cluster and waiting for a timeout for the node to come
* back in order to allocate the shards back to it).
*/
public int getDelayedUnassignedShards() {
return this.delayedUnassignedShards;
}
/**
* {@code true} if the waitForXXX has timeout out and did not match.
*/
public boolean isTimedOut() {
return this.timedOut;
}
public void setTimedOut(boolean timedOut) {
this.timedOut = timedOut;
}
public ClusterHealthStatus getStatus() {
return clusterHealthStatus;
}
/**
* Allows to explicitly override the derived cluster health status.
*
* @param status The override status. Must not be null.
*/
public void setStatus(ClusterHealthStatus status) {
if (status == null) {
throw new IllegalArgumentException("'status' must not be null");
}
this.clusterHealthStatus = status;
}
public Map<String, ClusterIndexHealth> getIndices() {
return clusterStateHealth.getIndices();
}
/**
*
* @return The maximum wait time of all tasks in the queue
*/
public TimeValue getTaskMaxWaitingTime() {
return taskMaxWaitingTime;
}
/**
* The percentage of active shards, should be 100% in a green system
*/
public double getActiveShardsPercent() {
return clusterStateHealth.getActiveShardsPercent();
}
public ClusterHealthResponse(StreamInput in) throws IOException {
clusterName = in.readString();
clusterHealthStatus = ClusterHealthStatus.fromValue(in.readByte());
clusterStateHealth = new ClusterStateHealth(in);
numberOfPendingTasks = in.readInt();
timedOut = in.readBoolean();
numberOfInFlightFetch = in.readInt();
delayedUnassignedShards = in.readInt();
taskMaxWaitingTime = in.readTimeValue();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(clusterName);
out.writeByte(clusterHealthStatus.value());
clusterStateHealth.writeTo(out);
out.writeInt(numberOfPendingTasks);
out.writeBoolean(timedOut);
out.writeInt(numberOfInFlightFetch);
out.writeInt(delayedUnassignedShards);
out.writeTimeValue(taskMaxWaitingTime);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClusterHealthResponse that = (ClusterHealthResponse) o;
return Objects.equals(clusterName, that.clusterName) &&
numberOfPendingTasks == that.numberOfPendingTasks &&
numberOfInFlightFetch == that.numberOfInFlightFetch &&
delayedUnassignedShards == that.delayedUnassignedShards &&
Objects.equals(taskMaxWaitingTime, that.taskMaxWaitingTime) &&
timedOut == that.timedOut &&
Objects.equals(clusterStateHealth, that.clusterStateHealth) &&
clusterHealthStatus == that.clusterHealthStatus;
}
@Override
public int hashCode() {
return Objects.hash(clusterName, numberOfPendingTasks, numberOfInFlightFetch, delayedUnassignedShards, taskMaxWaitingTime,
timedOut, clusterStateHealth, clusterHealthStatus);
}
}
| {
"pile_set_name": "Github"
} |
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// [email protected]. Any infringement will be prosecuted under
// applicable laws.
#endregion
using View = UIKit.UIView;
using UIKit;
using Syncfusion.iOS.TreeView;
namespace SampleBrowser
{
public class NodeImageAdapter : TreeViewAdapter
{
public NodeImageAdapter()
{
}
protected override View CreateContentView(TreeViewItemInfoBase itemInfo)
{
var gridView = new NodeImageView();
return gridView;
}
protected override void UpdateContentView(View view, TreeViewItemInfoBase itemInfo)
{
var grid = view as NodeImageView;
var treeViewNode = itemInfo.Node;
if (grid != null)
{
var imageView = grid.Subviews[0] as UIImageView;
if (imageView != null)
imageView.Image = (treeViewNode.Content as FileManager).ImageIcon;
var label1 = grid.Subviews[1] as UILabel;
if (label1 != null)
label1.Text = (treeViewNode.Content as FileManager).FileName;
}
}
}
} | {
"pile_set_name": "Github"
} |
#Original source: https://github.com/miguelgfierro/codebase/blob/master/python/machine_learning/metrics.py
import numpy as np
from sklearn.metrics import roc_auc_score,accuracy_score, precision_score, recall_score, f1_score
def classification_metrics_binary(y_true, y_pred):
m_acc = accuracy_score(y_true, y_pred)
m_f1 = f1_score(y_true, y_pred)
m_precision = precision_score(y_true, y_pred)
m_recall = recall_score(y_true, y_pred)
report = {'Accuracy':m_acc, 'Precision':m_precision, 'Recall':m_recall, 'F1':m_f1}
return report
def classification_metrics_binary_prob(y_true, y_prob):
m_auc = roc_auc_score(y_true, y_prob)
report = {'AUC':m_auc}
return report
def classification_metrics_multilabel(y_true, y_pred, labels):
m_acc = accuracy_score(y_true, y_pred)
m_f1 = f1_score(y_true, y_pred, labels, average='weighted')
m_precision = precision_score(y_true, y_pred, labels, average='weighted')
m_recall = recall_score(y_true, y_pred, labels, average='weighted')
report = {'Accuracy':m_acc, 'Precision':m_precision, 'Recall':m_recall, 'F1':m_f1}
return report
def binarize_prediction(y, threshold=0.5):
y_pred = np.where(y > threshold, 1, 0)
return y_pred
| {
"pile_set_name": "Github"
} |
/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2011 Steven Lovegrove
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <deque>
#include <pangolin/platform.h>
#include <pangolin/gl/glfont.h>
#include <pangolin/var/var.h>
#include <pangolin/display/view.h>
#include <pangolin/handler/handler.h>
#include <pangolin/gl/colour.h>
#include <pangolin/console/ConsoleInterpreter.h>
namespace pangolin
{
class ConsoleView : public pangolin::View, pangolin::Handler
{
public:
struct Line
{
Line()
{
}
Line(const GlText& text, ConsoleLineType linetype = ConsoleLineTypeCmd )
: text(text), linetype(linetype)
{
}
GlText text;
ConsoleLineType linetype;
};
// Construct with interpreter (and take ownership)
ConsoleView(ConsoleInterpreter* interpreter);
~ConsoleView();
View& ShowWithoutAnimation(bool show=true);
// Replace implementation in View to account for hiding animation
View& Show(bool show=true);
// Replace implementation in View to account for hiding animation
void ToggleShow();
// Replace implementation in View to account for hiding animation
bool IsShown() const;
void Render() override;
void Keyboard(View&, unsigned char key, int x, int y, bool pressed) override;
private:
void DrawLine(const ConsoleView::Line& l);
void ProcessOutputLines();
void AddLine(const std::string& text, ConsoleLineType linetype = ConsoleLineTypeCmd);
Line* GetLine(int id, ConsoleLineType line_type, const std::string& prefix = "");
ConsoleInterpreter* interpreter;
GlFont& font;
std::map<ConsoleLineType, GlText> prompts;
Line current_line;
std::deque<Line> line_buffer;
bool hiding;
GLfloat bottom;
Colour background_colour;
std::map<ConsoleLineType,pangolin::Colour> line_colours;
float animation_speed;
};
}
| {
"pile_set_name": "Github"
} |
$NetBSD: distinfo,v 1.2 2015/11/03 23:33:44 agc Exp $
SHA1 (tex-kastrup-15878/kastrup.tar.xz) = 5506d5568267aa1c949127beb374cbe555d452af
RMD160 (tex-kastrup-15878/kastrup.tar.xz) = cb1e6cea56d3e5b9ec45db73e71fc17ed4d63753
SHA512 (tex-kastrup-15878/kastrup.tar.xz) = 6d0011a198f4139d4edb8cbfc2fa4b36c9a881674510ecef40345b740a57db0054f8e8d8bf3d2d5432fb5677808b37b0d65fc138bf2556ef9d32aaa4243d6860
Size (tex-kastrup-15878/kastrup.tar.xz) = 1224 bytes
| {
"pile_set_name": "Github"
} |
/**
* This file is part of ORB-SLAM2.
*
* Copyright (C) 2014-2016 Raúl Mur-Artal <raulmur at unizar dot es> (University of Zaragoza)
* For more information see <https://github.com/raulmur/ORB_SLAM2>
*
* ORB-SLAM2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ORB-SLAM2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ORB-SLAM2. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iomanip>
#include "KeyFrameDatabase.h"
#include "KeyFrame.h"
#include "Thirdparty/DBoW2/DBoW2/BowVector.h"
#include<mutex>
using namespace std;
namespace ORB_SLAM2
{
KeyFrameDatabase::KeyFrameDatabase (const ORBVocabulary &voc):
mpVoc(&voc)
{
mvInvertedFile.resize(voc.size());
}
void KeyFrameDatabase::add(KeyFrame *pKF)
{
unique_lock<mutex> lock(mMutex);
for(DBoW2::BowVector::const_iterator vit= pKF->mBowVec.begin(), vend=pKF->mBowVec.end(); vit!=vend; vit++)
mvInvertedFile[vit->first].push_back(pKF);
}
void KeyFrameDatabase::erase(KeyFrame* pKF)
{
unique_lock<mutex> lock(mMutex);
// Erase elements in the Inverse File for the entry
for(DBoW2::BowVector::const_iterator vit=pKF->mBowVec.begin(), vend=pKF->mBowVec.end(); vit!=vend; vit++)
{
// List of keyframes that share the word
list<KeyFrame*> &lKFs = mvInvertedFile[vit->first];
for(list<KeyFrame*>::iterator lit=lKFs.begin(), lend= lKFs.end(); lit!=lend; lit++)
{
if(pKF==*lit)
{
lKFs.erase(lit);
break;
}
}
}
}
void KeyFrameDatabase::clear()
{
mvInvertedFile.clear();
mvInvertedFile.resize(mpVoc->size());
}
vector<KeyFrame*> KeyFrameDatabase::DetectLoopCandidates(KeyFrame* pKF, float minScore)
{
set<KeyFrame*> spConnectedKeyFrames = pKF->GetConnectedKeyFrames();
list<KeyFrame*> lKFsSharingWords;
// Search all keyframes that share a word with current keyframes
// Discard keyframes connected to the query keyframe
{
unique_lock<mutex> lock(mMutex);
for(DBoW2::BowVector::const_iterator vit=pKF->mBowVec.begin(), vend=pKF->mBowVec.end(); vit != vend; vit++)
{
list<KeyFrame*> &lKFs = mvInvertedFile[vit->first];
for(list<KeyFrame*>::iterator lit=lKFs.begin(), lend= lKFs.end(); lit!=lend; lit++)
{
KeyFrame* pKFi=*lit;
if(pKFi->mnLoopQuery!=pKF->mnId)
{
pKFi->mnLoopWords=0;
if(!spConnectedKeyFrames.count(pKFi))
{
pKFi->mnLoopQuery=pKF->mnId;
lKFsSharingWords.push_back(pKFi);
}
}
pKFi->mnLoopWords++;
}
}
}
if(lKFsSharingWords.empty())
return vector<KeyFrame*>();
list<pair<float,KeyFrame*> > lScoreAndMatch;
// Only compare against those keyframes that share enough words
int maxCommonWords=0;
for(list<KeyFrame*>::iterator lit=lKFsSharingWords.begin(), lend= lKFsSharingWords.end(); lit!=lend; lit++)
{
if((*lit)->mnLoopWords>maxCommonWords)
maxCommonWords=(*lit)->mnLoopWords;
}
int minCommonWords = maxCommonWords*0.8f;
int nscores=0;
// Compute similarity score. Retain the matches whose score is higher than minScore
for(list<KeyFrame*>::iterator lit=lKFsSharingWords.begin(), lend= lKFsSharingWords.end(); lit!=lend; lit++)
{
KeyFrame* pKFi = *lit;
if(pKFi->mnLoopWords>minCommonWords)
{
nscores++;
float si = mpVoc->score(pKF->mBowVec,pKFi->mBowVec);
pKFi->mLoopScore = si;
if(si>=minScore)
lScoreAndMatch.push_back(make_pair(si,pKFi));
}
}
if(lScoreAndMatch.empty())
return vector<KeyFrame*>();
list<pair<float,KeyFrame*> > lAccScoreAndMatch;
float bestAccScore = minScore;
// Lets now accumulate score by covisibility
for(list<pair<float,KeyFrame*> >::iterator it=lScoreAndMatch.begin(), itend=lScoreAndMatch.end(); it!=itend; it++)
{
KeyFrame* pKFi = it->second;
vector<KeyFrame*> vpNeighs = pKFi->GetBestCovisibilityKeyFrames(10);
float bestScore = it->first;
float accScore = it->first;
KeyFrame* pBestKF = pKFi;
for(vector<KeyFrame*>::iterator vit=vpNeighs.begin(), vend=vpNeighs.end(); vit!=vend; vit++)
{
KeyFrame* pKF2 = *vit;
if(pKF2->mnLoopQuery==pKF->mnId && pKF2->mnLoopWords>minCommonWords)
{
accScore+=pKF2->mLoopScore;
if(pKF2->mLoopScore>bestScore)
{
pBestKF=pKF2;
bestScore = pKF2->mLoopScore;
}
}
}
lAccScoreAndMatch.push_back(make_pair(accScore,pBestKF));
if(accScore>bestAccScore)
bestAccScore=accScore;
}
// Return all those keyframes with a score higher than 0.75*bestScore
float minScoreToRetain = 0.75f*bestAccScore;
set<KeyFrame*> spAlreadyAddedKF;
vector<KeyFrame*> vpLoopCandidates;
vpLoopCandidates.reserve(lAccScoreAndMatch.size());
for(list<pair<float,KeyFrame*> >::iterator it=lAccScoreAndMatch.begin(), itend=lAccScoreAndMatch.end(); it!=itend; it++)
{
if(it->first>minScoreToRetain)
{
KeyFrame* pKFi = it->second;
if(!spAlreadyAddedKF.count(pKFi))
{
vpLoopCandidates.push_back(pKFi);
spAlreadyAddedKF.insert(pKFi);
}
}
}
return vpLoopCandidates;
}
vector<KeyFrame*> KeyFrameDatabase::DetectRelocalizationCandidates(Frame *F)
{
list<KeyFrame*> lKFsSharingWords;
// Search all keyframes that share a word with current frame
{
unique_lock<mutex> lock(mMutex);
for(DBoW2::BowVector::const_iterator vit=F->mBowVec.begin(), vend=F->mBowVec.end(); vit != vend; vit++)
{
list<KeyFrame*> &lKFs = mvInvertedFile[vit->first];
for(list<KeyFrame*>::iterator lit=lKFs.begin(), lend= lKFs.end(); lit!=lend; lit++)
{
KeyFrame* pKFi=*lit;
if(pKFi->mnRelocQuery!=F->mnId)
{
pKFi->mnRelocWords=0;
pKFi->mnRelocQuery=F->mnId;
lKFsSharingWords.push_back(pKFi);
}
pKFi->mnRelocWords++;
}
}
}
if(lKFsSharingWords.empty())
return vector<KeyFrame*>();
// Only compare against those keyframes that share enough words
int maxCommonWords=0;
for(list<KeyFrame*>::iterator lit=lKFsSharingWords.begin(), lend= lKFsSharingWords.end(); lit!=lend; lit++)
{
if((*lit)->mnRelocWords>maxCommonWords)
maxCommonWords=(*lit)->mnRelocWords;
}
int minCommonWords = maxCommonWords*0.8f;
list<pair<float,KeyFrame*> > lScoreAndMatch;
int nscores=0;
// Compute similarity score.
for(list<KeyFrame*>::iterator lit=lKFsSharingWords.begin(), lend= lKFsSharingWords.end(); lit!=lend; lit++)
{
KeyFrame* pKFi = *lit;
if(pKFi->mnRelocWords>minCommonWords)
{
nscores++;
float si = mpVoc->score(F->mBowVec,pKFi->mBowVec);
pKFi->mRelocScore=si;
lScoreAndMatch.push_back(make_pair(si,pKFi));
}
}
if(lScoreAndMatch.empty())
return vector<KeyFrame*>();
list<pair<float,KeyFrame*> > lAccScoreAndMatch;
float bestAccScore = 0;
// Lets now accumulate score by covisibility
for(list<pair<float,KeyFrame*> >::iterator it=lScoreAndMatch.begin(), itend=lScoreAndMatch.end(); it!=itend; it++)
{
KeyFrame* pKFi = it->second;
vector<KeyFrame*> vpNeighs = pKFi->GetBestCovisibilityKeyFrames(10);
float bestScore = it->first;
float accScore = bestScore;
KeyFrame* pBestKF = pKFi;
for(vector<KeyFrame*>::iterator vit=vpNeighs.begin(), vend=vpNeighs.end(); vit!=vend; vit++)
{
KeyFrame* pKF2 = *vit;
if(pKF2->mnRelocQuery!=F->mnId)
continue;
accScore+=pKF2->mRelocScore;
if(pKF2->mRelocScore>bestScore)
{
pBestKF=pKF2;
bestScore = pKF2->mRelocScore;
}
}
lAccScoreAndMatch.push_back(make_pair(accScore,pBestKF));
if(accScore>bestAccScore)
bestAccScore=accScore;
}
// Return all those keyframes with a score higher than 0.75*bestScore
float minScoreToRetain = 0.75f*bestAccScore;
set<KeyFrame*> spAlreadyAddedKF;
vector<KeyFrame*> vpRelocCandidates;
vpRelocCandidates.reserve(lAccScoreAndMatch.size());
for(list<pair<float,KeyFrame*> >::iterator it=lAccScoreAndMatch.begin(), itend=lAccScoreAndMatch.end(); it!=itend; it++)
{
const float &si = it->first;
if(si>minScoreToRetain)
{
KeyFrame* pKFi = it->second;
if(!spAlreadyAddedKF.count(pKFi))
{
vpRelocCandidates.push_back(pKFi);
spAlreadyAddedKF.insert(pKFi);
}
}
}
return vpRelocCandidates;
}
} //namespace ORB_SLAM
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
<cbid>CROMU_00001</cbid>
<replay>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>noqwrws\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>cfzsial\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
<write echo="ascii"><data>cfzsial\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>cfzsial\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>aeglitguikpqvpn\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1: aeglitguikpqvpn\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>noqwrws\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>fpacqlyqpgkpaxo\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>cfzsial\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>lvjwyptklfduwxxszv\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2: lvjwyptklfduwxxszv\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>cfzsial\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>hihrfhpzyphe\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3: hihrfhpzyphe\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>4\n</data></write>
<read echo="ascii"><delim> </delim><match><data>ID: </data></match></read>
<write echo="ascii"><data>2\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>noqwrws\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>hlhgdg\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>cfzsial\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>lkjtwjrgeme\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Unread messages:\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4: lkjtwjrgeme\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>***********************************\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>1\n</data></write>
<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
<write echo="ascii"><data>noqwrws\n</data></write>
<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
<write echo="ascii"><data>yrjlcqebiye\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
<write echo="ascii"><data>6\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>Exiting...\n</data></match></read>
</replay>
</pov>
| {
"pile_set_name": "Github"
} |
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby.internal;
import io.jooby.SslOptions;
import javax.net.ssl.SSLContext;
public interface SslContextProvider {
boolean supports(String type);
SSLContext create(ClassLoader loader, SslOptions options);
static SslContextProvider[] providers() {
return new SslContextProvider[] {new SslPkcs12Provider(), new SslX509Provider()};
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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 androidx.core.text;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Locale;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class BidiFormatterTest {
private static final BidiFormatter LTR_FMT = BidiFormatter.getInstance(false /* LTR context */);
private static final BidiFormatter RTL_FMT = BidiFormatter.getInstance(true /* RTL context */);
private static final BidiFormatter LTR_FMT_EXIT_RESET =
new BidiFormatter.Builder(false /* LTR context */).stereoReset(false).build();
private static final BidiFormatter RTL_FMT_EXIT_RESET =
new BidiFormatter.Builder(true /* RTL context */).stereoReset(false).build();
private static final String EN = "abba";
private static final String HE = "\u05E0\u05E1";
private static final String LRM = "\u200E";
private static final String RLM = "\u200F";
private static final String LRE = "\u202A";
private static final String RLE = "\u202B";
private static final String PDF = "\u202C";
@Test
public void testIsRtlContext() {
assertEquals(false, LTR_FMT.isRtlContext());
assertEquals(true, RTL_FMT.isRtlContext());
assertEquals(false, BidiFormatter.getInstance(Locale.ENGLISH).isRtlContext());
assertEquals(true, BidiFormatter.getInstance(true).isRtlContext());
}
@Test
public void testBuilderIsRtlContext() {
assertEquals(false, new BidiFormatter.Builder(false).build().isRtlContext());
assertEquals(true, new BidiFormatter.Builder(true).build().isRtlContext());
}
@Test
public void testIsRtl() {
assertEquals(true, BidiFormatter.getInstance(true).isRtl(HE));
assertEquals(true, BidiFormatter.getInstance(false).isRtl(HE));
assertEquals(false, BidiFormatter.getInstance(true).isRtl(EN));
assertEquals(false, BidiFormatter.getInstance(false).isRtl(EN));
}
@Test
public void testUnicodeWrap() {
// Make sure an input of null doesn't crash anything.
assertNull(LTR_FMT.unicodeWrap(null));
// Uniform directionality in opposite context.
assertEquals("uniform dir opposite to LTR context",
RLE + "." + HE + "." + PDF + LRM,
LTR_FMT_EXIT_RESET.unicodeWrap("." + HE + "."));
assertEquals("uniform dir opposite to LTR context, stereo reset",
LRM + RLE + "." + HE + "." + PDF + LRM,
LTR_FMT.unicodeWrap("." + HE + "."));
assertEquals("uniform dir opposite to LTR context, stereo reset, no isolation",
RLE + "." + HE + "." + PDF,
LTR_FMT.unicodeWrap("." + HE + ".", false));
assertEquals("neutral treated as opposite to LTR context",
RLE + "." + PDF + LRM,
LTR_FMT_EXIT_RESET.unicodeWrap(".", TextDirectionHeuristicsCompat.RTL));
assertEquals("uniform dir opposite to RTL context",
LRE + "." + EN + "." + PDF + RLM,
RTL_FMT_EXIT_RESET.unicodeWrap("." + EN + "."));
assertEquals("uniform dir opposite to RTL context, stereo reset",
RLM + LRE + "." + EN + "." + PDF + RLM,
RTL_FMT.unicodeWrap("." + EN + "."));
assertEquals("uniform dir opposite to RTL context, stereo reset, no isolation",
LRE + "." + EN + "." + PDF,
RTL_FMT.unicodeWrap("." + EN + ".", false));
assertEquals("neutral treated as opposite to RTL context",
LRE + "." + PDF + RLM,
RTL_FMT_EXIT_RESET.unicodeWrap(".", TextDirectionHeuristicsCompat.LTR));
// We test mixed-directionality cases only with an explicit overall directionality parameter
// because the estimation logic is outside the sphere of BidiFormatter, and different
// estimators will treat them differently.
// Overall directionality matching context, but with opposite exit directionality.
assertEquals("exit dir opposite to LTR context",
EN + HE + LRM,
LTR_FMT_EXIT_RESET.unicodeWrap(EN + HE, TextDirectionHeuristicsCompat.LTR));
assertEquals("exit dir opposite to LTR context, stereo reset",
EN + HE + LRM,
LTR_FMT.unicodeWrap(EN + HE, TextDirectionHeuristicsCompat.LTR));
assertEquals("exit dir opposite to LTR context, stereo reset, no isolation",
EN + HE,
LTR_FMT.unicodeWrap(EN + HE, TextDirectionHeuristicsCompat.LTR, false));
assertEquals("exit dir opposite to RTL context",
HE + EN + RLM,
RTL_FMT_EXIT_RESET.unicodeWrap(HE + EN, TextDirectionHeuristicsCompat.RTL));
assertEquals("exit dir opposite to RTL context, stereo reset",
HE + EN + RLM,
RTL_FMT.unicodeWrap(HE + EN, TextDirectionHeuristicsCompat.RTL));
assertEquals("exit dir opposite to RTL context, stereo reset, no isolation",
HE + EN,
RTL_FMT.unicodeWrap(HE + EN, TextDirectionHeuristicsCompat.RTL, false));
// Overall directionality matching context, but with opposite entry directionality.
assertEquals("entry dir opposite to LTR context",
HE + EN,
LTR_FMT_EXIT_RESET.unicodeWrap(HE + EN, TextDirectionHeuristicsCompat.LTR));
assertEquals("entry dir opposite to LTR context, stereo reset",
LRM + HE + EN,
LTR_FMT.unicodeWrap(HE + EN, TextDirectionHeuristicsCompat.LTR));
assertEquals("entry dir opposite to LTR context, stereo reset, no isolation",
HE + EN,
LTR_FMT.unicodeWrap(HE + EN, TextDirectionHeuristicsCompat.LTR, false));
assertEquals("entry dir opposite to RTL context",
EN + HE,
RTL_FMT_EXIT_RESET.unicodeWrap(EN + HE, TextDirectionHeuristicsCompat.RTL));
assertEquals("entry dir opposite to RTL context, stereo reset",
RLM + EN + HE,
RTL_FMT.unicodeWrap(EN + HE, TextDirectionHeuristicsCompat.RTL));
assertEquals("entry dir opposite to RTL context, stereo reset, no isolation",
EN + HE,
RTL_FMT.unicodeWrap(EN + HE, TextDirectionHeuristicsCompat.RTL, false));
// Overall directionality matching context, but with opposite entry and exit directionality.
assertEquals("entry and exit dir opposite to LTR context",
HE + EN + HE + LRM,
LTR_FMT_EXIT_RESET.unicodeWrap(HE + EN + HE, TextDirectionHeuristicsCompat.LTR));
assertEquals("entry and exit dir opposite to LTR context, stereo reset",
LRM + HE + EN + HE + LRM,
LTR_FMT.unicodeWrap(HE + EN + HE, TextDirectionHeuristicsCompat.LTR));
assertEquals("entry and exit dir opposite to LTR context, no isolation",
HE + EN + HE,
LTR_FMT_EXIT_RESET.unicodeWrap(HE + EN + HE, TextDirectionHeuristicsCompat.LTR,
false));
assertEquals("entry and exit dir opposite to RTL context",
EN + HE + EN + RLM,
RTL_FMT_EXIT_RESET.unicodeWrap(EN + HE + EN, TextDirectionHeuristicsCompat.RTL));
assertEquals("entry and exit dir opposite to RTL context, no isolation",
EN + HE + EN,
RTL_FMT_EXIT_RESET.unicodeWrap(EN + HE + EN, TextDirectionHeuristicsCompat.RTL,
false));
// Entry and exit directionality matching context, but with opposite overall directionality.
assertEquals("overall dir (but not entry or exit dir) opposite to LTR context",
RLE + EN + HE + EN + PDF + LRM,
LTR_FMT_EXIT_RESET.unicodeWrap(EN + HE + EN, TextDirectionHeuristicsCompat.RTL));
assertEquals("overall dir (but not entry or exit dir) opposite to LTR context, stereo reset",
LRM + RLE + EN + HE + EN + PDF + LRM,
LTR_FMT.unicodeWrap(EN + HE + EN, TextDirectionHeuristicsCompat.RTL));
assertEquals("overall dir (but not entry or exit dir) opposite to LTR context, no isolation",
RLE + EN + HE + EN + PDF,
LTR_FMT_EXIT_RESET.unicodeWrap(EN + HE + EN, TextDirectionHeuristicsCompat.RTL,
false));
assertEquals("overall dir (but not entry or exit dir) opposite to RTL context",
LRE + HE + EN + HE + PDF + RLM,
RTL_FMT_EXIT_RESET.unicodeWrap(HE + EN + HE, TextDirectionHeuristicsCompat.LTR));
assertEquals("overall dir (but not entry or exit dir) opposite to RTL context, stereo reset",
RLM + LRE + HE + EN + HE + PDF + RLM,
RTL_FMT.unicodeWrap(HE + EN + HE, TextDirectionHeuristicsCompat.LTR));
assertEquals("overall dir (but not entry or exit dir) opposite to RTL context, no isolation",
LRE + HE + EN + HE + PDF,
RTL_FMT_EXIT_RESET.unicodeWrap(HE + EN + HE, TextDirectionHeuristicsCompat.LTR,
false));
}
@Test
public void testCharSequenceApis() {
final CharSequence CS_HE = new SpannableString(HE);
assertEquals(true, BidiFormatter.getInstance(true).isRtl(CS_HE));
final SpannableString CS_EN_HE = new SpannableString(EN + HE);
final Object RELATIVE_SIZE_SPAN = new RelativeSizeSpan(1.2f);
CS_EN_HE.setSpan(RELATIVE_SIZE_SPAN, 0, EN.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
Spanned wrapped;
Object[] spans;
wrapped = (Spanned) LTR_FMT.unicodeWrap(CS_EN_HE);
assertEquals(EN + HE + LRM, wrapped.toString());
spans = wrapped.getSpans(0, wrapped.length(), Object.class);
assertEquals(1, spans.length);
assertEquals(RELATIVE_SIZE_SPAN, spans[0]);
assertEquals(0, wrapped.getSpanStart(RELATIVE_SIZE_SPAN));
assertEquals(EN.length(), wrapped.getSpanEnd(RELATIVE_SIZE_SPAN));
wrapped = (Spanned) LTR_FMT.unicodeWrap(CS_EN_HE, TextDirectionHeuristicsCompat.LTR);
assertEquals(EN + HE + LRM, wrapped.toString());
spans = wrapped.getSpans(0, wrapped.length(), Object.class);
assertEquals(1, spans.length);
assertEquals(RELATIVE_SIZE_SPAN, spans[0]);
assertEquals(0, wrapped.getSpanStart(RELATIVE_SIZE_SPAN));
assertEquals(EN.length(), wrapped.getSpanEnd(RELATIVE_SIZE_SPAN));
wrapped = (Spanned) LTR_FMT.unicodeWrap(CS_EN_HE, false);
assertEquals(EN + HE, wrapped.toString());
spans = wrapped.getSpans(0, wrapped.length(), Object.class);
assertEquals(1, spans.length);
assertEquals(RELATIVE_SIZE_SPAN, spans[0]);
assertEquals(0, wrapped.getSpanStart(RELATIVE_SIZE_SPAN));
assertEquals(EN.length(), wrapped.getSpanEnd(RELATIVE_SIZE_SPAN));
wrapped = (Spanned) LTR_FMT.unicodeWrap(CS_EN_HE, TextDirectionHeuristicsCompat.LTR, false);
assertEquals(EN + HE, wrapped.toString());
spans = wrapped.getSpans(0, wrapped.length(), Object.class);
assertEquals(1, spans.length);
assertEquals(RELATIVE_SIZE_SPAN, spans[0]);
assertEquals(0, wrapped.getSpanStart(RELATIVE_SIZE_SPAN));
assertEquals(EN.length(), wrapped.getSpanEnd(RELATIVE_SIZE_SPAN));
}
}
| {
"pile_set_name": "Github"
} |
.class public IL2C.ILConverters.Ldc_i4_5
{
.method public static int32 RawValue() cil managed
{
.maxstack 2
ldc.i4.5
ret
}
.method public static int32 Add(int32 num) cil managed
{
.maxstack 2
ldarg.0
ldc.i4.5
add
ret
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.8: http://docutils.sourceforge.net/" />
<title>C++ exam</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
</head>
<body>
<div class="document" id="c-exam">
<h1 class="title">C++ exam</h1>
<p>Name:</p>
<p>Surname:</p>
<div class="section" id="extern">
<h1>1 Extern</h1>
<p>The code below declares and defines variable x. <strong>True</strong> or <strong>False</strong> ?</p>
<pre class="code c++ literal-block">
<span class="k">extern</span> <span class="kt">int</span> <span class="n">x</span><span class="p">;</span>
</pre>
</div>
<div class="section" id="namespace">
<h1>2 Namespace</h1>
<p>In namespace foo, the function bar can access the variable x also declared in
namespace foo ? <strong>True</strong> or <strong>False</strong> ?</p>
<pre class="code c++ literal-block">
<span class="cp">#include <iostream>
</span>
<span class="k">namespace</span> <span class="n">foo</span>
<span class="p">{</span>
<span class="kt">void</span> <span class="n">bar</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">x</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="n">x</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="references">
<h1>3 References</h1>
<p>What is the output of the following program ?</p>
<pre class="code c++ literal-block">
<span class="cp">#include <iostream>
</span><span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>
<span class="kt">void</span> <span class="n">swap1</span><span class="p">(</span> <span class="kt">int</span> <span class="n">a</span><span class="p">,</span> <span class="kt">int</span> <span class="n">b</span> <span class="p">)</span> <span class="p">{</span> <span class="kt">int</span> <span class="n">c</span><span class="o">=</span><span class="n">a</span><span class="p">;</span> <span class="n">a</span><span class="o">=</span><span class="n">b</span><span class="p">;</span> <span class="n">b</span><span class="o">=</span><span class="n">c</span><span class="p">;</span> <span class="p">}</span>
<span class="kt">void</span> <span class="n">swap2</span><span class="p">(</span> <span class="kt">int</span> <span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="kt">int</span> <span class="o">*</span><span class="n">b</span> <span class="p">)</span> <span class="p">{</span> <span class="kt">int</span> <span class="n">c</span><span class="o">=*</span><span class="n">a</span><span class="p">;</span> <span class="o">*</span><span class="n">a</span><span class="o">=*</span><span class="n">b</span><span class="p">;</span> <span class="o">*</span><span class="n">b</span><span class="o">=</span><span class="n">c</span><span class="p">;</span> <span class="p">}</span>
<span class="kt">void</span> <span class="n">swap3</span><span class="p">(</span> <span class="kt">int</span> <span class="o">&</span><span class="n">a</span><span class="p">,</span> <span class="kt">int</span> <span class="o">&</span><span class="n">b</span> <span class="p">)</span> <span class="p">{</span> <span class="kt">int</span> <span class="o">&</span><span class="n">c</span><span class="o">=</span><span class="n">a</span><span class="p">;</span> <span class="n">a</span><span class="o">=</span><span class="n">b</span><span class="p">;</span> <span class="n">b</span><span class="o">=</span><span class="n">c</span><span class="p">;</span> <span class="p">}</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span> <span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">**</span><span class="n">argv</span> <span class="p">)</span>
<span class="p">{</span>
<span class="kt">int</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">;</span>
<span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> <span class="n">swap1</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">);</span>
<span class="n">cout</span> <span class="o"><<</span> <span class="s">"a: "</span> <span class="o"><<</span> <span class="n">a</span> <span class="o"><<</span> <span class="s">", "</span> <span class="o"><<</span><span class="s">"b: "</span> <span class="o"><<</span> <span class="n">b</span> <span class="o"><<</span> <span class="n">endl</span><span class="p">;</span>
<span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> <span class="n">swap2</span><span class="p">(</span><span class="o">&</span><span class="n">a</span><span class="p">,</span><span class="o">&</span><span class="n">b</span><span class="p">);</span>
<span class="n">cout</span> <span class="o"><<</span> <span class="s">"a: "</span> <span class="o"><<</span> <span class="n">a</span> <span class="o"><<</span> <span class="s">", "</span> <span class="o"><<</span><span class="s">"b: "</span> <span class="o"><<</span> <span class="n">b</span> <span class="o"><<</span> <span class="n">endl</span><span class="p">;</span>
<span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> <span class="n">swap3</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">);</span>
<span class="n">cout</span> <span class="o"><<</span> <span class="s">"a: "</span> <span class="o"><<</span> <span class="n">a</span> <span class="o"><<</span> <span class="s">", "</span> <span class="o"><<</span><span class="s">"b: "</span> <span class="o"><<</span> <span class="n">b</span> <span class="o"><<</span> <span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="inheritance">
<h1>4 Inheritance</h1>
<p>What is the output of the program ?</p>
<pre class="code c++ literal-block">
<span class="cp">#include <iostream>
</span>
<span class="k">struct</span> <span class="n">A</span> <span class="p">{</span> <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">color</span><span class="p">;</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">B</span> <span class="o">:</span> <span class="k">public</span> <span class="n">A</span> <span class="p">{</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">C</span> <span class="o">:</span> <span class="k">public</span> <span class="n">A</span> <span class="p">{</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">D</span> <span class="o">:</span> <span class="k">public</span> <span class="n">B</span><span class="p">,</span> <span class="k">public</span> <span class="n">C</span> <span class="p">{</span> <span class="p">};</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">D</span> <span class="n">d</span><span class="p">;</span>
<span class="n">d</span><span class="p">.</span><span class="n">color</span> <span class="o">=</span> <span class="mi">3</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="n">d</span><span class="p">.</span><span class="n">color</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="id1">
<h1>5 Inheritance</h1>
<p>How many times is "Hello World" printed by this program ?</p>
<pre class="code c++ literal-block">
<span class="cp">#include <iostream>
</span>
<span class="k">struct</span> <span class="n">A</span> <span class="p">{</span> <span class="n">A</span><span class="p">()</span> <span class="p">{</span> <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Hello World"</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span> <span class="p">}</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">A1</span> <span class="o">:</span> <span class="k">public</span> <span class="n">A</span> <span class="p">{</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">A2</span> <span class="o">:</span> <span class="k">public</span> <span class="n">A</span> <span class="p">{</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">A3</span> <span class="o">:</span> <span class="k">public</span> <span class="n">A</span> <span class="p">{</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">A4</span> <span class="o">:</span> <span class="k">public</span> <span class="n">A</span> <span class="p">{</span> <span class="p">};</span>
<span class="k">struct</span> <span class="n">B</span> <span class="o">:</span> <span class="k">public</span> <span class="n">A1</span><span class="p">,</span> <span class="k">public</span> <span class="n">A2</span><span class="p">,</span> <span class="k">public</span> <span class="n">A3</span><span class="p">,</span> <span class="k">public</span> <span class="n">A4</span> <span class="p">{</span> <span class="p">};</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">B</span> <span class="n">b</span><span class="p">;</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="initialization">
<h1>6 Initialization</h1>
<p>What is the value of x, y & z ?</p>
<pre class="code c++ literal-block">
<span class="cp">#include <iostream>
</span>
<span class="k">struct</span> <span class="n">A</span>
<span class="p">{</span>
<span class="n">A</span><span class="p">(</span><span class="kt">int</span> <span class="n">n</span><span class="p">)</span> <span class="o">:</span> <span class="n">x</span><span class="p">(</span><span class="n">n</span><span class="o">++</span><span class="p">),</span> <span class="n">y</span><span class="p">(</span><span class="n">n</span><span class="o">++</span><span class="p">),</span> <span class="n">z</span><span class="p">(</span><span class="n">n</span><span class="o">++</span><span class="p">)</span> <span class="p">{}</span>
<span class="kt">int</span> <span class="n">x</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">y</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">z</span><span class="p">;</span>
<span class="p">};</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">Foo</span> <span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"x: "</span> <span class="o"><<</span> <span class="n">f</span><span class="p">.</span><span class="n">x</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"y: "</span> <span class="o"><<</span> <span class="n">f</span><span class="p">.</span><span class="n">y</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"z: "</span> <span class="o"><<</span> <span class="n">f</span><span class="p">.</span><span class="n">z</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="logic">
<h1>7 Logic</h1>
<p>What value gets printed by the program?</p>
<pre class="code c++ literal-block">
<span class="cp">#include <iostream>
</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">x</span><span class="o">++</span> <span class="o">&&</span> <span class="n">y</span><span class="o">++</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">y</span> <span class="o">+=</span> <span class="mi">2</span><span class="p">;</span>
<span class="p">}</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="constructors">
<h1>8 Constructors</h1>
<p>Which lines below should not compile ?</p>
<pre class="code c++ literal-block">
<span class="k">struct</span> <span class="n">A</span>
<span class="p">{</span>
<span class="n">A</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="o">:</span> <span class="n">n</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="p">{}</span>
<span class="kt">int</span> <span class="n">n</span><span class="p">;</span>
<span class="p">};</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">A</span> <span class="n">a1</span><span class="p">;</span>
<span class="n">A</span> <span class="n">a2</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
<span class="n">A</span> <span class="n">a3</span><span class="p">(</span><span class="n">a2</span><span class="p">);</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="memory">
<h1>9 Memory</h1>
<p>Which of the following implementations of the reset function is best for
initializing the array to all zero.</p>
<pre class="code c++ literal-block">
<span class="k">class</span> <span class="nc">foo</span><span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
<span class="n">foo</span><span class="p">(){</span>
<span class="n">reset</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">private</span><span class="o">:</span>
<span class="kt">void</span> <span class="n">reset</span><span class="p">(){</span>
<span class="c1">// A // memset(x, 0, 50);
</span> <span class="c1">// B // memset(x, 0, sizeof(x));
</span> <span class="c1">// C // memset(x, 0, 50 * 4);
</span> <span class="c1">// D // memset(x, 0, 50 * sizeof(x));
</span> <span class="p">}</span>
<span class="kt">long</span> <span class="n">x</span><span class="p">[</span><span class="mi">50</span><span class="p">];</span>
<span class="p">};</span>
</pre>
</div>
<div class="section" id="id2">
<h1>10 References</h1>
<p>What is the output of the program ?</p>
<pre class="code c++ literal-block">
<span class="cp">#include <iostream>
</span>
<span class="kt">int</span> <span class="n">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">**</span> <span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// assume address of x is 0x822222222
</span> <span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">3</span><span class="p">;</span>
<span class="kt">int</span><span class="o">*&</span> <span class="n">rpx</span> <span class="o">=</span> <span class="o">&</span><span class="n">x</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="n">rpx</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre>
</div>
<div class="section" id="end">
<h1>11 End</h1>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
'use strict';
const { expect } = require('chai');
const spec = require('../util.js').setup();
describe('lesshint', function () {
describe('#spaceAroundComma', function () {
let options;
it('should have the proper node types', function () {
const source = 'color: rgb(255, 255, 255);';
return spec.parse(source, function (ast) {
expect(spec.linter.nodeTypes).to.include(ast.root.first.type);
});
});
describe('when "style" is "after"', function () {
beforeEach(function () {
options = {
style: 'after'
};
});
it('should allow one space after comma', function () {
const source = 'color: rgb(255, 255, 255);';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should not allow missing space after comma', function () {
const source = 'color: rgb(255,255,255);';
const expected = [
{
column: 15,
line: 1,
message: 'Commas should be followed by one space.'
},
{
column: 19,
line: 1,
message: 'Commas should be followed by one space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should allow one space after comma in mixin declarations', function () {
const source = '.mixin(@margin, @padding) {}';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should allow one space after comma in mixin includes', function () {
const source = '.foo {.mixin(@margin, @padding);}';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first.first);
expect(result).to.be.undefined;
});
});
it('should account for multiline rules with commas', function () {
const source = '.foo,\n.bar {}';
options.allowNewline = true;
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should not allow missing space after comma in mixins', function () {
const source = '.mixin(@margin,@padding) {}';
const expected = [{
column: 15,
line: 1,
message: 'Commas should be followed by one space.'
}];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should not allow multiline comma lists when allowNewline is false', function () {
const source = 'font: 14px,\n Roboto,\n #000000;';
const expected = [
{
column: 11,
line: 1,
message: 'Commas should be followed by one space.'
},
{
column: 11,
line: 2,
message: 'Commas should be followed by one space.'
}
];
options.allowNewline = false;
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should allow multiline comma lists when allowNewline is true', function () {
const source = 'font: 14px,\n Roboto,\n #000000;';
options.allowNewline = true;
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
}); // "after"
describe('when "style" is "before"', function () {
beforeEach(function () {
options = {
style: 'before'
};
});
it('should allow one space before comma', function () {
const source = 'color: rgb(255 ,255 ,255);';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should not allow missing space before comma', function () {
const source = 'color: rgb(255, 255, 255);';
const expected = [
{
column: 15,
line: 1,
message: 'Commas should be preceded by one space.'
},
{
column: 20,
line: 1,
message: 'Commas should be preceded by one space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should account for multiline rules with commas', function () {
const source = '.foo\n,.bar {}';
options.allowNewline = true;
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should allow one space before comma in mixin declarations', function () {
const source = '.mixin(@margin ,@padding) {}';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should allow one space after comma in mixin includes', function () {
const source = '.foo {.mixin(@margin ,@padding);}';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first.first);
expect(result).to.be.undefined;
});
});
it('should not allow missing space before comma in mixins', function () {
const source = '.mixin(@margin, @padding) {}';
const expected = [{
column: 15,
line: 1,
message: 'Commas should be preceded by one space.'
}];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should allow multiline comma lists when allowNewline is true', function () {
const source = 'font: 14px\n, Roboto\n, #000000;';
options.allowNewline = true;
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
}); // "before"
describe('when "style" is "both"', function () {
beforeEach(function () {
options = {
style: 'both'
};
});
it('should allow one space before and after comma', function () {
const source = 'color: rgb(255 , 255 , 255);';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should not allow missing space before comma', function () {
const source = 'color: rgb(255, 255, 255);';
const expected = [
{
column: 15,
line: 1,
message: 'Commas should be preceded and followed by one space.'
},
{
column: 20,
line: 1,
message: 'Commas should be preceded and followed by one space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should not allow missing space after comma', function () {
const source = 'color: rgb(255 ,255 ,255);';
const expected = [
{
column: 16,
line: 1,
message: 'Commas should be preceded and followed by one space.'
},
{
column: 21,
line: 1,
message: 'Commas should be preceded and followed by one space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should not allow missing space before and after comma', function () {
const source = 'color: rgb(255,255,255);';
const expected = [
{
column: 15,
line: 1,
message: 'Commas should be preceded and followed by one space.'
},
{
column: 19,
line: 1,
message: 'Commas should be preceded and followed by one space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should allow one space before and after comma in mixins', function () {
const source = '.mixin(@margin , @padding) {}';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should not allow missing space before comma in mixins', function () {
const source = '.mixin(@margin, @padding) {}';
const expected = [{
column: 15,
line: 1,
message: 'Commas should be preceded and followed by one space.'
}];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should not allow missing space after comma in mixins', function () {
const source = '.mixin(@margin ,@padding) {}';
const expected = [{
column: 16,
line: 1,
message: 'Commas should be preceded and followed by one space.'
}];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
}); // "both"
describe('when "style" is "none"', function () {
beforeEach(function () {
options = {
style: 'none'
};
});
it('should allow a missing space after comma', function () {
const source = 'color: rgb(255,255,255);';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should not allow one space after comma', function () {
const source = 'color: rgb(255, 255, 255);';
const expected = [
{
column: 15,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
},
{
column: 20,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should not allow one space before comma', function () {
const source = 'color: rgb(255 ,255 ,255);';
const expected = [
{
column: 16,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
},
{
column: 21,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should not allow one space before and after comma', function () {
const source = 'color: rgb(255 , 255 , 255);';
const expected = [
{
column: 16,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
},
{
column: 22,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
}
];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should allow a missing space after comma in mixins', function () {
const source = '.mixin(@margin,@padding) {}';
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
it('should not allow one space after comma in mixins', function () {
const source = '.mixin(@margin, @padding) {}';
const expected = [{
column: 15,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
}];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
it('should not allow one space before comma in mixins', function () {
const source = '.mixin(@margin ,@padding) {}';
const expected = [{
column: 16,
line: 1,
message: 'Commas should not be preceded nor followed by any space.'
}];
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.deep.equal(expected);
});
});
}); // "none"
describe('with invalid "style" value', function () {
beforeEach(function () {
options = {
style: 'invalid'
};
});
it('should throw an error', function () {
const source = 'color: rgb(255 , 255 , 255);';
return spec.parse(source, function (ast) {
const node = ast.root.first;
const lint = spec.linter.lint.bind(null, options, node);
expect(lint).to.throw(Error);
});
});
}); // "invalid"
});
it('should ignore comma in the wrong place', function () {
const source = 'color: rgb(255, 255, 255),';
const options = {
style: 'after'
};
return spec.parse(source, function (ast) {
const result = spec.linter.lint(options, ast.root.first);
expect(result).to.be.undefined;
});
});
});
| {
"pile_set_name": "Github"
} |
@model ProductReviewModel
@{
//page title
ViewBag.Title = T("Admin.Catalog.ProductReviews.EditProductReviewDetails").Text;
}
<form asp-area="@Constants.AreaAdmin" asp-controller="ProductReview" asp-action="Edit" method="post" asp-route-ProductId="@Context.Request.Query["ProductId"]">
<div class="row">
<div class="col-md-12">
<div class="x_panel light form-fit">
<div class="x_title">
<div class="caption">
<i class="fa fa-cube"></i>
@T("Admin.Catalog.ProductReviews.EditProductReviewDetails")
<small><i class="fa fa-arrow-circle-left"></i>@Html.ActionLink(T("Admin.Catalog.ProductReviews.BackToList").Text, "List")</small>
</div>
<div class="actions">
<div class="btn-group btn-group-devided">
<button class="btn btn-success" type="submit" name="save"><i class="fa fa-check"></i> @T("Admin.Common.Save") </button>
<button class="btn btn-success" type="submit" name="save-continue"><i class="fa fa-check-circle"></i> @T("Admin.Common.SaveContinue") </button>
<span id="productreview-delete" class="btn red"><i class="fa fa-trash-o"></i> @T("Admin.Common.Delete")</span>
<vc:admin-widget widget-zone="product_review_details_buttons" additional-data="Model" />
</div>
</div>
</div>
<div class="x_content form">
<partial name="_CreateOrUpdate" model="Model" />
</div>
</div>
</div>
</div>
</form>
<admin-delete-confirmation button-id="productreview-delete"/> | {
"pile_set_name": "Github"
} |
set -ex
cd $SRC_DIR
if [ ! -f setup.py ]; then
ls
echo $(pwd)
exit 1
else
echo "found setup.py in workdir ($(pwd)) OK"
fi
| {
"pile_set_name": "Github"
} |
'use strict';
var toString = Object.prototype.toString;
var toType = function toType(value) {
// Null: 兼容 IE8
return value === null ? 'Null' : toString.call(value).slice(8, -1);
};
/**
* 快速继承默认配置
* @param {Object} options
* @param {?Object} defaults
* @return {Object}
*/
var extend = function extend(target, defaults) {
var object = void 0;
var type = toType(target);
if (type === 'Object') {
object = Object.create(defaults || {});
} else if (type === 'Array') {
object = [].concat(defaults || []);
}
if (object) {
for (var index in target) {
if (Object.hasOwnProperty.call(target, index)) {
object[index] = extend(target[index], object[index]);
}
}
return object;
} else {
return target;
}
};
module.exports = extend; | {
"pile_set_name": "Github"
} |
Bootstrap uses [GitHub's Releases feature](https://github.com/blog/1547-release-your-software) for its changelogs.
See [the Releases section of our GitHub project](https://github.com/twbs/bootstrap/releases) for changelogs for each release version of Bootstrap.
Release announcement posts on [the official Bootstrap blog](http://blog.getbootstrap.com) contain summaries of the most noteworthy changes made in each release.
| {
"pile_set_name": "Github"
} |
/*
* Tencent is pleased to support the open source community by making QMUI_Android available.
*
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qmuiteam.qmui.recyclerView;
import android.animation.Animator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.qmuiteam.qmui.R;
import java.util.ArrayList;
import java.util.List;
public class QMUIRVItemSwipeAction extends RecyclerView.ItemDecoration
implements RecyclerView.OnChildAttachStateChangeListener {
public static final int SWIPE_NONE = 0;
public static final int SWIPE_LEFT = 1;
public static final int SWIPE_RIGHT = 2;
public static final int SWIPE_UP = 3;
public static final int SWIPE_DOWN = 4;
public static final int ANIMATION_TYPE_SWIPE_SUCCESS = 1;
public static final int ANIMATION_TYPE_SWIPE_CANCEL = 2;
public static final int ANIMATION_TYPE_SWIPE_ACTION = 3;
private static final int ACTIVE_POINTER_ID_NONE = -1;
private static final int PIXELS_PER_SECOND = 1000;
private static final int SWIPE_TRIGGERED_IMMEDIATELY = -1;
private static final String TAG = "QMUIRVItemSwipeAction";
private static final boolean DEBUG = false;
/**
* Views, whose state should be cleared after they are detached from RecyclerView.
* This is necessary after swipe dismissing an item. We wait until animator finishes its job
* to clean these views.
*/
final List<View> mPendingCleanup = new ArrayList<>();
/**
* Re-use array to calculate dx dy for a ViewHolder
*/
private final float[] mTmpPosition = new float[2];
/**
* The reference coordinates for the action start. For drag & drop, this is the time long
* press is completed vs for swipe, this is the initial touch point.
*/
float mInitialTouchX;
float mInitialTouchY;
long mDownTimeMillis = 0;
/**
* Set when ItemTouchHelper is assigned to a RecyclerView.
*/
private float mSwipeEscapeVelocity;
/**
* Set when ItemTouchHelper is assigned to a RecyclerView.
*/
private float mMaxSwipeVelocity;
/**
* The diff between the last event and initial touch.
*/
float mDx;
float mDy;
/**
* The pointer we are tracking.
*/
int mActivePointerId = ACTIVE_POINTER_ID_NONE;
/**
* When a View is swiped and needs to go back to where it was, we create a Recover
* Animation and animate it to its location using this custom Animator, instead of using
* framework Animators.
* Using framework animators has the side effect of clashing with ItemAnimator, creating
* jumpy UIs.
*/
List<RecoverAnimation> mRecoverAnimations = new ArrayList<>();
private int mSlop;
RecyclerView mRecyclerView;
/**
* Used for detecting fling swipe
*/
VelocityTracker mVelocityTracker;
private long mPressTimeToSwipe = SWIPE_TRIGGERED_IMMEDIATELY;
/**
* The coordinates of the selected view at the time it is selected. We record these values
* when action starts so that we can consistently position it even if LayoutManager moves the
* View.
*/
float mSelectedStartX;
float mSelectedStartY;
int mSwipeDirection;
private MotionEvent mCurrentDownEvent;
private Runnable mLongPressToSwipe = new Runnable() {
@Override
public void run() {
if (mCurrentDownEvent != null) {
final int activePointerIndex = mCurrentDownEvent.findPointerIndex(mActivePointerId);
if (activePointerIndex >= 0) {
checkSelectForSwipe(mCurrentDownEvent.getAction(), mCurrentDownEvent, activePointerIndex, true);
}
}
}
};
/**
* Currently selected view holder
*/
RecyclerView.ViewHolder mSelected = null;
private final RecyclerView.OnItemTouchListener mOnItemTouchListener = new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView recyclerView,
@NonNull MotionEvent event) {
if (DEBUG) {
Log.d(TAG, "intercept: x:" + event.getX() + ",y:" + event.getY() + ", " + event);
}
final int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
if (mCurrentDownEvent != null) {
mCurrentDownEvent.recycle();
}
mCurrentDownEvent = MotionEvent.obtain(event);
if (mPressTimeToSwipe > 0 && mSelected == null) {
recyclerView.postDelayed(mLongPressToSwipe, mPressTimeToSwipe);
}
mActivePointerId = event.getPointerId(0);
mInitialTouchX = event.getX();
mInitialTouchY = event.getY();
obtainVelocityTracker();
mDownTimeMillis = System.currentTimeMillis();
if (mSelected == null) {
final RecoverAnimation animation = findAnimation(event);
if (animation != null) {
mInitialTouchX -= animation.mX;
mInitialTouchY -= animation.mY;
endRecoverAnimation(animation.mViewHolder, true);
if (mPendingCleanup.remove(animation.mViewHolder.itemView)) {
mCallback.clearView(mRecyclerView, animation.mViewHolder);
}
select(animation.mViewHolder);
updateDxDy(event, mSwipeDirection, 0);
}
} else {
if (mSelected instanceof QMUISwipeViewHolder) {
QMUISwipeViewHolder swipeViewHolder = (QMUISwipeViewHolder) mSelected;
boolean isDownToAction = swipeViewHolder.checkDown(mInitialTouchX, mInitialTouchY);
if (!isDownToAction) {
if (hitTest(mSelected.itemView,
mInitialTouchX, mInitialTouchY,
mSelectedStartX + mDx, mSelectedStartY + mDy)) {
mInitialTouchX -= mDx;
mInitialTouchY -= mDy;
} else {
select(null);
return true;
}
} else {
mInitialTouchX -= mDx;
mInitialTouchY -= mDy;
}
}
}
} else if (action == MotionEvent.ACTION_CANCEL) {
mActivePointerId = ACTIVE_POINTER_ID_NONE;
mRecyclerView.removeCallbacks(mLongPressToSwipe);
select(null);
} else if (action == MotionEvent.ACTION_UP) {
mRecyclerView.removeCallbacks(mLongPressToSwipe);
handleActionUp(event.getX(), event.getY(), mSlop);
mActivePointerId = ACTIVE_POINTER_ID_NONE;
} else if (mActivePointerId != ACTIVE_POINTER_ID_NONE) {
// in a non scroll orientation, if distance change is above threshold, we
// can select the item
final int index = event.findPointerIndex(mActivePointerId);
if (DEBUG) {
Log.d(TAG, "pointer index " + index);
}
if (index >= 0) {
checkSelectForSwipe(action, event, index, false);
}
}
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(event);
}
return mSelected != null;
}
@Override
public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent event) {
if (DEBUG) {
Log.d(TAG,
"on touch: x:" + mInitialTouchX + ",y:" + mInitialTouchY + ", :" + event);
}
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(event);
}
if (mActivePointerId == ACTIVE_POINTER_ID_NONE) {
return;
}
final int action = event.getActionMasked();
final int activePointerIndex = event.findPointerIndex(mActivePointerId);
if (activePointerIndex >= 0) {
checkSelectForSwipe(action, event, activePointerIndex, false);
}
RecyclerView.ViewHolder viewHolder = mSelected;
if (viewHolder == null) {
return;
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
// Find the index of the active pointer and fetch its position
if (activePointerIndex >= 0) {
updateDxDy(event, mSwipeDirection, activePointerIndex);
mRecyclerView.invalidate();
final float x = event.getX(activePointerIndex);
final float y = event.getY(activePointerIndex);
if (Math.abs(x - mInitialTouchX) > mSlop ||
Math.abs(y - mInitialTouchY) > mSlop) {
mRecyclerView.removeCallbacks(mLongPressToSwipe);
}
}
break;
}
case MotionEvent.ACTION_CANCEL:
mRecyclerView.removeCallbacks(mLongPressToSwipe);
select(null);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
mActivePointerId = ACTIVE_POINTER_ID_NONE;
break;
case MotionEvent.ACTION_UP:
mRecyclerView.removeCallbacks(mLongPressToSwipe);
handleActionUp(event.getX(), event.getY(), mSlop);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
mActivePointerId = ACTIVE_POINTER_ID_NONE;
break;
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = event.getActionIndex();
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = event.getPointerId(newPointerIndex);
updateDxDy(event, mSwipeDirection, pointerIndex);
}
break;
}
}
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (!disallowIntercept) {
return;
}
select(null);
}
};
private Callback mCallback;
private boolean mSwipeDeleteWhenOnlyOneAction = false;
public QMUIRVItemSwipeAction(boolean swipeDeleteWhenOnlyOneAction, Callback callback) {
mCallback = callback;
mSwipeDeleteWhenOnlyOneAction = swipeDeleteWhenOnlyOneAction;
}
/**
* Attaches the ItemTouchHelper to the provided RecyclerView. If TouchHelper is already
* attached to a RecyclerView, it will first detach from the previous one. You can call this
* method with {@code null} to detach it from the current RecyclerView.
*
* @param recyclerView The RecyclerView instance to which you want to add this helper or
* {@code null} if you want to remove ItemTouchHelper from the current
* RecyclerView.
*/
public void attachToRecyclerView(@Nullable RecyclerView recyclerView) {
if (mRecyclerView == recyclerView) {
return; // nothing to do
}
if (mRecyclerView != null) {
destroyCallbacks();
}
mRecyclerView = recyclerView;
if (recyclerView != null) {
final Resources resources = recyclerView.getResources();
mSwipeEscapeVelocity = resources.getDimension(R.dimen.qmui_rv_swipe_action_escape_velocity);
mMaxSwipeVelocity = resources.getDimension(R.dimen.qmui_rv_swipe_action_escape_max_velocity);
setupCallbacks();
}
}
public void setPressTimeToSwipe(long pressTimeToSwipe) {
mPressTimeToSwipe = pressTimeToSwipe;
}
private void setupCallbacks() {
ViewConfiguration vc = ViewConfiguration.get(mRecyclerView.getContext());
mSlop = vc.getScaledTouchSlop();
mRecyclerView.addItemDecoration(this);
mRecyclerView.addOnItemTouchListener(mOnItemTouchListener);
mRecyclerView.addOnChildAttachStateChangeListener(this);
}
private void destroyCallbacks() {
mRecyclerView.removeItemDecoration(this);
mRecyclerView.removeOnItemTouchListener(mOnItemTouchListener);
mRecyclerView.removeOnChildAttachStateChangeListener(this);
// clean all attached
final int recoverAnimSize = mRecoverAnimations.size();
for (int i = recoverAnimSize - 1; i >= 0; i--) {
final RecoverAnimation recoverAnimation = mRecoverAnimations.get(0);
mCallback.clearView(mRecyclerView, recoverAnimation.mViewHolder);
}
mRecoverAnimations.clear();
releaseVelocityTracker();
}
@Override
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
float dx = 0, dy = 0;
if (mSelected != null) {
getSelectedDxDy(mTmpPosition);
dx = mTmpPosition[0];
dy = mTmpPosition[1];
}
mCallback.onDrawOver(c, parent, mSelected, mRecoverAnimations, dx, dy);
}
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
float dx = 0, dy = 0;
if (mSelected != null) {
getSelectedDxDy(mTmpPosition);
dx = mTmpPosition[0];
dy = mTmpPosition[1];
}
mCallback.onDraw(c, parent, mSelected, mRecoverAnimations, dx, dy, mSwipeDirection);
}
@Override
public void onChildViewAttachedToWindow(@NonNull View view) {
}
@Override
public void onChildViewDetachedFromWindow(@NonNull View view) {
final RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(view);
if (holder == null) {
return;
}
if (mSelected != null && holder == mSelected) {
select(null);
} else {
endRecoverAnimation(holder, false); // this may push it into pending cleanup list.
if (mPendingCleanup.remove(holder.itemView)) {
mCallback.clearView(mRecyclerView, holder);
}
}
}
void updateDxDy(MotionEvent ev, int swipeDirection, int pointerIndex) {
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
// Calculate the distance moved
if (swipeDirection == SWIPE_RIGHT) {
mDx = Math.max(0, x - mInitialTouchX);
mDy = 0;
} else if (swipeDirection == SWIPE_LEFT) {
mDx = Math.min(0, x - mInitialTouchX);
mDy = 0;
} else if (swipeDirection == SWIPE_DOWN) {
mDx = 0;
mDy = Math.max(0, y - mInitialTouchY);
} else if (swipeDirection == SWIPE_UP) {
mDx = 0;
mDy = Math.min(0, y - mInitialTouchY);
}
}
/**
* Checks whether we should select a View for swiping.
*/
void checkSelectForSwipe(int action, MotionEvent motionEvent, int pointerIndex, boolean isLongPressToSwipe) {
if (mSelected != null || (mPressTimeToSwipe == SWIPE_TRIGGERED_IMMEDIATELY && action != MotionEvent.ACTION_MOVE)) {
return;
}
if (mRecyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
return;
}
final RecyclerView.ViewHolder vh = findSwipedView(motionEvent, isLongPressToSwipe);
if (vh == null) {
return;
}
int swipeDirection = mCallback.getSwipeDirection(mRecyclerView, vh);
if (swipeDirection == SWIPE_NONE) {
return;
}
if (mPressTimeToSwipe == SWIPE_TRIGGERED_IMMEDIATELY) {
// mDx and mDy are only set in allowed directions. We use custom x/y here instead of
// updateDxDy to avoid swiping if user moves more in the other direction
final float x = motionEvent.getX(pointerIndex);
final float y = motionEvent.getY(pointerIndex);
// Calculate the distance moved
final float dx = x - mInitialTouchX;
final float dy = y - mInitialTouchY;
// swipe target is chose w/o applying flags so it does not really check if swiping in that
// direction is allowed. This why here, we use mDx mDy to check slope value again.
final float absDx = Math.abs(dx);
final float absDy = Math.abs(dy);
if (swipeDirection == SWIPE_LEFT) {
if (absDx < mSlop || dx >= 0) {
return;
}
} else if (swipeDirection == SWIPE_RIGHT) {
if (absDx < mSlop || dx <= 0) {
return;
}
} else if (swipeDirection == SWIPE_UP) {
if (absDy < mSlop || dy >= 0) {
return;
}
} else if (swipeDirection == SWIPE_DOWN) {
if (absDy < mSlop || dy <= 0) {
return;
}
}
} else {
if (mPressTimeToSwipe >= System.currentTimeMillis() - mDownTimeMillis) {
return;
}
}
mRecyclerView.removeCallbacks(mLongPressToSwipe);
mDx = mDy = 0f;
mActivePointerId = motionEvent.getPointerId(0);
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL);
vh.itemView.dispatchTouchEvent(cancelEvent);
cancelEvent.recycle();
select(vh);
}
public void clear() {
select(null, false);
}
void handleActionUp(float x, float y, int touchSlop) {
if (mSelected != null) {
if (mSelected instanceof QMUISwipeViewHolder) {
QMUISwipeViewHolder swipeViewHolder = (QMUISwipeViewHolder) mSelected;
if (!swipeViewHolder.hasAction()) {
select(null, true);
} else if(swipeViewHolder.mSwipeActions.size() == 1 && mSwipeDeleteWhenOnlyOneAction){
if(mCallback.isOverThreshold(mRecyclerView, mSelected, mDx, mDy, mSwipeDirection)){
select(null, true);
}else{
handleSwipeActionActionUp(swipeViewHolder, x, y, touchSlop);
}
} else {
handleSwipeActionActionUp(swipeViewHolder, x, y, touchSlop);
}
} else {
select(null, true);
}
}
}
void handleSwipeActionActionUp( QMUISwipeViewHolder swipeViewHolder, float x, float y, int touchSlop){
QMUISwipeAction action = swipeViewHolder.checkUp(x, y, touchSlop);
if (action != null) {
mCallback.onClickAction(this, mSelected, action);
swipeViewHolder.clearTouchInfo();
return;
}
swipeViewHolder.clearTouchInfo();
final int swipeDir = checkSwipe(mSelected, mSwipeDirection, true);
if (swipeDir == SWIPE_NONE) {
select(null, true);
} else {
getSelectedDxDy(mTmpPosition);
final float currentTranslateX = mTmpPosition[0];
final float currentTranslateY = mTmpPosition[1];
final float targetTranslateX, targetTranslateY;
switch (swipeDir) {
case SWIPE_LEFT:
targetTranslateY = 0;
targetTranslateX = -swipeViewHolder.mActionTotalWidth;
break;
case SWIPE_RIGHT:
targetTranslateY = 0;
targetTranslateX = swipeViewHolder.mActionTotalWidth;
break;
case SWIPE_UP:
targetTranslateX = 0;
targetTranslateY = -swipeViewHolder.mActionTotalHeight;
break;
case SWIPE_DOWN:
targetTranslateX = 0;
targetTranslateY = swipeViewHolder.mActionTotalHeight;
break;
default:
targetTranslateX = 0;
targetTranslateY = 0;
}
mDx += targetTranslateX - currentTranslateX;
mDy += targetTranslateY - currentTranslateY;
final RecoverAnimation rv = new RecoverAnimation(swipeViewHolder,
currentTranslateX, currentTranslateY,
targetTranslateX, targetTranslateY,
mCallback.getInterpolator(ANIMATION_TYPE_SWIPE_ACTION));
final long duration = mCallback.getAnimationDuration(mRecyclerView,
ANIMATION_TYPE_SWIPE_ACTION,
targetTranslateX - currentTranslateX,
targetTranslateY - currentTranslateY);
rv.setDuration(duration);
mRecoverAnimations.add(rv);
rv.start();
mRecyclerView.invalidate();
}
}
void select(@Nullable RecyclerView.ViewHolder selected) {
select(selected, false);
}
void select(@Nullable RecyclerView.ViewHolder selected, boolean isActionUp) {
if (selected == mSelected) {
return;
}
// prevent duplicate animations
endRecoverAnimation(selected, true);
boolean preventLayout = false;
if (mSelected != null) {
final RecyclerView.ViewHolder prevSelected = mSelected;
if (prevSelected.itemView.getParent() != null) {
endRecoverAnimation(prevSelected, true);
final int swipeDir = isActionUp ? checkSwipe(mSelected, mSwipeDirection, false) : SWIPE_NONE;
getSelectedDxDy(mTmpPosition);
final float currentTranslateX = mTmpPosition[0];
final float currentTranslateY = mTmpPosition[1];
final float targetTranslateX, targetTranslateY;
switch (swipeDir) {
case SWIPE_LEFT:
case SWIPE_RIGHT:
targetTranslateY = 0;
targetTranslateX = Math.signum(mDx) * mRecyclerView.getWidth();
break;
case SWIPE_UP:
case SWIPE_DOWN:
targetTranslateX = 0;
targetTranslateY = Math.signum(mDy) * mRecyclerView.getHeight();
break;
default:
targetTranslateX = 0;
targetTranslateY = 0;
}
final int animType = swipeDir > 0 ? ANIMATION_TYPE_SWIPE_SUCCESS : ANIMATION_TYPE_SWIPE_CANCEL;
if (swipeDir > 0) {
mCallback.onStartSwipeAnimation(mSelected, swipeDir);
}
final RecoverAnimation rv = new RecoverAnimation(prevSelected,
currentTranslateX, currentTranslateY,
targetTranslateX, targetTranslateY,
mCallback.getInterpolator(ANIMATION_TYPE_SWIPE_ACTION)) {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (this.mOverridden) {
return;
}
if (swipeDir == SWIPE_NONE) {
// this is a drag or failed swipe. recover immediately
mCallback.clearView(mRecyclerView, prevSelected);
// full cleanup will happen on onDrawOver
} else {
// wait until remove animation is complete.
mPendingCleanup.add(prevSelected.itemView);
mIsPendingCleanup = true;
if (swipeDir > 0) {
// Animation might be ended by other animators during a layout.
// We defer callback to avoid editing adapter during a layout.
postDispatchSwipe(this, swipeDir);
}
}
}
};
final long duration = mCallback.getAnimationDuration(mRecyclerView, animType,
targetTranslateX - currentTranslateX,
targetTranslateY - currentTranslateY);
rv.setDuration(duration);
mRecoverAnimations.add(rv);
rv.start();
preventLayout = true;
} else {
mCallback.clearView(mRecyclerView, prevSelected);
}
mSelected = null;
}
if (selected != null) {
mSwipeDirection = mCallback.getSwipeDirection(mRecyclerView, selected);
mSelectedStartX = selected.itemView.getLeft();
mSelectedStartY = selected.itemView.getTop();
mSelected = selected;
if (selected instanceof QMUISwipeViewHolder) {
QMUISwipeViewHolder qmuiSwipeViewHolder = (QMUISwipeViewHolder) selected;
qmuiSwipeViewHolder.setup(mSwipeDirection, mSwipeDeleteWhenOnlyOneAction);
}
}
final ViewParent rvParent = mRecyclerView.getParent();
if (rvParent != null) {
rvParent.requestDisallowInterceptTouchEvent(mSelected != null);
}
if (!preventLayout) {
mRecyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout();
}
mCallback.onSelectedChanged(mSelected);
mRecyclerView.invalidate();
}
private void getSelectedDxDy(float[] outPosition) {
if (mSwipeDirection == SWIPE_LEFT || mSwipeDirection == SWIPE_RIGHT) {
outPosition[0] = mSelectedStartX + mDx - mSelected.itemView.getLeft();
} else {
outPosition[0] = mSelected.itemView.getTranslationX();
}
if (mSwipeDirection == SWIPE_UP || mSwipeDirection == SWIPE_DOWN) {
outPosition[1] = mSelectedStartY + mDy - mSelected.itemView.getTop();
} else {
outPosition[1] = mSelected.itemView.getTranslationY();
}
}
void postDispatchSwipe(final RecoverAnimation anim, final int swipeDir) {
// wait until animations are complete.
mRecyclerView.post(new Runnable() {
@Override
public void run() {
if (mRecyclerView != null && mRecyclerView.isAttachedToWindow()
&& !anim.mOverridden
&& anim.mViewHolder.getAdapterPosition() != RecyclerView.NO_POSITION) {
final RecyclerView.ItemAnimator animator = mRecyclerView.getItemAnimator();
// if animator is running or we have other active recover animations, we try
// not to call onSwiped because DefaultItemAnimator is not good at merging
// animations. Instead, we wait and batch.
if ((animator == null || !animator.isRunning(null))
&& !hasRunningRecoverAnim()) {
mCallback.onSwiped(anim.mViewHolder, swipeDir);
} else {
mRecyclerView.post(this);
}
}
}
});
}
boolean hasRunningRecoverAnim() {
final int size = mRecoverAnimations.size();
for (int i = 0; i < size; i++) {
if (!mRecoverAnimations.get(i).mEnded) {
return true;
}
}
return false;
}
private int checkSwipe(RecyclerView.ViewHolder viewHolder, int swipeDirection, boolean checkAction) {
if (swipeDirection == SWIPE_LEFT || swipeDirection == SWIPE_RIGHT) {
final int dirFlag = mDx > 0 ? SWIPE_RIGHT : SWIPE_LEFT;
if (mVelocityTracker != null && mActivePointerId > -1) {
mVelocityTracker.computeCurrentVelocity(PIXELS_PER_SECOND,
mCallback.getSwipeVelocityThreshold(mMaxSwipeVelocity));
final float xVelocity = mVelocityTracker.getXVelocity(mActivePointerId);
final int velDirFlag = xVelocity > 0f ? SWIPE_RIGHT : SWIPE_LEFT;
final float absXVelocity = Math.abs(xVelocity);
if (dirFlag == velDirFlag &&
absXVelocity >= mCallback.getSwipeEscapeVelocity(mSwipeEscapeVelocity)) {
return velDirFlag;
}
}
float threshold;
if (checkAction && viewHolder instanceof QMUISwipeViewHolder) {
threshold = ((QMUISwipeViewHolder) viewHolder).mActionTotalWidth;
} else {
threshold = mRecyclerView.getWidth() * mCallback.getSwipeThreshold(viewHolder);
}
if (Math.abs(mDx) >= threshold) {
return dirFlag;
}
} else if (swipeDirection == SWIPE_UP || swipeDirection == SWIPE_DOWN) {
final int dirFlag = mDy > 0 ? SWIPE_DOWN : SWIPE_UP;
if (mVelocityTracker != null && mActivePointerId > -1) {
mVelocityTracker.computeCurrentVelocity(PIXELS_PER_SECOND,
mCallback.getSwipeVelocityThreshold(mMaxSwipeVelocity));
final float yVelocity = mVelocityTracker.getYVelocity(mActivePointerId);
final int velDirFlag = yVelocity > 0f ? SWIPE_DOWN : SWIPE_UP;
final float absYVelocity = Math.abs(yVelocity);
if (velDirFlag == dirFlag &&
absYVelocity >= mCallback.getSwipeEscapeVelocity(mSwipeEscapeVelocity)) {
return velDirFlag;
}
}
float threshold;
if (checkAction && viewHolder instanceof QMUISwipeViewHolder) {
threshold = ((QMUISwipeViewHolder) viewHolder).mActionTotalHeight;
} else {
threshold = mRecyclerView.getHeight() * mCallback.getSwipeThreshold(viewHolder);
}
if (Math.abs(mDy) >= threshold) {
return dirFlag;
}
}
return SWIPE_NONE;
}
@Nullable
private RecyclerView.ViewHolder findSwipedView(MotionEvent motionEvent, boolean isLongPressToSwipe) {
final RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager();
if (mActivePointerId == ACTIVE_POINTER_ID_NONE || lm == null) {
return null;
}
if (isLongPressToSwipe) {
View child = findChildView(motionEvent);
if (child == null) {
return null;
}
return mRecyclerView.getChildViewHolder(child);
}
final int pointerIndex = motionEvent.findPointerIndex(mActivePointerId);
final float dx = motionEvent.getX(pointerIndex) - mInitialTouchX;
final float dy = motionEvent.getY(pointerIndex) - mInitialTouchY;
final float absDx = Math.abs(dx);
final float absDy = Math.abs(dy);
if (absDx < mSlop && absDy < mSlop) {
return null;
}
if (absDx > absDy && lm.canScrollHorizontally()) {
return null;
} else if (absDy > absDx && lm.canScrollVertically()) {
return null;
}
View child = findChildView(motionEvent);
if (child == null) {
return null;
}
return mRecyclerView.getChildViewHolder(child);
}
void endRecoverAnimation(RecyclerView.ViewHolder viewHolder, boolean override) {
final int recoverAnimSize = mRecoverAnimations.size();
for (int i = recoverAnimSize - 1; i >= 0; i--) {
final RecoverAnimation anim = mRecoverAnimations.get(i);
if (anim.mViewHolder == viewHolder) {
anim.mOverridden |= override;
if (!anim.mEnded) {
anim.cancel();
}
mRecoverAnimations.remove(i);
return;
}
}
}
View findChildView(MotionEvent event) {
// first check elevated views, if none, then call RV
final float x = event.getX();
final float y = event.getY();
if (mSelected != null) {
final View selectedView = mSelected.itemView;
if (hitTest(selectedView, x, y, mSelectedStartX + mDx, mSelectedStartY + mDy)) {
return selectedView;
}
}
for (int i = mRecoverAnimations.size() - 1; i >= 0; i--) {
final RecoverAnimation anim = mRecoverAnimations.get(i);
final View view = anim.mViewHolder.itemView;
if (hitTest(view, x, y, view.getX(), view.getY())) {
return view;
}
}
return mRecyclerView.findChildViewUnder(x, y);
}
@Nullable
RecoverAnimation findAnimation(MotionEvent event) {
if (mRecoverAnimations.isEmpty()) {
return null;
}
View target = findChildView(event);
for (int i = mRecoverAnimations.size() - 1; i >= 0; i--) {
final RecoverAnimation anim = mRecoverAnimations.get(i);
if (anim.mViewHolder.itemView == target) {
return anim;
}
}
return null;
}
void obtainVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
}
mVelocityTracker = VelocityTracker.obtain();
}
private void releaseVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private static boolean hitTest(View child, float x, float y, float left, float top) {
return x >= left
&& x <= left + child.getWidth()
&& y >= top
&& y <= top + child.getHeight();
}
private static class RecoverAnimation implements Animator.AnimatorListener {
final float mStartDx;
final float mStartDy;
final float mTargetX;
final float mTargetY;
final RecyclerView.ViewHolder mViewHolder;
private final ValueAnimator mValueAnimator;
boolean mIsPendingCleanup;
float mX;
float mY;
// if user starts touching a recovering view, we put it into interaction mode again,
// instantly.
boolean mOverridden = false;
boolean mEnded = false;
private float mFraction;
RecoverAnimation(RecyclerView.ViewHolder viewHolder,
float startDx, float startDy, float targetX, float targetY,
TimeInterpolator interpolator) {
mViewHolder = viewHolder;
mStartDx = startDx;
mStartDy = startDy;
mTargetX = targetX;
mTargetY = targetY;
mValueAnimator = ValueAnimator.ofFloat(0f, 1f);
mValueAnimator.addUpdateListener(
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setFraction(animation.getAnimatedFraction());
}
});
mValueAnimator.setTarget(viewHolder.itemView);
mValueAnimator.addListener(this);
mValueAnimator.setInterpolator(interpolator);
setFraction(0f);
}
public void setDuration(long duration) {
mValueAnimator.setDuration(duration);
}
public void start() {
mViewHolder.setIsRecyclable(false);
mValueAnimator.start();
}
public void cancel() {
mValueAnimator.cancel();
}
public void setFraction(float fraction) {
mFraction = fraction;
}
/**
* We run updates on onDraw method but use the fraction from animator callback.
* This way, we can sync translate x/y values w/ the animators to avoid one-off frames.
*/
public void update() {
if (mStartDx == mTargetX) {
mX = mViewHolder.itemView.getTranslationX();
} else {
mX = mStartDx + mFraction * (mTargetX - mStartDx);
}
if (mStartDy == mTargetY) {
mY = mViewHolder.itemView.getTranslationY();
} else {
mY = mStartDy + mFraction * (mTargetY - mStartDy);
}
}
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (!mEnded) {
mViewHolder.setIsRecyclable(true);
}
mEnded = true;
}
@Override
public void onAnimationCancel(Animator animation) {
setFraction(1f); //make sure we recover the view's state.
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
public static abstract class Callback {
public static final int DEFAULT_SWIPE_ANIMATION_DURATION = 250;
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
View view = viewHolder.itemView;
view.setTranslationX(0);
view.setTranslationY(0);
if (viewHolder instanceof QMUISwipeViewHolder) {
((QMUISwipeViewHolder) viewHolder).clearTouchInfo();
}
}
public int getSwipeDirection(@NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder) {
return SWIPE_NONE;
}
public void onStartSwipeAnimation(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
return .5f;
}
public float getSwipeEscapeVelocity(float defaultValue) {
return defaultValue;
}
public float getSwipeVelocityThreshold(float defaultValue) {
return defaultValue;
}
public long getAnimationDuration(@NonNull RecyclerView recyclerView, int animationType,
float animateDx, float animateDy) {
return DEFAULT_SWIPE_ANIMATION_DURATION;
}
public void onSelectedChanged(RecyclerView.ViewHolder selected) {
}
public void onClickAction(QMUIRVItemSwipeAction swipeAction, RecyclerView.ViewHolder selected, QMUISwipeAction action) {
}
public TimeInterpolator getInterpolator(int animationType) {
return null;
}
void onDraw(Canvas c, RecyclerView parent, RecyclerView.ViewHolder selected,
List<RecoverAnimation> recoverAnimationList, float dX, float dY, int swipeDirection) {
final int recoverAnimSize = recoverAnimationList.size();
for (int i = 0; i < recoverAnimSize; i++) {
final RecoverAnimation anim = recoverAnimationList.get(i);
anim.update();
if (anim.mViewHolder == selected) {
dX = anim.mX;
dY = anim.mY;
} else {
final int count = c.save();
onChildDraw(c, parent, anim.mViewHolder, anim.mX, anim.mY, false, swipeDirection);
c.restoreToCount(count);
}
}
if (selected != null) {
final int count = c.save();
onChildDraw(c, parent, selected, dX, dY, true, swipeDirection);
c.restoreToCount(count);
}
}
void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.ViewHolder selected,
List<RecoverAnimation> recoverAnimationList, float dX, float dY) {
final int recoverAnimSize = recoverAnimationList.size();
for (int i = 0; i < recoverAnimSize; i++) {
final RecoverAnimation anim = recoverAnimationList.get(i);
final int count = c.save();
onChildDrawOver(c, parent, anim.mViewHolder, anim.mX, anim.mY, false);
c.restoreToCount(count);
}
if (selected != null) {
final int count = c.save();
onChildDrawOver(c, parent, selected, dX, dY, true);
c.restoreToCount(count);
}
boolean hasRunningAnimation = false;
for (int i = recoverAnimSize - 1; i >= 0; i--) {
final RecoverAnimation anim = recoverAnimationList.get(i);
if (anim.mEnded && !anim.mIsPendingCleanup) {
recoverAnimationList.remove(i);
} else if (!anim.mEnded) {
hasRunningAnimation = true;
}
}
if (hasRunningAnimation) {
parent.invalidate();
}
}
public void onChildDrawOver(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY,
boolean isCurrentlyActive) {
}
protected boolean isOverThreshold(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dx, float dy, int swipeDirection) {
if (swipeDirection == SWIPE_LEFT || swipeDirection == SWIPE_RIGHT) {
return Math.abs(dx) >= recyclerView.getWidth() * getSwipeThreshold(viewHolder);
}
return Math.abs(dy) >= recyclerView.getHeight() * getSwipeThreshold(viewHolder);
}
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY,
boolean isCurrentlyActive, int swipeDirection) {
View view = viewHolder.itemView;
view.setTranslationX(dX);
view.setTranslationY(dY);
if (viewHolder instanceof QMUISwipeViewHolder) {
if (swipeDirection != SWIPE_NONE) {
((QMUISwipeViewHolder) viewHolder).draw(c, isOverThreshold(recyclerView, viewHolder, dX, dY, swipeDirection), dX, dY);
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
{
"id": "https://schema.management.azure.com/schemas/2019-04-30/Microsoft.ContainerService.json#",
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Microsoft.ContainerService",
"description": "Microsoft ContainerService Resource Types",
"resourceDefinitions": {
"openShiftManagedClusters": {
"type": "object",
"properties": {
"apiVersion": {
"type": "string",
"enum": [
"2019-04-30"
]
},
"location": {
"type": "string",
"description": "Resource location"
},
"name": {
"type": "string",
"description": "The name of the OpenShift managed cluster resource."
},
"plan": {
"oneOf": [
{
"$ref": "#/definitions/PurchasePlan"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Used for establishing the purchase context of any 3rd Party artifact through MarketPlace."
},
"properties": {
"oneOf": [
{
"$ref": "#/definitions/OpenShiftManagedClusterProperties"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Properties of the OpenShift managed cluster."
},
"tags": {
"oneOf": [
{
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {}
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Resource tags"
},
"type": {
"type": "string",
"enum": [
"Microsoft.ContainerService/openShiftManagedClusters"
]
}
},
"required": [
"apiVersion",
"location",
"name",
"properties",
"type"
],
"description": "Microsoft.ContainerService/openShiftManagedClusters"
}
},
"definitions": {
"NetworkProfile": {
"type": "object",
"properties": {
"peerVnetId": {
"type": "string",
"description": "CIDR of the Vnet to peer."
},
"vnetCidr": {
"type": "string",
"default": "10.0.0.0/8",
"description": "CIDR for the OpenShift Vnet."
},
"vnetId": {
"type": "string",
"description": "ID of the Vnet created for OSA cluster."
}
},
"description": "Represents the OpenShift networking configuration"
},
"OpenShiftManagedClusterAADIdentityProvider": {
"type": "object",
"properties": {
"clientId": {
"type": "string",
"description": "The clientId password associated with the provider."
},
"customerAdminGroupId": {
"type": "string",
"description": "The groupId to be granted cluster admin role."
},
"kind": {
"type": "string",
"enum": [
"AADIdentityProvider"
]
},
"secret": {
"type": "string",
"description": "The secret password associated with the provider."
},
"tenantId": {
"type": "string",
"description": "The tenantId associated with the provider."
}
},
"required": [
"kind"
],
"description": "Defines the Identity provider for MS AAD."
},
"OpenShiftManagedClusterAgentPoolProfile": {
"type": "object",
"properties": {
"count": {
"oneOf": [
{
"type": "integer"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Number of agents (VMs) to host docker containers."
},
"name": {
"type": "string",
"description": "Unique name of the pool profile in the context of the subscription and resource group."
},
"osType": {
"oneOf": [
{
"type": "string",
"enum": [
"Linux",
"Windows"
]
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."
},
"role": {
"oneOf": [
{
"type": "string",
"enum": [
"compute",
"infra"
]
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Define the role of the AgentPoolProfile."
},
"subnetCidr": {
"type": "string",
"default": "10.0.0.0/24",
"description": "Subnet CIDR for the peering."
},
"vmSize": {
"oneOf": [
{
"type": "string",
"enum": [
"Standard_D2s_v3",
"Standard_D4s_v3",
"Standard_D8s_v3",
"Standard_D16s_v3",
"Standard_D32s_v3",
"Standard_D64s_v3",
"Standard_DS4_v2",
"Standard_DS5_v2",
"Standard_F8s_v2",
"Standard_F16s_v2",
"Standard_F32s_v2",
"Standard_F64s_v2",
"Standard_F72s_v2",
"Standard_F8s",
"Standard_F16s",
"Standard_E4s_v3",
"Standard_E8s_v3",
"Standard_E16s_v3",
"Standard_E20s_v3",
"Standard_E32s_v3",
"Standard_E64s_v3",
"Standard_GS2",
"Standard_GS3",
"Standard_GS4",
"Standard_GS5",
"Standard_DS12_v2",
"Standard_DS13_v2",
"Standard_DS14_v2",
"Standard_DS15_v2",
"Standard_L4s",
"Standard_L8s",
"Standard_L16s",
"Standard_L32s"
]
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Size of agent VMs."
}
},
"required": [
"count",
"name",
"vmSize"
],
"description": "Defines the configuration of the OpenShift cluster VMs."
},
"OpenShiftManagedClusterAuthProfile": {
"type": "object",
"properties": {
"identityProviders": {
"oneOf": [
{
"type": "array",
"items": {
"$ref": "#/definitions/OpenShiftManagedClusterIdentityProvider"
}
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Type of authentication profile to use."
}
},
"description": "Defines all possible authentication profiles for the OpenShift cluster."
},
"OpenShiftManagedClusterBaseIdentityProvider": {
"type": "object",
"oneOf": [
{
"$ref": "#/definitions/OpenShiftManagedClusterAADIdentityProvider"
}
],
"properties": {},
"description": "Structure for any Identity provider."
},
"OpenShiftManagedClusterIdentityProvider": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the provider."
},
"provider": {
"oneOf": [
{
"$ref": "#/definitions/OpenShiftManagedClusterBaseIdentityProvider"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Structure for any Identity provider."
}
},
"description": "Defines the configuration of the identity providers to be used in the OpenShift cluster."
},
"OpenShiftManagedClusterMasterPoolProfile": {
"type": "object",
"properties": {
"count": {
"oneOf": [
{
"type": "integer"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Number of masters (VMs) to host docker containers. The default value is 3."
},
"name": {
"type": "string",
"description": "Unique name of the master pool profile in the context of the subscription and resource group."
},
"osType": {
"oneOf": [
{
"type": "string",
"enum": [
"Linux",
"Windows"
]
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."
},
"subnetCidr": {
"type": "string",
"description": "Subnet CIDR for the peering."
},
"vmSize": {
"oneOf": [
{
"type": "string",
"enum": [
"Standard_D2s_v3",
"Standard_D4s_v3",
"Standard_D8s_v3",
"Standard_D16s_v3",
"Standard_D32s_v3",
"Standard_D64s_v3",
"Standard_DS4_v2",
"Standard_DS5_v2",
"Standard_F8s_v2",
"Standard_F16s_v2",
"Standard_F32s_v2",
"Standard_F64s_v2",
"Standard_F72s_v2",
"Standard_F8s",
"Standard_F16s",
"Standard_E4s_v3",
"Standard_E8s_v3",
"Standard_E16s_v3",
"Standard_E20s_v3",
"Standard_E32s_v3",
"Standard_E64s_v3",
"Standard_GS2",
"Standard_GS3",
"Standard_GS4",
"Standard_GS5",
"Standard_DS12_v2",
"Standard_DS13_v2",
"Standard_DS14_v2",
"Standard_DS15_v2",
"Standard_L4s",
"Standard_L8s",
"Standard_L16s",
"Standard_L32s"
]
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Size of agent VMs."
}
},
"required": [
"count",
"vmSize"
],
"description": "OpenShiftManagedClusterMaterPoolProfile contains configuration for OpenShift master VMs."
},
"OpenShiftManagedClusterProperties": {
"type": "object",
"properties": {
"agentPoolProfiles": {
"oneOf": [
{
"type": "array",
"items": {
"$ref": "#/definitions/OpenShiftManagedClusterAgentPoolProfile"
}
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Configuration of OpenShift cluster VMs."
},
"authProfile": {
"oneOf": [
{
"$ref": "#/definitions/OpenShiftManagedClusterAuthProfile"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Defines all possible authentication profiles for the OpenShift cluster."
},
"masterPoolProfile": {
"oneOf": [
{
"$ref": "#/definitions/OpenShiftManagedClusterMasterPoolProfile"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "OpenShiftManagedClusterMaterPoolProfile contains configuration for OpenShift master VMs."
},
"networkProfile": {
"oneOf": [
{
"$ref": "#/definitions/NetworkProfile"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Represents the OpenShift networking configuration"
},
"openShiftVersion": {
"type": "string",
"description": "Version of OpenShift specified when creating the cluster."
},
"routerProfiles": {
"oneOf": [
{
"type": "array",
"items": {
"$ref": "#/definitions/OpenShiftRouterProfile"
}
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Configuration for OpenShift router(s)."
}
},
"required": [
"openShiftVersion"
],
"description": "Properties of the OpenShift managed cluster."
},
"OpenShiftRouterProfile": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the router profile."
}
},
"description": "Represents an OpenShift router"
},
"PurchasePlan": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The plan ID."
},
"product": {
"type": "string",
"description": "Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element."
},
"promotionCode": {
"type": "string",
"description": "The promotion code."
},
"publisher": {
"type": "string",
"description": "The plan ID."
}
},
"description": "Used for establishing the purchase context of any 3rd Party artifact through MarketPlace."
}
}
} | {
"pile_set_name": "Github"
} |
[](https://travis-ci.org/visionmedia/nib)
# Nib
Stylus mixins, utilities, components, and gradient image generation. Don't forget to check out the [documentation](http://visionmedia.github.com/nib/).
## Installation
```bash
$ npm install nib
```
If the image generation features of Nib are desired, such as generating the linear gradient images, install [node-canvas](http://github.com/learnboost/node-canvas):
```bash
$ npm install canvas
```
## JavaScript API
Below is an example of how to utilize nib and stylus with the connect framework (or express).
```javascript
var connect = require('connect')
, stylus = require('stylus')
, nib = require('nib');
var server = connect();
function compile(str, path) {
return stylus(str)
.set('filename', path)
.set('compress', true)
.use(nib());
}
server.use(stylus.middleware({
src: __dirname
, compile: compile
}));
```
## Stylus API
To gain access to everything nib has to offer, simply add:
```css
@import 'nib'
```
Or you may also pick and choose based on the directory structure in `./lib`, for example:
```css
@import 'nib/gradients'
@import 'nib/overflow'
```
to be continued....
## More Information
- Introduction [screencast](http://www.screenr.com/M6a)
## Testing
You will first need to install the dependencies:
```bash
$ npm install -d
```
Run the automated test cases:
```bash
$ npm test
```
For visual testing run the test server:
```bash
$ npm run-script test-server
```
Then visit `localhost:3000` in your browser.
## Contributors
I would love more contributors. And if you have helped out, you are awesome! I want to give a huge thanks to these people:
- [TJ Holowaychuk](https://github.com/visionmedia) (Original Creator)
- [Sean Lang](https://github.com/slang800) (Current Maintainer)
- [Isaac Johnston](https://github.com/superstructor)
- [Everyone Else](https://github.com/visionmedia/nib/contributors)
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.