text
stringlengths 2
100k
| meta
dict |
---|---|
/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <string.h> /* for NULL, strrchr() */
/**
* @date 2014-11-23
* @author Arto Bendiken
* @see http://libc11.org/string/strrchr.html
*/
char*
strrchr(const char* s,
const int c) {
const char* p = NULL;
while (*s != '\0') {
if (*s == (char)c) {
p = s;
}
s++;
}
return (char*)p;
}
| {
"pile_set_name": "Github"
} |
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(76);
/***/ },
/***/ 76:
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _col = __webpack_require__(77);
var _col2 = _interopRequireDefault(_col);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_col2.default.install = function (Vue) {
Vue.component(_col2.default.name, _col2.default);
};
exports.default = _col2.default;
/***/ },
/***/ 77:
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = {
name: 'ElCol',
props: {
span: {
type: Number,
default: 24
},
tag: {
type: String,
default: 'div'
},
offset: Number,
pull: Number,
push: Number,
xs: [Number, Object],
sm: [Number, Object],
md: [Number, Object],
lg: [Number, Object]
},
computed: {
gutter: function gutter() {
var parent = this.$parent;
while (parent && parent.$options.componentName !== 'ElRow') {
parent = parent.$parent;
}
return parent ? parent.gutter : 0;
}
},
render: function render(h) {
var _this = this;
var classList = [];
var style = {};
if (this.gutter) {
style.paddingLeft = this.gutter / 2 + 'px';
style.paddingRight = style.paddingLeft;
}
['span', 'offset', 'pull', 'push'].forEach(function (prop) {
if (_this[prop]) {
classList.push(prop !== 'span' ? 'el-col-' + prop + '-' + _this[prop] : 'el-col-' + _this[prop]);
}
});
['xs', 'sm', 'md', 'lg'].forEach(function (size) {
if (typeof _this[size] === 'number') {
classList.push('el-col-' + size + '-' + _this[size]);
} else if (_typeof(_this[size]) === 'object') {
(function () {
var props = _this[size];
Object.keys(props).forEach(function (prop) {
classList.push(prop !== 'span' ? 'el-col-' + size + '-' + prop + '-' + props[prop] : 'el-col-' + size + '-' + props[prop]);
});
})();
}
});
return h(this.tag, {
class: ['el-col', classList],
style: style
}, this.$slots.default);
}
};
/***/ }
/******/ }); | {
"pile_set_name": "Github"
} |
package com.insthub.BeeFramework;
/*
* ______ ______ ______
* /\ __ \ /\ ___\ /\ ___\
* \ \ __< \ \ __\_ \ \ __\_
* \ \_____\ \ \_____\ \ \_____\
* \/_____/ \/_____/ \/_____/
*
*
* Copyright (c) 2013-2014, {Bee} open source community
* http://www.bee-framework.com
*
*
* 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.
*/
import java.io.File;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import com.baidu.frontia.FrontiaApplication;
import com.external.activeandroid.app.Application;
import com.insthub.BeeFramework.Utils.CustomExceptionHandler;
import com.insthub.BeeFramework.activity.DebugCancelDialogActivity;
import com.insthub.BeeFramework.activity.DebugTabActivity;
import com.insthub.ecmobile.R;
import com.insthub.ecmobile.protocol.SESSION;
public class BeeFrameworkApp extends Application implements OnClickListener{
private static BeeFrameworkApp instance;
private ImageView bugImage;
public Context currContext;
private WindowManager wManager ;
private boolean flag = true;
public Handler messageHandler;
public static BeeFrameworkApp getInstance()
{
if (instance == null) {
instance = new BeeFrameworkApp();
}
return instance;
}
@Override
public void onCreate() {
instance = this;
super.onCreate();
FrontiaApplication.initFrontiaApplication(this);
initConfig();
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + BeeFrameworkConst.LOG_DIR_PATH;
File storePath = new File(path);
storePath.mkdirs();
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
path, null));
}
void initConfig() {
SharedPreferences shared;
shared = this.getSharedPreferences("userInfo", 0);
SESSION.getInstance().uid = shared.getString("uid", "");
SESSION.getInstance().sid = shared.getString("sid", "");
}
public void showBug(final Context context)
{
BeeFrameworkApp.getInstance().currContext = context;
wManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type = LayoutParams.TYPE_PHONE;
wmParams.format = PixelFormat.RGBA_8888;
wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL |
LayoutParams.FLAG_NOT_FOCUSABLE;
wmParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
wmParams.x = 0;
wmParams.y = 0;
wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
if(bugImage != null) { //判断bugImage是否存在,如果存在则移除,必须加在 new ImageView(context) 前面
wManager.removeView(bugImage);
}
bugImage = new ImageView(context);
bugImage.setImageResource(R.drawable.bug);
wManager.addView(bugImage, wmParams);
bugImage.setOnClickListener(this);
bugImage.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
DebugCancelDialogActivity.parentHandler = messageHandler;
Intent intent = new Intent(BeeFrameworkApp.getInstance().currContext,DebugCancelDialogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
flag = false;
return false;
}
});
messageHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
wManager.removeView(bugImage);
bugImage = null; // 必须要把bugImage清空,否则再次进入debug模式会与102行冲突
}
}
};
}
public void onClick(View v) {
if(flag != false) {
Intent intent = new Intent(BeeFrameworkApp.getInstance().currContext,DebugTabActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
flag = true;
}
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) Microsoft Open Technologies, Inc.
* All Rights Reserved
* Licensed under the Apache License, Version 2.0.
* See License.txt in the project root for license information.
******************************************************************************/
#import "MSOrcURLImpl.h"
#import "NSString+NSStringExtensions.h"
@implementation MSOrcURLImpl
@synthesize queryStringParameters = _queryStringParameters;
@synthesize pathComponents = _pathComponents;
@synthesize baseUrl = _baseUrl;
- (instancetype)init {
if (self = [super init]) {
_queryStringParameters = [[NSMutableDictionary alloc] init];
_pathComponents = [[NSMutableArray alloc] init];
}
return self;
}
- (void)setBaseUrl:(NSString *)baseUrl {
NSArray *urlParts = [baseUrl componentsSeparatedByString:@"?"];
_baseUrl = [self removeTrailingSlash:(NSString *)[urlParts objectAtIndex:0]];
if (urlParts.count > 1) {
NSArray *parameters = [(NSString *)[urlParts objectAtIndex:1] componentsSeparatedByString:@"&"];
for (NSString *kv in parameters)
{
NSArray *parameterParts = [kv componentsSeparatedByString:@"="];
[self addQueryStringParameter:[parameterParts objectAtIndex:0]
value:[parameterParts objectAtIndex:1]];
}
}
}
- (void)addQueryStringParameter:(NSString *)name value:(NSString *)value {
NSMutableDictionary *dicc = [[NSMutableDictionary alloc] initWithObjectsAndKeys:value, name, nil];
[dicc addEntriesFromDictionary: self.queryStringParameters];
_queryStringParameters = dicc;
}
- (void)appendPathComponent:(NSString *)value {
NSMutableArray *a = [[NSMutableArray alloc] initWithObjects:value, nil];
[a addObjectsFromArray: self.pathComponents];
_pathComponents = a;
}
- (NSString *)addTrailingSlash:(NSString *)s {
NSMutableString *theString = [[NSMutableString alloc] initWithString:s];
if (![theString hasSuffix:@"/"]) {
[theString appendString:@"/"];
}
return theString;
}
- (NSString *)removeTrailingSlash:(NSString *)s {
if ([s hasSuffix:@"/"]) {
return [s substringWithRange:NSMakeRange(0, s.length-1)];
}
else if ([s hasSuffix:@"%2F"]) {
return [s substringWithRange:NSMakeRange(0, s.length-3)];
}
return s;
}
- (NSString *)toString {
NSMutableString *queryString = [[NSMutableString alloc] initWithFormat:@"%@/", self.baseUrl];
for (NSString *value in self.pathComponents) {
if ([value hasPrefix:@"('"] && [value hasSuffix:@"')"]) {
queryString =[[NSMutableString alloc] initWithString : [self removeTrailingSlash:queryString]];
}
[queryString appendString:[self addTrailingSlash:value] ];
}
if (self.queryStringParameters.allKeys.count > 0) {
[queryString appendString:@"?"];
}
for (NSString *key in self.queryStringParameters.allKeys) {
[queryString appendFormat:@"%@=%@&",[key urlEncode], [[self.queryStringParameters objectForKey:key] urlEncode]];
}
if ([queryString hasSuffix:@"&"]) {
queryString = (NSMutableString *)[queryString substringToIndex:[queryString length]-1];
}
return queryString;
}
@end | {
"pile_set_name": "Github"
} |
// Copyright (c) 2010, Peter Barrett
/*
** Permission to use, copy, modify, and/or distribute this software for
** any purpose with or without fee is hereby granted, provided that the
** above copyright notice and this permission notice appear in all copies.
**
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
** SOFTWARE.
*/
#ifndef __USBCORE_H__
#define __USBCORE_H__
// Standard requests
#define GET_STATUS 0
#define CLEAR_FEATURE 1
#define SET_FEATURE 3
#define SET_ADDRESS 5
#define GET_DESCRIPTOR 6
#define SET_DESCRIPTOR 7
#define GET_CONFIGURATION 8
#define SET_CONFIGURATION 9
#define GET_INTERFACE 10
#define SET_INTERFACE 11
// bmRequestType
#define REQUEST_HOSTTODEVICE 0x00
#define REQUEST_DEVICETOHOST 0x80
#define REQUEST_DIRECTION 0x80
#define REQUEST_STANDARD 0x00
#define REQUEST_CLASS 0x20
#define REQUEST_VENDOR 0x40
#define REQUEST_TYPE 0x60
#define REQUEST_DEVICE 0x00
#define REQUEST_INTERFACE 0x01
#define REQUEST_ENDPOINT 0x02
#define REQUEST_OTHER 0x03
#define REQUEST_RECIPIENT 0x03
#define REQUEST_DEVICETOHOST_CLASS_INTERFACE (REQUEST_DEVICETOHOST + REQUEST_CLASS + REQUEST_INTERFACE)
#define REQUEST_HOSTTODEVICE_CLASS_INTERFACE (REQUEST_HOSTTODEVICE + REQUEST_CLASS + REQUEST_INTERFACE)
// Class requests
#define CDC_SET_LINE_CODING 0x20
#define CDC_GET_LINE_CODING 0x21
#define CDC_SET_CONTROL_LINE_STATE 0x22
#define MSC_RESET 0xFF
#define MSC_GET_MAX_LUN 0xFE
#define HID_GET_REPORT 0x01
#define HID_GET_IDLE 0x02
#define HID_GET_PROTOCOL 0x03
#define HID_SET_REPORT 0x09
#define HID_SET_IDLE 0x0A
#define HID_SET_PROTOCOL 0x0B
// Descriptors
#define USB_DEVICE_DESC_SIZE 18
#define USB_CONFIGUARTION_DESC_SIZE 9
#define USB_INTERFACE_DESC_SIZE 9
#define USB_ENDPOINT_DESC_SIZE 7
#define USB_DEVICE_DESCRIPTOR_TYPE 1
#define USB_CONFIGURATION_DESCRIPTOR_TYPE 2
#define USB_STRING_DESCRIPTOR_TYPE 3
#define USB_INTERFACE_DESCRIPTOR_TYPE 4
#define USB_ENDPOINT_DESCRIPTOR_TYPE 5
#define USB_DEVICE_CLASS_COMMUNICATIONS 0x02
#define USB_DEVICE_CLASS_HUMAN_INTERFACE 0x03
#define USB_DEVICE_CLASS_STORAGE 0x08
#define USB_DEVICE_CLASS_VENDOR_SPECIFIC 0xFF
#define USB_CONFIG_POWERED_MASK 0x40
#define USB_CONFIG_BUS_POWERED 0x80
#define USB_CONFIG_SELF_POWERED 0xC0
#define USB_CONFIG_REMOTE_WAKEUP 0x20
// bMaxPower in Configuration Descriptor
#define USB_CONFIG_POWER_MA(mA) ((mA)/2)
// bEndpointAddress in Endpoint Descriptor
#define USB_ENDPOINT_DIRECTION_MASK 0x80
#define USB_ENDPOINT_OUT(addr) ((addr) | 0x00)
#define USB_ENDPOINT_IN(addr) ((addr) | 0x80)
#define USB_ENDPOINT_TYPE_MASK 0x03
#define USB_ENDPOINT_TYPE_CONTROL 0x00
#define USB_ENDPOINT_TYPE_ISOCHRONOUS 0x01
#define USB_ENDPOINT_TYPE_BULK 0x02
#define USB_ENDPOINT_TYPE_INTERRUPT 0x03
#define TOBYTES(x) ((x) & 0xFF),(((x) >> 8) & 0xFF)
#define CDC_V1_10 0x0110
#define CDC_COMMUNICATION_INTERFACE_CLASS 0x02
#define CDC_CALL_MANAGEMENT 0x01
#define CDC_ABSTRACT_CONTROL_MODEL 0x02
#define CDC_HEADER 0x00
#define CDC_ABSTRACT_CONTROL_MANAGEMENT 0x02
#define CDC_UNION 0x06
#define CDC_CS_INTERFACE 0x24
#define CDC_CS_ENDPOINT 0x25
#define CDC_DATA_INTERFACE_CLASS 0x0A
#define MSC_SUBCLASS_SCSI 0x06
#define MSC_PROTOCOL_BULK_ONLY 0x50
#define HID_HID_DESCRIPTOR_TYPE 0x21
#define HID_REPORT_DESCRIPTOR_TYPE 0x22
#define HID_PHYSICAL_DESCRIPTOR_TYPE 0x23
// Device
typedef struct {
u8 len; // 18
u8 dtype; // 1 USB_DEVICE_DESCRIPTOR_TYPE
u16 usbVersion; // 0x200
u8 deviceClass;
u8 deviceSubClass;
u8 deviceProtocol;
u8 packetSize0; // Packet 0
u16 idVendor;
u16 idProduct;
u16 deviceVersion; // 0x100
u8 iManufacturer;
u8 iProduct;
u8 iSerialNumber;
u8 bNumConfigurations;
} DeviceDescriptor;
// Config
typedef struct {
u8 len; // 9
u8 dtype; // 2
u16 clen; // total length
u8 numInterfaces;
u8 config;
u8 iconfig;
u8 attributes;
u8 maxPower;
} ConfigDescriptor;
// String
// Interface
typedef struct
{
u8 len; // 9
u8 dtype; // 4
u8 number;
u8 alternate;
u8 numEndpoints;
u8 interfaceClass;
u8 interfaceSubClass;
u8 protocol;
u8 iInterface;
} InterfaceDescriptor;
// Endpoint
typedef struct
{
u8 len; // 7
u8 dtype; // 5
u8 addr;
u8 attr;
u16 packetSize;
u8 interval;
} EndpointDescriptor;
// Interface Association Descriptor
// Used to bind 2 interfaces together in CDC compostite device
typedef struct
{
u8 len; // 8
u8 dtype; // 11
u8 firstInterface;
u8 interfaceCount;
u8 functionClass;
u8 funtionSubClass;
u8 functionProtocol;
u8 iInterface;
} IADDescriptor;
// CDC CS interface descriptor
typedef struct
{
u8 len; // 5
u8 dtype; // 0x24
u8 subtype;
u8 d0;
u8 d1;
} CDCCSInterfaceDescriptor;
typedef struct
{
u8 len; // 4
u8 dtype; // 0x24
u8 subtype;
u8 d0;
} CDCCSInterfaceDescriptor4;
typedef struct
{
u8 len;
u8 dtype; // 0x24
u8 subtype; // 1
u8 bmCapabilities;
u8 bDataInterface;
} CMFunctionalDescriptor;
typedef struct
{
u8 len;
u8 dtype; // 0x24
u8 subtype; // 1
u8 bmCapabilities;
} ACMFunctionalDescriptor;
typedef struct
{
// IAD
IADDescriptor iad; // Only needed on compound device
// Control
InterfaceDescriptor cif; //
CDCCSInterfaceDescriptor header;
CMFunctionalDescriptor callManagement; // Call Management
ACMFunctionalDescriptor controlManagement; // ACM
CDCCSInterfaceDescriptor functionalDescriptor; // CDC_UNION
EndpointDescriptor cifin;
// Data
InterfaceDescriptor dif;
EndpointDescriptor in;
EndpointDescriptor out;
} CDCDescriptor;
typedef struct
{
InterfaceDescriptor msc;
EndpointDescriptor in;
EndpointDescriptor out;
} MSCDescriptor;
typedef struct
{
u8 len; // 9
u8 dtype; // 0x21
u8 addr;
u8 versionL; // 0x101
u8 versionH; // 0x101
u8 country;
u8 desctype; // 0x22 report
u8 descLenL;
u8 descLenH;
} HIDDescDescriptor;
typedef struct
{
InterfaceDescriptor hid;
HIDDescDescriptor desc;
EndpointDescriptor in;
} HIDDescriptor;
#define D_DEVICE(_class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs) \
{ 18, 1, 0x200, _class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs }
#define D_CONFIG(_totalLength,_interfaces) \
{ 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED, USB_CONFIG_POWER_MA(500) }
#define D_INTERFACE(_n,_numEndpoints,_class,_subClass,_protocol) \
{ 9, 4, _n, 0, _numEndpoints, _class,_subClass, _protocol, 0 }
#define D_ENDPOINT(_addr,_attr,_packetSize, _interval) \
{ 7, 5, _addr,_attr,_packetSize, _interval }
#define D_IAD(_firstInterface, _count, _class, _subClass, _protocol) \
{ 8, 11, _firstInterface, _count, _class, _subClass, _protocol, 0 }
#define D_HIDREPORT(_descriptorLength) \
{ 9, 0x21, 0x1, 0x1, 0, 1, 0x22, _descriptorLength, 0 }
#define D_CDCCS(_subtype,_d0,_d1) { 5, 0x24, _subtype, _d0, _d1 }
#define D_CDCCS4(_subtype,_d0) { 4, 0x24, _subtype, _d0 }
#endif | {
"pile_set_name": "Github"
} |
//
// IMAppDelegate.m
// IMQuickSearch
//
// Created by Ben Gordon on 12/13/13.
// Copyright (c) 2013 Intermark. All rights reserved.
//
#import "IMAppDelegate.h"
@implementation IMAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
| {
"pile_set_name": "Github"
} |
<div>
<ul>
{% for item in items %}<li>{{ item }}</li>{% endfor %}
</ul>
</div> | {
"pile_set_name": "Github"
} |
/*
* Copyright 2002-2018 the original author or 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
*
* https://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.springframework.test.context.transaction.ejb;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.test.context.transaction.ejb.dao.RequiresNewEjbTxTestEntityDao;
/**
* Concrete subclass of {@link AbstractEjbTxDaoTests} which uses the
* {@link RequiresNewEjbTxTestEntityDao} and sets the default rollback semantics
* for the {@link TransactionalTestExecutionListener} to {@code false} (i.e.,
* <em>commit</em>).
*
* @author Sam Brannen
* @since 4.0.1
*/
@ContextConfiguration("requires-new-tx-config.xml")
@Commit
public class CommitForRequiresNewEjbTxDaoTests extends AbstractEjbTxDaoTests {
/* test methods in superclass */
}
| {
"pile_set_name": "Github"
} |
within Modelica.Mechanics.Rotational.Examples;
model FirstGrounded
"First example: simple drive train with grounded elements"
extends Modelica.Icons.Example;
parameter SI.Torque amplitude=10
"Amplitude of driving torque";
parameter SI.Frequency f=5 "Frequency of driving torque";
parameter SI.Inertia Jmotor(min=0) = 0.1 "Motor inertia";
parameter SI.Inertia Jload(min=0) = 2 "Load inertia";
parameter Real ratio=10 "Gear ratio";
parameter Real damping=10 "Damping in bearing of gear";
Rotational.Components.Fixed fixed annotation (Placement(transformation(
extent={{38,-48},{54,-32}})));
Rotational.Sources.Torque torque(useSupport=false) annotation (Placement(
transformation(extent={{-68,-8},{-52,8}})));
Rotational.Components.Inertia inertia1(J=Jmotor) annotation (Placement(
transformation(extent={{-38,-8},{-22,8}})));
Rotational.Components.IdealGear idealGear(ratio=ratio, useSupport=false)
annotation (Placement(transformation(extent={{-8,-8},{8,8}})));
Rotational.Components.Inertia inertia2(
J=2,
phi(fixed=true, start=0),
w(fixed=true, start=0)) annotation (Placement(transformation(extent={{
22,-8},{38,8}})));
Rotational.Components.Spring spring(c=1.e4, phi_rel(fixed=true))
annotation (Placement(transformation(extent={{52,-8},{68,8}})));
Rotational.Components.Inertia inertia3(J=Jload, w(fixed=true, start=0))
annotation (Placement(transformation(extent={{82,-8},{98,8}})));
Rotational.Components.Damper damper(d=damping) annotation (Placement(
transformation(
origin={46,-22},
extent={{-8,-8},{8,8}},
rotation=270)));
Modelica.Blocks.Sources.Sine sine(amplitude=amplitude, f=f)
annotation (Placement(transformation(extent={{-98,-8},{-82,8}})));
equation
connect(inertia1.flange_b, idealGear.flange_a)
annotation (Line(points={{-22,0},{-8,0}}));
connect(idealGear.flange_b, inertia2.flange_a)
annotation (Line(points={{8,0},{22,0}}));
connect(inertia2.flange_b, spring.flange_a)
annotation (Line(points={{38,0},{52,0}}));
connect(spring.flange_b, inertia3.flange_a)
annotation (Line(points={{68,0},{82,0}}));
connect(damper.flange_a, inertia2.flange_b)
annotation (Line(points={{46,-14},{46,0},{38,0}}));
connect(damper.flange_b, fixed.flange)
annotation (Line(points={{46,-30},{46,-40}}));
connect(sine.y, torque.tau)
annotation (Line(points={{-81.2,0},{-69.6,0}}, color={0,0,127}));
connect(torque.flange, inertia1.flange_a) annotation (Line(
points={{-52,0},{-38,0}}));
annotation (Documentation(info="<html>
<p>The drive train consists of a motor inertia which is driven by
a sine-wave motor torque. Via a gearbox the rotational energy is
transmitted to a load inertia. Elasticity in the gearbox is modeled
by a spring element. A linear damper is used to model the
damping in the gearbox bearing.</p>
<p>Note, that a force component (like the damper of this example)
which is acting between a shaft and the housing has to be fixed
in the housing on one side via component Fixed.</p>
<p>Simulate for 1 second and plot the following variables:<br>
angular velocities of inertias inertia2 and 3: inertia2.w, inertia3.w</p>
</html>"),
experiment(StopTime=1.0, Interval=0.001));
end FirstGrounded;
| {
"pile_set_name": "Github"
} |
# Markdown is broken
I have a lot of scraps of markdown engine oddities that I've collected over the
years. What you see below is slightly messy, but it's what I've managed to
cobble together to illustrate the differences between markdown engines, and
why, if there ever is a markdown specification, it has to be absolutely
thorough. There are a lot more of these little differences I have documented
elsewhere. I know I will find them lingering on my disk one day, but until
then, I'll continue to add whatever strange nonsensical things I find.
Some of these examples may only mention a particular engine compared to marked.
However, the examples with markdown.pl could easily be swapped out for
discount, upskirt, or markdown.js, and you would very easily see even more
inconsistencies.
A lot of this was written when I was very unsatisfied with the inconsistencies
between markdown engines. Please excuse the frustration noticeable in my
writing.
## Examples of markdown's "stupid" list parsing
```
$ markdown.pl
* item1
* item2
text
^D
<ul>
<li><p>item1</p>
<ul>
<li>item2</li>
</ul>
<p><p>text</p></li>
</ul></p>
```
```
$ marked
* item1
* item2
text
^D
<ul>
<li><p>item1</p>
<ul>
<li>item2</li>
</ul>
<p>text</p>
</li>
</ul>
```
Which looks correct to you?
- - -
```
$ markdown.pl
* hello
> world
^D
<p><ul>
<li>hello</p>
<blockquote>
<p>world</li>
</ul></p>
</blockquote>
```
```
$ marked
* hello
> world
^D
<ul>
<li>hello<blockquote>
<p>world</p>
</blockquote>
</li>
</ul>
```
Again, which looks correct to you?
- - -
EXAMPLE:
```
$ markdown.pl
* hello
* world
* hi
code
^D
<ul>
<li>hello
<ul>
<li>world</li>
<li>hi
code</li>
</ul></li>
</ul>
```
The code isn't a code block even though it's after the bullet margin. I know,
lets give it two more spaces, effectively making it 8 spaces past the bullet.
```
$ markdown.pl
* hello
* world
* hi
code
^D
<ul>
<li>hello
<ul>
<li>world</li>
<li>hi
code</li>
</ul></li>
</ul>
```
And, it's still not a code block. Did you also notice that the 3rd item isn't
even its own list? Markdown screws that up too because of its indentation
unaware parsing.
- - -
Let's look at some more examples of markdown's list parsing:
```
$ markdown.pl
* item1
* item2
text
^D
<ul>
<li><p>item1</p>
<ul>
<li>item2</li>
</ul>
<p><p>text</p></li>
</ul></p>
```
Misnested tags.
```
$ marked
* item1
* item2
text
^D
<ul>
<li><p>item1</p>
<ul>
<li>item2</li>
</ul>
<p>text</p>
</li>
</ul>
```
Which looks correct to you?
- - -
```
$ markdown.pl
* hello
> world
^D
<p><ul>
<li>hello</p>
<blockquote>
<p>world</li>
</ul></p>
</blockquote>
```
More misnested tags.
```
$ marked
* hello
> world
^D
<ul>
<li>hello<blockquote>
<p>world</p>
</blockquote>
</li>
</ul>
```
Again, which looks correct to you?
- - -
# Why quality matters - Part 2
``` bash
$ markdown.pl
* hello
> world
^D
<p><ul>
<li>hello</p>
<blockquote>
<p>world</li>
</ul></p>
</blockquote>
```
``` bash
$ sundown # upskirt
* hello
> world
^D
<ul>
<li>hello
> world</li>
</ul>
```
``` bash
$ marked
* hello
> world
^D
<ul><li>hello <blockquote><p>world</p></blockquote></li></ul>
```
Which looks correct to you?
- - -
See: https://github.com/evilstreak/markdown-js/issues/23
``` bash
$ markdown.pl # upskirt/markdown.js/discount
* hello
var a = 1;
* world
^D
<ul>
<li>hello
var a = 1;</li>
<li>world</li>
</ul>
```
``` bash
$ marked
* hello
var a = 1;
* world
^D
<ul><li>hello
<pre>code>var a = 1;</code></pre></li>
<li>world</li></ul>
```
Which looks more reasonable? Why shouldn't code blocks be able to appear in
list items in a sane way?
- - -
``` bash
$ markdown.js
<div>hello</div>
<span>hello</span>
^D
<p><div>hello</div></p>
<p><span>hello</span></p>
```
``` bash
$ marked
<div>hello</div>
<span>hello</span>
^D
<div>hello</div>
<p><span>hello</span>
</p>
```
- - -
See: https://github.com/evilstreak/markdown-js/issues/27
``` bash
$ markdown.js
[](/link)
^D
<p><a href="/image)](/link">](/link)
^D
<p><a href="/link"><img src="/image" alt="an image"></a>
</p>
```
- - -
See: https://github.com/evilstreak/markdown-js/issues/24
``` bash
$ markdown.js
> a
> b
> c
^D
<blockquote><p>a</p><p>bundefined> c</p></blockquote>
```
``` bash
$ marked
> a
> b
> c
^D
<blockquote><p>a
</p></blockquote>
<blockquote><p>b
</p></blockquote>
<blockquote><p>c
</p></blockquote>
```
- - -
``` bash
$ markdown.pl
* hello
* world
how
are
you
* today
* hi
^D
<ul>
<li><p>hello</p>
<ul>
<li>world
how</li>
</ul>
<p>are
you</p>
<ul>
<li>today</li>
</ul></li>
<li>hi</li>
</ul>
```
``` bash
$ marked
* hello
* world
how
are
you
* today
* hi
^D
<ul>
<li><p>hello</p>
<ul>
<li><p>world
how</p>
<p>are
you</p>
</li>
<li><p>today</p>
</li>
</ul>
</li>
<li>hi</li>
</ul>
```
| {
"pile_set_name": "Github"
} |
/*
Copyright 2019 The kubewg 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.
*/
package mutating
import (
"context"
"fmt"
"net/http"
"sigs.k8s.io/controller-runtime/pkg/client"
wgv1alpha1 "github.com/munnerz/kubewg/pkg/apis/wg/v1alpha1"
"sigs.k8s.io/controller-runtime/pkg/runtime/inject"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/types"
)
func init() {
webhookName := "mutating-create-peer"
if HandlerMap[webhookName] == nil {
HandlerMap[webhookName] = []admission.Handler{}
}
HandlerMap[webhookName] = append(HandlerMap[webhookName], &PeerCreateHandler{})
}
// PeerCreateHandler handles Peer
type PeerCreateHandler struct {
Client client.Client
// Decoder decodes objects
Decoder types.Decoder
}
func (h *PeerCreateHandler) mutatingPeerFn(ctx context.Context, obj *wgv1alpha1.Peer) error {
if obj.Status.Network == "" {
return fmt.Errorf("network must be specified")
}
if obj.Status.Address != "" {
return nil
}
// TODO(user): implement your admission logic
return nil
}
var _ admission.Handler = &PeerCreateHandler{}
// Handle handles admission requests.
func (h *PeerCreateHandler) Handle(ctx context.Context, req types.Request) types.Response {
obj := &wgv1alpha1.Peer{}
err := h.Decoder.Decode(req, obj)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}
copy := obj.DeepCopy()
err = h.mutatingPeerFn(ctx, copy)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
return admission.PatchResponse(obj, copy)
}
var _ inject.Client = &PeerCreateHandler{}
//
//// InjectClient injects the client into the PeerCreateHandler
func (h *PeerCreateHandler) InjectClient(c client.Client) error {
h.Client = c
return nil
}
var _ inject.Decoder = &PeerCreateHandler{}
// InjectDecoder injects the decoder into the PeerCreateHandler
func (h *PeerCreateHandler) InjectDecoder(d types.Decoder) error {
h.Decoder = d
return nil
}
| {
"pile_set_name": "Github"
} |
# =============================================================================
# Copyright 2016 The TensorFlow Authors. 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.
# =============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy
import tensorflow
from tensorflow.contrib.periodic_resample import periodic_resample
from tensorflow.python.framework import test_util
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
class PeriodicResampleTest(test_util.TensorFlowTestCase):
def testPeriodicResampleBasic2D(self):
input_tensor = numpy.arange(12).reshape((3, 4))
desired_shape = numpy.array([6, None])
output_tensor = input_tensor.reshape((6, 2))
with self.test_session():
variables.global_variables_initializer().run()
result = periodic_resample(input_tensor, desired_shape).eval()
self.assertAllEqual(result, output_tensor)
def testPeriodicResampleTruncatedBasic2D(self):
input_tensor = numpy.arange(12).reshape((3, 4))
desired_shape = numpy.array([5, None])
output_tensor = input_tensor.reshape((6, 2))[:-1]
with self.test_session():
variables.global_variables_initializer().run()
result = periodic_resample(input_tensor, desired_shape).eval()
self.assertAllEqual(result, output_tensor)
def testPeriodicResampleBasic3D(self):
input_tensor = numpy.arange(2*2*4).reshape((2, 2, 4))
desired_shape = numpy.array([4, 4, None])
output_tensor = numpy.array([[[0], [2], [4], [6]],
[[1], [3], [5], [7]],
[[8], [10], [12], [14]],
[[9], [11], [13], [15]]])
# NOTE: output_tensor != input_tensor.reshape((4, 4, -1))
with self.test_session():
variables.global_variables_initializer().run()
result = periodic_resample(input_tensor, desired_shape).eval()
# input_tensor[0, 0, 0] == result[0, 0, 0]
# input_tensor[0, 0, 1] == result[1, 0, 0]
# input_tensor[0, 0, 2] == result[0, 1, 0]
# input_tensor[0, 0, 3] == result[1, 1, 0]
self.assertAllEqual(result, output_tensor)
def testPeriodicResampleBasic4D(self):
input_tensor = numpy.arange(2*2*2*8).reshape((2, 2, 2, 8))
desired_shape = numpy.array([4, 4, 4, None])
output_tensor = numpy.array([[[[0], [4], [8], [12]],
[[2], [6], [10], [14]],
[[16], [20], [24], [28]],
[[18], [22], [26], [30]]],
[[[1], [5], [9], [13]],
[[3], [7], [11], [15]],
[[17], [21], [25], [29]],
[[19], [23], [27], [31]]],
[[[32], [36], [40], [44]],
[[34], [38], [42], [46]],
[[48], [52], [56], [60]],
[[50], [54], [58], [62]]],
[[[33], [37], [41], [45]],
[[35], [39], [43], [47]],
[[49], [53], [57], [61]],
[[51], [55], [59], [63]]]])
# NOTE: output_tensor != input_tensor.reshape((4, 4, 4, -1))
with self.test_session():
variables.global_variables_initializer().run()
result = periodic_resample(input_tensor, desired_shape).eval()
self.assertAllEqual(result, output_tensor)
if __name__ == "__main__":
googletest.main()
| {
"pile_set_name": "Github"
} |
<testcase>
<info>
<keywords>
HTTPS
HTTP GET
PEM certificate
</keywords>
</info>
#
# Server-side
<reply>
</reply>
#
# Client-side
<client>
<features>
SSL
SSLpinning
</features>
<server>
https Server-localhost-sv.pem
</server>
<name>
HTTPS wrong base64-sha256 pinnedpubkey but right CN
</name>
<command>
--cacert %SRCDIR/certs/EdelCurlRoot-ca.crt --pinnedpubkey sha256//bSIggTf+ikMG0CtmDlpMVBd7yi7H1md4URogRPqerso= https://localhost:%HTTPSPORT/2042
</command>
# Ensure that we're running on localhost because we're checking the host name
<precheck>
perl -e "print 'Test requires default test server host' if ( '%HOSTIP' ne '127.0.0.1' );"
</precheck>
</client>
#
# Verify data after the test has been "shot"
<verify>
<errorcode>
90
</errorcode>
</verify>
</testcase>
| {
"pile_set_name": "Github"
} |
// Generated from definition io.k8s.api.apps.v1beta1.DeploymentSpec
/// DeploymentSpec is the specification of the desired behavior of the Deployment.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DeploymentSpec {
/// Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)
pub min_ready_seconds: Option<i32>,
/// Indicates that the deployment is paused.
pub paused: Option<bool>,
/// The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.
pub progress_deadline_seconds: Option<i32>,
/// Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.
pub replicas: Option<i32>,
/// The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2.
pub revision_history_limit: Option<i32>,
/// DEPRECATED. The config this deployment is rolling back to. Will be cleared after rollback is done.
pub rollback_to: Option<crate::api::apps::v1beta1::RollbackConfig>,
/// Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment.
pub selector: Option<crate::apimachinery::pkg::apis::meta::v1::LabelSelector>,
/// The deployment strategy to use to replace existing pods with new ones.
pub strategy: Option<crate::api::apps::v1beta1::DeploymentStrategy>,
/// Template describes the pods that will be created.
pub template: crate::api::core::v1::PodTemplateSpec,
}
impl<'de> serde::Deserialize<'de> for DeploymentSpec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_min_ready_seconds,
Key_paused,
Key_progress_deadline_seconds,
Key_replicas,
Key_revision_history_limit,
Key_rollback_to,
Key_selector,
Key_strategy,
Key_template,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(match v {
"minReadySeconds" => Field::Key_min_ready_seconds,
"paused" => Field::Key_paused,
"progressDeadlineSeconds" => Field::Key_progress_deadline_seconds,
"replicas" => Field::Key_replicas,
"revisionHistoryLimit" => Field::Key_revision_history_limit,
"rollbackTo" => Field::Key_rollback_to,
"selector" => Field::Key_selector,
"strategy" => Field::Key_strategy,
"template" => Field::Key_template,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = DeploymentSpec;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("DeploymentSpec")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_min_ready_seconds: Option<i32> = None;
let mut value_paused: Option<bool> = None;
let mut value_progress_deadline_seconds: Option<i32> = None;
let mut value_replicas: Option<i32> = None;
let mut value_revision_history_limit: Option<i32> = None;
let mut value_rollback_to: Option<crate::api::apps::v1beta1::RollbackConfig> = None;
let mut value_selector: Option<crate::apimachinery::pkg::apis::meta::v1::LabelSelector> = None;
let mut value_strategy: Option<crate::api::apps::v1beta1::DeploymentStrategy> = None;
let mut value_template: Option<crate::api::core::v1::PodTemplateSpec> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_min_ready_seconds => value_min_ready_seconds = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_paused => value_paused = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_progress_deadline_seconds => value_progress_deadline_seconds = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_replicas => value_replicas = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_revision_history_limit => value_revision_history_limit = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_rollback_to => value_rollback_to = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_selector => value_selector = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_strategy => value_strategy = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_template => value_template = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(DeploymentSpec {
min_ready_seconds: value_min_ready_seconds,
paused: value_paused,
progress_deadline_seconds: value_progress_deadline_seconds,
replicas: value_replicas,
revision_history_limit: value_revision_history_limit,
rollback_to: value_rollback_to,
selector: value_selector,
strategy: value_strategy,
template: value_template.ok_or_else(|| serde::de::Error::missing_field("template"))?,
})
}
}
deserializer.deserialize_struct(
"DeploymentSpec",
&[
"minReadySeconds",
"paused",
"progressDeadlineSeconds",
"replicas",
"revisionHistoryLimit",
"rollbackTo",
"selector",
"strategy",
"template",
],
Visitor,
)
}
}
impl serde::Serialize for DeploymentSpec {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"DeploymentSpec",
1 +
self.min_ready_seconds.as_ref().map_or(0, |_| 1) +
self.paused.as_ref().map_or(0, |_| 1) +
self.progress_deadline_seconds.as_ref().map_or(0, |_| 1) +
self.replicas.as_ref().map_or(0, |_| 1) +
self.revision_history_limit.as_ref().map_or(0, |_| 1) +
self.rollback_to.as_ref().map_or(0, |_| 1) +
self.selector.as_ref().map_or(0, |_| 1) +
self.strategy.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.min_ready_seconds {
serde::ser::SerializeStruct::serialize_field(&mut state, "minReadySeconds", value)?;
}
if let Some(value) = &self.paused {
serde::ser::SerializeStruct::serialize_field(&mut state, "paused", value)?;
}
if let Some(value) = &self.progress_deadline_seconds {
serde::ser::SerializeStruct::serialize_field(&mut state, "progressDeadlineSeconds", value)?;
}
if let Some(value) = &self.replicas {
serde::ser::SerializeStruct::serialize_field(&mut state, "replicas", value)?;
}
if let Some(value) = &self.revision_history_limit {
serde::ser::SerializeStruct::serialize_field(&mut state, "revisionHistoryLimit", value)?;
}
if let Some(value) = &self.rollback_to {
serde::ser::SerializeStruct::serialize_field(&mut state, "rollbackTo", value)?;
}
if let Some(value) = &self.selector {
serde::ser::SerializeStruct::serialize_field(&mut state, "selector", value)?;
}
if let Some(value) = &self.strategy {
serde::ser::SerializeStruct::serialize_field(&mut state, "strategy", value)?;
}
serde::ser::SerializeStruct::serialize_field(&mut state, "template", &self.template)?;
serde::ser::SerializeStruct::end(state)
}
}
| {
"pile_set_name": "Github"
} |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
#ifndef __CCPLATFORMDEFINE_H__
#define __CCPLATFORMDEFINE_H__
#include "base/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include <assert.h>
#define CC_DLL
#define CC_ASSERT(cond) assert(cond)
#define CC_UNUSED_PARAM(unusedparam) (void)unusedparam
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#endif // CC_PLATFORM_IOS
#endif /* __CCPLATFORMDEFINE_H__*/
| {
"pile_set_name": "Github"
} |
/*
Copyright 2014 The Kubernetes 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.
*/
package labels
import (
"fmt"
"sort"
"strings"
)
// Labels allows you to present labels independently from their storage.
type Labels interface {
// Has returns whether the provided label exists.
Has(label string) (exists bool)
// Get returns the value for the provided label.
Get(label string) (value string)
}
// Set is a map of label:value. It implements Labels.
type Set map[string]string
// String returns all labels listed as a human readable string.
// Conveniently, exactly the format that ParseSelector takes.
func (ls Set) String() string {
selector := make([]string, 0, len(ls))
for key, value := range ls {
selector = append(selector, key+"="+value)
}
// Sort for determinism.
sort.StringSlice(selector).Sort()
return strings.Join(selector, ",")
}
// Has returns whether the provided label exists in the map.
func (ls Set) Has(label string) bool {
_, exists := ls[label]
return exists
}
// Get returns the value in the map for the provided label.
func (ls Set) Get(label string) string {
return ls[label]
}
// AsSelector converts labels into a selectors.
func (ls Set) AsSelector() Selector {
return SelectorFromSet(ls)
}
// AsSelectorPreValidated converts labels into a selector, but
// assumes that labels are already validated and thus don't
// preform any validation.
// According to our measurements this is significantly faster
// in codepaths that matter at high scale.
func (ls Set) AsSelectorPreValidated() Selector {
return SelectorFromValidatedSet(ls)
}
// FormatLabels convert label map into plain string
func FormatLabels(labelMap map[string]string) string {
l := Set(labelMap).String()
if l == "" {
l = "<none>"
}
return l
}
// Conflicts takes 2 maps and returns true if there a key match between
// the maps but the value doesn't match, and returns false in other cases
func Conflicts(labels1, labels2 Set) bool {
small := labels1
big := labels2
if len(labels2) < len(labels1) {
small = labels2
big = labels1
}
for k, v := range small {
if val, match := big[k]; match {
if val != v {
return true
}
}
}
return false
}
// Merge combines given maps, and does not check for any conflicts
// between the maps. In case of conflicts, second map (labels2) wins
func Merge(labels1, labels2 Set) Set {
mergedMap := Set{}
for k, v := range labels1 {
mergedMap[k] = v
}
for k, v := range labels2 {
mergedMap[k] = v
}
return mergedMap
}
// Equals returns true if the given maps are equal
func Equals(labels1, labels2 Set) bool {
if len(labels1) != len(labels2) {
return false
}
for k, v := range labels1 {
value, ok := labels2[k]
if !ok {
return false
}
if value != v {
return false
}
}
return true
}
// AreLabelsInWhiteList verifies if the provided label list
// is in the provided whitelist and returns true, otherwise false.
func AreLabelsInWhiteList(labels, whitelist Set) bool {
if len(whitelist) == 0 {
return true
}
for k, v := range labels {
value, ok := whitelist[k]
if !ok {
return false
}
if value != v {
return false
}
}
return true
}
// ConvertSelectorToLabelsMap converts selector string to labels map
// and validates keys and values
func ConvertSelectorToLabelsMap(selector string) (Set, error) {
labelsMap := Set{}
if len(selector) == 0 {
return labelsMap, nil
}
labels := strings.Split(selector, ",")
for _, label := range labels {
l := strings.Split(label, "=")
if len(l) != 2 {
return labelsMap, fmt.Errorf("invalid selector: %s", l)
}
key := strings.TrimSpace(l[0])
if err := validateLabelKey(key); err != nil {
return labelsMap, err
}
value := strings.TrimSpace(l[1])
if err := validateLabelValue(key, value); err != nil {
return labelsMap, err
}
labelsMap[key] = value
}
return labelsMap, nil
}
| {
"pile_set_name": "Github"
} |
package com.icafe4j.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import com.icafe4j.image.meta.Metadata;
import com.icafe4j.image.meta.MetadataEntry;
import com.icafe4j.image.meta.icc.ICCProfile;
public class TestICCProfile extends TestBase {
public static void main(String[] args) throws IOException {
new TestICCProfile().test(args);
}
public void test(String ... args) throws IOException {
FileInputStream fin = new FileInputStream(args[0]);
Metadata icc_profile = new ICCProfile(fin);
Iterator<MetadataEntry> iterator = icc_profile.iterator();
while(iterator.hasNext()) {
MetadataEntry item = iterator.next();
logger.info(item.getKey() + ": " + item.getValue());
if(item.isMetadataEntryGroup()) {
String indent = " ";
Collection<MetadataEntry> entries = item.getMetadataEntries();
for(MetadataEntry e : entries) {
logger.info(indent + e.getKey() + ": " + e.getValue());
}
}
}
FileOutputStream fout = new FileOutputStream(new File("ICCProfile.icc"));
icc_profile.write(fout);
fin.close();
fout.close();
}
}
| {
"pile_set_name": "Github"
} |
"""
```
Model990{T} <: AbstractRepModel{T}
```
The `Model990` type defines the structure of the New York Fed DSGE model.
### Fields
#### Parameters and Steady-States
* `parameters::Vector{AbstractParameter}`: Vector of all time-invariant model
parameters.
* `steady_state::Vector{AbstractParameter}`: Model steady-state values, computed
as a function of elements of `parameters`.
* `keys::OrderedDict{Symbol,Int}`: Maps human-readable names for all model
parameters and steady-states to their indices in `parameters` and
`steady_state`.
#### Inputs to Measurement and Equilibrium Condition Equations
The following fields are dictionaries that map human-readable names to row and
column indices in the matrix representations of of the measurement equation and
equilibrium conditions.
* `endogenous_states::OrderedDict{Symbol,Int}`: Maps each state to a column in
the measurement and equilibrium condition matrices.
* `exogenous_shocks::OrderedDict{Symbol,Int}`: Maps each shock to a column in
the measurement and equilibrium condition matrices.
* `expected_shocks::OrderedDict{Symbol,Int}`: Maps each expected shock to a
column in the measurement and equilibrium condition matrices.
* `equilibrium_conditions::OrderedDict{Symbol,Int}`: Maps each equlibrium
condition to a row in the model's equilibrium condition matrices.
* `endogenous_states_augmented::OrderedDict{Symbol,Int}`: Maps lagged states to
their columns in the measurement and equilibrium condition equations. These
are added after `gensys` solves the model.
* `observables::OrderedDict{Symbol,Int}`: Maps each observable to a row in the
model's measurement equation matrices.
* `pseudo_observables::OrderedDict{Symbol,Int}`: Maps each pseudo-observable to
a row in the model's pseudo-measurement equation matrices.
#### Model Specifications and Settings
* `spec::String`: The model specification identifier, \"m990\", cached
here for filepath computation.
* `subspec::String`: The model subspecification number, indicating that
some parameters from the original model spec (\"ss3\") are initialized
differently. Cached here for filepath computation.
* `settings::Dict{Symbol,Setting}`: Settings/flags that affect computation
without changing the economic or mathematical setup of the model.
* `test_settings::Dict{Symbol,Setting}`: Settings/flags for testing mode
#### Other Fields
* `rng::MersenneTwister`: Random number generator. Can be is seeded to ensure
reproducibility in algorithms that involve randomness (such as
Metropolis-Hastings).
* `testing::Bool`: Indicates whether the model is in testing mode. If `true`,
settings from `m.test_settings` are used in place of those in `m.settings`.
* `observable_mappings::OrderedDict{Symbol,Observable}`: A dictionary that
stores data sources, series mnemonics, and transformations to/from model
units. DSGE.jl will fetch data from the Federal Reserve Bank of St. Louis's
FRED database; all other data must be downloaded by the user. See `load_data`
and `Observable` for further details.
* `pseudo_observable_mappings::OrderedDict{Symbol,PseudoObservable}`: A
dictionary that stores names and transformations to/from model units. See
`PseudoObservable` for further details.
"""
mutable struct Model990{T} <: AbstractRepModel{T}
parameters::ParameterVector{T} # vector of all time-invariant model parameters
steady_state::ParameterVector{T} # model steady-state values
keys::OrderedDict{Symbol,Int} # human-readable names for all the model
# parameters and steady-states
endogenous_states::OrderedDict{Symbol,Int} # these fields used to create matrices in the
exogenous_shocks::OrderedDict{Symbol,Int} # measurement and equilibrium condition equations.
expected_shocks::OrderedDict{Symbol,Int} #
equilibrium_conditions::OrderedDict{Symbol,Int} #
endogenous_states_augmented::OrderedDict{Symbol,Int} #
observables::OrderedDict{Symbol,Int} #
pseudo_observables::OrderedDict{Symbol,Int} #
spec::String # Model specification number (eg "m990")
subspec::String # Model subspecification (eg "ss0")
settings::Dict{Symbol,Setting} # Settings/flags for computation
test_settings::Dict{Symbol,Setting} # Settings/flags for testing mode
rng::MersenneTwister # Random number generator
testing::Bool # Whether we are in testing mode or not
observable_mappings::OrderedDict{Symbol, Observable}
pseudo_observable_mappings::OrderedDict{Symbol, PseudoObservable}
end
description(m::Model990) = "New York Fed DSGE Model m990, $(m.subspec)"
"""
`init_model_indices!(m::Model990)`
Arguments:
`m:: Model990`: a model object
Description:
Initializes indices for all of `m`'s states, shocks, and equilibrium conditions.
"""
function init_model_indices!(m::Model990)
# Endogenous states
endogenous_states = [[
:y_t, :c_t, :i_t, :qk_t, :k_t, :kbar_t, :u_t, :rk_t, :Rtil_k_t, :n_t, :mc_t,
:π_t, :μ_ω_t, :w_t, :L_t, :R_t, :g_t, :b_t, :μ_t, :z_t, :λ_f_t, :λ_f_t1,
:λ_w_t, :λ_w_t1, :rm_t, :σ_ω_t, :μ_e_t, :γ_t, :π_star_t, :Ec_t, :Eqk_t, :Ei_t,
:Eπ_t, :EL_t, :Erk_t, :Ew_t, :ERtil_k_t, :y_f_t, :c_f_t, :i_f_t, :qk_f_t, :k_f_t,
:kbar_f_t, :u_f_t, :rk_f_t, :w_f_t, :L_f_t, :r_f_t, :Ec_f_t, :Eqk_f_t, :Ei_f_t,
:EL_f_t, :Erk_f_t, :ztil_t, :π_t1, :π_t2, :π_a_t, :R_t1, :zp_t, :Ez_t];
[Symbol("rm_tl$i") for i = 1:n_mon_anticipated_shocks(m)]]
# Exogenous shocks
exogenous_shocks = [[
:g_sh, :b_sh, :μ_sh, :z_sh, :λ_f_sh, :λ_w_sh, :rm_sh, :σ_ω_sh, :μ_e_sh,
:γ_sh, :π_star_sh, :lr_sh, :zp_sh, :tfp_sh, :gdpdef_sh, :corepce_sh];
[Symbol("rm_shl$i") for i = 1:n_mon_anticipated_shocks(m)]]
# Expectations shocks
expected_shocks = [
:Ec_sh, :Eqk_sh, :Ei_sh, :Eπ_sh, :EL_sh, :Erk_sh, :Ew_sh, :ERktil_sh, :Ec_f_sh,
:Eqk_f_sh, :Ei_f_sh, :EL_f_sh, :Erk_f_sh]
# Equilibrium conditions
equilibrium_conditions = [[
:eq_euler, :eq_inv, :eq_capval, :eq_spread, :eq_nevol, :eq_output, :eq_caputl, :eq_capsrv, :eq_capev,
:eq_mkupp, :eq_phlps, :eq_caprnt, :eq_msub, :eq_wage, :eq_mp, :eq_res, :eq_g, :eq_b, :eq_μ, :eq_z,
:eq_λ_f, :eq_λ_w, :eq_rm, :eq_σ_ω, :eq_μ_e, :eq_γ, :eq_λ_f1, :eq_λ_w1, :eq_Ec,
:eq_Eqk, :eq_Ei, :eq_Eπ, :eq_EL, :eq_Erk, :eq_Ew, :eq_ERktil, :eq_euler_f, :eq_inv_f,
:eq_capval_f, :eq_output_f, :eq_caputl_f, :eq_capsrv_f, :eq_capev_f, :eq_mkupp_f,
:eq_caprnt_f, :eq_msub_f, :eq_res_f, :eq_Ec_f, :eq_Eqk_f, :eq_Ei_f, :eq_EL_f, :eq_Erk_f,
:eq_ztil, :eq_π_star, :eq_π1, :eq_π2, :eq_π_a, :eq_Rt1, :eq_zp, :eq_Ez];
[Symbol("eq_rml$i") for i=1:n_mon_anticipated_shocks(m)]]
# Additional states added after solving model
# Lagged states and observables measurement error
endogenous_states_augmented = [
:y_t1, :c_t1, :i_t1, :w_t1, :π_t1_dup, :L_t1, :Et_π_t, :lr_t, :tfp_t, :e_gdpdef_t,
:e_corepce_t, :u_t1]
# Observables
observables = keys(m.observable_mappings)
# Pseudo-observables
pseudo_observables = keys(m.pseudo_observable_mappings)
for (i,k) in enumerate(endogenous_states); m.endogenous_states[k] = i end
for (i,k) in enumerate(exogenous_shocks); m.exogenous_shocks[k] = i end
for (i,k) in enumerate(expected_shocks); m.expected_shocks[k] = i end
for (i,k) in enumerate(equilibrium_conditions); m.equilibrium_conditions[k] = i end
for (i,k) in enumerate(endogenous_states); m.endogenous_states[k] = i end
for (i,k) in enumerate(endogenous_states_augmented); m.endogenous_states_augmented[k] = i+length(endogenous_states) end
for (i,k) in enumerate(observables); m.observables[k] = i end
for (i,k) in enumerate(pseudo_observables); m.pseudo_observables[k] = i end
end
function Model990(subspec::String="ss3";
custom_settings::Dict{Symbol, Setting} = Dict{Symbol, Setting}(),
testing = false)
# Model-specific specifications
spec = split(basename(@__FILE__),'.')[1]
subspec = subspec
settings = Dict{Symbol,Setting}()
test_settings = Dict{Symbol,Setting}()
rng = MersenneTwister(0)
# initialize empty model
m = Model990{Float64}(
# model parameters and steady state values
Vector{AbstractParameter{Float64}}(), Vector{Float64}(), OrderedDict{Symbol,Int}(),
# model indices
OrderedDict{Symbol,Int}(), OrderedDict{Symbol,Int}(), OrderedDict{Symbol,Int}(), OrderedDict{Symbol,Int}(), OrderedDict{Symbol,Int}(), OrderedDict{Symbol,Int}(), OrderedDict{Symbol,Int}(),
spec,
subspec,
settings,
test_settings,
rng,
testing,
OrderedDict{Symbol,Observable}(),
OrderedDict{Symbol,PseudoObservable}())
# Set settings
model_settings!(m)
default_test_settings!(m)
for custom_setting in values(custom_settings)
m <= custom_setting
end
# Set observable and pseudo-observable transformations
init_observable_mappings!(m)
init_pseudo_observable_mappings!(m)
# Initialize parameters
init_parameters!(m)
init_model_indices!(m)
init_subspec!(m)
steadystate!(m)
return m
end
"""
```
init_parameters!(m::Model990)
```
Initializes the model's parameters, as well as empty values for the steady-state
parameters (in preparation for `steadystate!(m)` being called to initialize
those).
"""
function init_parameters!(m::Model990)
m <= parameter(:α, 0.1596, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), Normal(0.30, 0.05), fixed=false,
description="α: Capital elasticity in the intermediate goods sector's production function (also known as the capital share).",
tex_label="\\alpha")
m <= parameter(:ζ_p, 0.8940, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.1), fixed=false,
description="ζ_p: The Calvo parameter. In every period, intermediate goods producers optimize prices with probability (1-ζ_p). With probability ζ_p, prices are adjusted according to a weighted average of the previous period's inflation (π_t1) and steady-state inflation (π_star).",
tex_label="\\zeta_p")
m <= parameter(:ι_p, 0.1865, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.15), fixed=false,
description="ι_p: The weight attributed to last period's inflation in price indexation. (1-ι_p) is the weight attributed to steady-state inflation.",
tex_label="\\iota_p")
m <= parameter(:δ, 0.025, fixed=true,
description="δ: The capital depreciation rate.",
tex_label="\\delta" )
m <= parameter(:Upsilon, 1.000, (0., 10.), (1e-5, 0.), ModelConstructors.Exponential(), GammaAlt(1., 0.5), fixed=true,
description="Υ: The trend evolution of the price of investment goods relative to consumption goods. Set equal to 1.",
tex_label="\\Upsilon")
m <= parameter(:Φ, 1.1066, (1., 10.), (1.00, 10.00), ModelConstructors.Exponential(), Normal(1.25, 0.12), fixed=false,
description="Φ: Fixed costs.",
tex_label="\\Phi_p")
m <= parameter(:S′′, 2.7314, (-15., 15.), (-15., 15.), ModelConstructors.Untransformed(), Normal(4., 1.5), fixed=false,
description="S'': The second derivative of households' cost of adjusting investment.",
tex_label="S''")
m <= parameter(:h, 0.5347, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.7, 0.1), fixed=false,
description="h: Consumption habit persistence.",
tex_label="h")
m <= parameter(:ppsi, 0.6862, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.15), fixed=false,
description="ppsi: Utilization costs.",
tex_label="\\psi")
m <= parameter(:ν_l, 2.5975, (1e-5, 10.), (1e-5, 10.), ModelConstructors.Exponential(), Normal(2, 0.75), fixed=false,
description="ν_l: The coefficient of relative risk aversion on the labor term of households' utility function.",
tex_label="\\nu_l")
m <= parameter(:ζ_w, 0.9291, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.1), fixed=false,
description="ζ_w: (1-ζ_w) is the probability with which households can freely choose wages in each period. With probability ζ_w, wages increase at a geometrically weighted average of the steady state rate of wage increases and last period's productivity times last period's inflation.",
tex_label="\\zeta_w")
m <= parameter(:ι_w, 0.2992, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.15), fixed=false,
description="ι_w: The weight attributed to last period's wage in wage indexation. (1-ι_w) is the weight attributed to steady-state wages.",
tex_label="\\iota_w")
m <= parameter(:λ_w, 1.5000, fixed=true,
description="λ_w: The wage markup, which affects the elasticity of substitution between differentiated labor services.",
tex_label="\\lambda_w")
m <= parameter(:β, 0.1402, (1e-5, 10.), (1e-5, 10.), ModelConstructors.Exponential(), GammaAlt(0.25, 0.1), fixed=false,
scaling = x -> 1/(1 + x/100),
description="β: Discount rate.",
tex_label="100(\\beta^{-1} - 1)")
m <= parameter(:ψ1, 1.3679, (1e-5, 10.), (1e-5, 10.00), ModelConstructors.Exponential(), Normal(1.5, 0.25), fixed=false,
description="ψ₁: Weight on inflation gap in monetary policy rule.",
tex_label="\\psi_1")
m <= parameter(:ψ2, 0.0388, (-0.5, 0.5), (-0.5, 0.5), ModelConstructors.Untransformed(), Normal(0.12, 0.05), fixed=false,
description="ψ₂: Weight on output gap in monetary policy rule.",
tex_label="\\psi_2")
m <= parameter(:ψ3, 0.2464, (-0.5, 0.5), (-0.5, 0.5), ModelConstructors.Untransformed(), Normal(0.12, 0.05), fixed=false,
description="ψ₃: Weight on rate of change of output gap in the monetary policy rule.",
tex_label="\\psi_3")
m <= parameter(:π_star, 0.5000, (1e-5, 10.), (1e-5, 10.), ModelConstructors.Exponential(), GammaAlt(0.75, 0.4), fixed=true,
scaling = x -> 1 + x/100,
description="π_star: The steady-state rate of inflation.",
tex_label="\\pi_*")
m <= parameter(:σ_c, 0.8719, (1e-5, 10.), (1e-5, 10.), ModelConstructors.Exponential(), Normal(1.5, 0.37), fixed=false,
description="σ_c: Coefficient of relative risk aversion.",
tex_label="\\sigma_{c}")
m <= parameter(:ρ, 0.7126, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.75, 0.10), fixed=false,
description="ρ: The degree of inertia in the monetary policy rule.",
tex_label="\\rho_R")
m <= parameter(:ϵ_p, 10.000, fixed=true,
description="ϵ_p: Curvature parameter in the Kimball aggregator for prices.",
tex_label="\\epsilon_{p}")
m <= parameter(:ϵ_w, 10.000, fixed=true,
description="ϵ_w: Curvature parameter in the Kimball aggregator for wages.",
tex_label="\\epsilon_{w}")
# financial frictions parameters
m <= parameter(:Fω, 0.0300, (1e-5, 0.99999), (1e-5, 0.99), ModelConstructors.SquareRoot(), BetaAlt(0.03, 0.01), fixed=true,
scaling = x -> 1 - (1-x)^0.25,
description="F(ω): The cumulative distribution function of ω (idiosyncratic iid shock that increases or decreases entrepreneurs' capital).",
tex_label="F(\\bar{\\omega})")
m <= parameter(:spr, 1.7444, (0., 100.), (1e-5, 0.), ModelConstructors.Exponential(), GammaAlt(2., 0.1), fixed=false,
scaling = x -> (1 + x/100)^0.25,
description="spr_*: Steady-state level of spread.",
tex_label="SP_*")
m <= parameter(:ζ_spb, 0.0559, (1e-5, 0.99999), (1e-5, 0.99), ModelConstructors.SquareRoot(), BetaAlt(0.05, 0.005), fixed=false,
description="ζ_spb: The elasticity of the expected exess return on capital (or 'spread') with respect to leverage.",
tex_label="\\zeta_{sp,b}")
m <= parameter(:γ_star, 0.9900, (1e-5, 0.99999), (1e-5, 0.99), ModelConstructors.SquareRoot(), BetaAlt(0.99, 0.002), fixed=true,
description="γ_star: Fraction of entrepreneurs who survive and continue operating for another period.",
tex_label="\\gamma_*")
# exogenous processes - level
m <= parameter(:γ, 0.3673, (-5.0, 5.0), (-5., 5.), ModelConstructors.Untransformed(), Normal(0.4, 0.1), fixed=false,
scaling = x -> x/100,
description="γ: The log of the steady-state growth rate of technology.",
tex_label="100\\gamma")
m <= parameter(:Lmean, -45.9364, (-1000., 1000.), (-1e3, 1e3), ModelConstructors.Untransformed(), Normal(-45., 5.), fixed=false,
description="Lmean: Mean level of hours.",
tex_label="\\bar{L}")
m <= parameter(:g_star, 0.1800, fixed=true,
description="g_star: 1 - (c_star + i_star)/y_star.",
tex_label="g_*")
# exogenous processes - autocorrelation
m <= parameter(:ρ_g, 0.9863, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_g: AR(1) coefficient in the government spending process.",
tex_label="\\rho_g")
m <= parameter(:ρ_b, 0.9410, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_b: AR(1) coefficient in the intertemporal preference shifter process.",
tex_label="\\rho_b")
m <= parameter(:ρ_μ, 0.8735, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_μ: AR(1) coefficient in capital adjustment cost process.",
tex_label="\\rho_{\\mu}")
m <= parameter(:ρ_z, 0.9446, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_z: AR(1) coefficient in the technology process.",
tex_label="\\rho_z")
m <= parameter(:ρ_λ_f, 0.8827, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_λ_f: AR(1) coefficient in the price mark-up shock process.",
tex_label="\\rho_{\\lambda_f}")
m <= parameter(:ρ_λ_w, 0.3884, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_λ_w: AR(1) coefficient in the wage mark-up shock process.",
tex_label="\\rho_{\\lambda_w}")
# monetary policy shock - see eqcond
m <= parameter(:ρ_rm, 0.2135, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_rm: AR(1) coefficient in the monetary policy shock process.",
tex_label="\\rho_{r^m}")
m <= parameter(:ρ_σ_w, 0.9898, (1e-5, 0.99999), (1e-5, 0.99999), ModelConstructors.SquareRoot(), BetaAlt(0.75, 0.15), fixed=false,
description="ρ_σ_w: The standard deviation of entrepreneurs' capital productivity follows an exogenous process with mean ρ_σ_w. Innovations to the process are called _spread shocks_.",
tex_label="\\rho_{\\sigma_\\omega}")
m <= parameter(:ρ_μ_e, 0.7500, (1e-5, 0.99999), (1e-5, 0.99999), ModelConstructors.SquareRoot(), BetaAlt(0.75, 0.15), fixed=true,
description="ρ_μ_e: AR(1) coefficient in the exogenous bankruptcy cost process.",
tex_label="\\rho_{\\mu_e}")
m <= parameter(:ρ_γ, 0.7500, (1e-5, 0.99999), (1e-5, 0.99), ModelConstructors.SquareRoot(), BetaAlt(0.75, 0.15), fixed=true,
description="ρ_γ: AR(1) coefficient in the process describing the fraction of entrepreneurs surviving period t.",
tex_label="\\rho_{\\gamma}")
m <= parameter(:ρ_π_star, 0.9900, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=true,
description="ρ_π_star: AR(1) coefficient in the time-varying inflation target process.",
tex_label="\\rho_{\\pi_*}")
m <= parameter(:ρ_lr, 0.6936, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
tex_label="\\rho_{10y}")
m <= parameter(:ρ_z_p, 0.8910, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
description="ρ_z_p: AR(1) coefficient in the process describing the permanent component of productivity.",
tex_label="\\rho_{z^p}")
m <= parameter(:ρ_tfp, 0.1953, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
tex_label="\\rho_{tfp}")
m <= parameter(:ρ_gdpdef, 0.5379, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
tex_label="\\rho_{gdpdef}")
m <= parameter(:ρ_corepce, 0.2320, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.5, 0.2), fixed=false,
tex_label="\\rho_{pce}")
# exogenous processes - standard deviation
m <= parameter(:σ_g, 2.5230, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
description="σ_g: The standard deviation of the government spending process.",
tex_label="\\sigma_{g}")
m <= parameter(:σ_b, 0.0292, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
description="σ_b: The standard deviation of the intertemporal preference shifter process.",
tex_label="\\sigma_{b}")
m <= parameter(:σ_μ, 0.4559, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
description="σ_μ: The standard deviation of the exogenous marginal efficiency of investment shock process.",
tex_label="\\sigma_{\\mu}")
m <= parameter(:σ_z, 0.6742, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
description="σ_z: The standard deviation of the process describing the stationary component of productivity.",
tex_label="\\sigma_{z}")
m <= parameter(:σ_λ_f, 0.1314, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
description="σ_λ_f: The mean of the process that generates the price elasticity of the composite good. Specifically, the elasticity is (1+λ_{f,t})/(λ_{f_t}).",
tex_label="\\sigma_{\\lambda_f}")
m <= parameter(:σ_λ_w, 0.3864, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
tex_label="\\sigma_{\\lambda_w}")
m <= parameter(:σ_r_m, 0.2380, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
description="σ_r_m: The standard deviation of the monetary policy shock.",
tex_label="\\sigma_{r^m}")
m <= parameter(:σ_σ_ω, 0.0428, (1e-7,100.), (1e-5, 0.), ModelConstructors.Exponential(), RootInverseGamma(4., 0.05), fixed=false,
description="σ_σ_ω: The standard deviation of entrepreneurs' capital productivity follows an exogenous process with standard deviation σ_σ_ω.",
tex_label="\\sigma_{\\sigma_\\omega}")
m <= parameter(:σ_μ_e, 0.0000, (1e-7,100.), (1e-5, 0.), ModelConstructors.Exponential(), RootInverseGamma(4., 0.05), fixed=true,
description="σ_μ_e: Exogenous bankrupcy costs follow an exogenous process with standard deviation σ_μ_e.",
tex_label="\\sigma_{\\mu_e}")
m <= parameter(:σ_γ, 0.0000, (1e-7,100.), (1e-5, 0.), ModelConstructors.Exponential(), RootInverseGamma(4., 0.01), fixed=true,
description="σ_γ: The fraction of entrepreneurs surviving period t follows an exogenous process with standard deviation σ_γ.",
tex_label="\\sigma_{\\gamma}")
m <= parameter(:σ_π_star, 0.0269, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(6., 0.03), fixed=false,
description="σ_π_star: The standard deviation of the inflation target.",
tex_label="\\sigma_{\\pi_*}")
m <= parameter(:σ_lr, 0.1766, (1e-8,10.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.75), fixed=false,
tex_label="\\sigma_{10y}")
m <= parameter(:σ_z_p, 0.1662, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
description="σ_z_p: The standard deviation of the shock to the permanent component of productivity.",
tex_label="\\sigma_{z^p}")
m <= parameter(:σ_tfp, 0.9391, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
tex_label="\\sigma_{tfp}")
m <= parameter(:σ_gdpdef, 0.1575, (1e-8, 5.), (1e-8, 5.), ModelConstructors.Exponential(), RootInverseGamma(2., 0.10), fixed=false,
tex_label="\\sigma_{gdpdef}")
m <= parameter(:σ_corepce, 0.0999, (1e-8, 5.),(1e-8, 5.), ModelConstructors.Exponential(),RootInverseGamma(2., 0.10),
fixed=false,
tex_label="\\sigma_{pce}")
# standard deviations of the anticipated policy shocks
for i = 1:n_mon_anticipated_shocks_padding(m)
if i < 13
m <= parameter(Symbol("σ_r_m$i"), .2, (1e-7, 100.), (1e-5, 0.), ModelConstructors.Exponential(), RootInverseGamma(4., .2), fixed=false,
description="σ_r_m$i: Standard deviation of the $i-period-ahead anticipated policy shock.",
tex_label=@sprintf("\\sigma_{ant%d}",i))
else
m <= parameter(Symbol("σ_r_m$i"), .0, (1e-7, 100.), (1e-5, 0.), ModelConstructors.Exponential(), RootInverseGamma(4., .2), fixed=true,
description="σ_r_m$i: Standard deviation of the $i-period-ahead anticipated policy shock.",
tex_label=@sprintf("\\sigma_{ant%d}",i))
end
end
m <= parameter(:η_gz, 0.8400, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.50, 0.20), fixed=false,
description="η_gz: Correlate g and z shocks.",
tex_label="\\eta_{gz}")
m <= parameter(:η_λ_f, 0.7892, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.50, 0.20), fixed=false,
description="η_λ_f: Moving average component in the price markup shock.",
tex_label="\\eta_{\\lambda_f}")
m <= parameter(:η_λ_w, 0.4226, (1e-5, 0.999), (1e-5, 0.999), ModelConstructors.SquareRoot(), BetaAlt(0.50, 0.20), fixed=false,
description="η_λ_w: Moving average component in the wage markup shock.",
tex_label="\\eta_{\\lambda_w}")
m <= parameter(:Iendoα, 0.0000, (0.000, 1.000), (0., 0.), ModelConstructors.Untransformed(), BetaAlt(0.50, 0.20), fixed=true,
description="Iendoα: Indicates whether to use the model's endogenous α in the capacity utilization adjustment of total factor productivity.",
tex_label="I\\{\\alpha^{model}\\}")
m <= parameter(:Γ_gdpdef, 1.0354, (-10., 10.), (-10., -10.), ModelConstructors.Untransformed(), Normal(1.00, 2.), fixed=false,
tex_label="\\gamma_{gdpdef}")
m <= parameter(:δ_gdpdef, 0.0181, (-9.1, 9.1), (-10., -10.), ModelConstructors.Untransformed(), Normal(0.00, 2.), fixed=false,
tex_label="\\delta_{gdpdef}")
# steady states
m <= SteadyStateParameter(:z_star, NaN, tex_label="\\z_*")
m <= SteadyStateParameter(:rstar, NaN, tex_label="\\r_*")
m <= SteadyStateParameter(:Rstarn, NaN, tex_label="\\R_*_n")
m <= SteadyStateParameter(:r_k_star, NaN, tex_label="\\r^k_*")
m <= SteadyStateParameter(:wstar, NaN, tex_label="\\w_*")
m <= SteadyStateParameter(:Lstar, NaN, tex_label="\\L_*")
m <= SteadyStateParameter(:kstar, NaN, description="Effective capital that households rent to firms in the steady state.", tex_label="\\k_*")
m <= SteadyStateParameter(:kbarstar, NaN, description="Total capital owned by households in the steady state.", tex_label="\\bar{k}_*")
m <= SteadyStateParameter(:istar, NaN, description="Detrended steady-state investment", tex_label="\\i_*")
m <= SteadyStateParameter(:ystar, NaN, tex_label="\\y_*")
m <= SteadyStateParameter(:cstar, NaN, tex_label="\\c_*")
m <= SteadyStateParameter(:wl_c, NaN, tex_label="\\wl_c")
m <= SteadyStateParameter(:nstar, NaN, tex_label="\\n_*")
m <= SteadyStateParameter(:vstar, NaN, tex_label="\\v_*")
m <= SteadyStateParameter(:ζ_spσ_ω, NaN, tex_label="\\zeta_{sp_{\\sigma_\\omega}}")
m <= SteadyStateParameter(:ζ_spμ_e, NaN, tex_label="\\zeta_{sp_{\\mu_e}}")
m <= SteadyStateParameter(:ζ_nRk, NaN, tex_label="\\zeta_{n_R_k}")
m <= SteadyStateParameter(:ζ_nR, NaN, tex_label="\\zeta_{n_R}")
m <= SteadyStateParameter(:ζ_nqk, NaN, tex_label="\\zeta_{n_q_k}")
m <= SteadyStateParameter(:ζ_nn, NaN, tex_label="\\zeta_{nn}")
m <= SteadyStateParameter(:ζ_nμ_e, NaN, tex_label="\\zeta_{n_{\\mu_e}}")
m <= SteadyStateParameter(:ζ_nσ_ω, NaN, tex_label="\\zeta_{n_{\\sigma_\\omega}}")
end
"""
```
steadystate!(m::Model990)
```
Calculates the model's steady-state values. `steadystate!(m)` must be called whenever
the parameters of `m` are updated.
"""
function steadystate!(m::Model990)
SIGWSTAR_ZERO = 0.5
m[:z_star] = log(1+m[:γ]) + m[:α]/(1-m[:α])*log(m[:Upsilon])
m[:rstar] = exp(m[:σ_c]*m[:z_star]) / m[:β]
m[:Rstarn] = 100*(m[:rstar]*m[:π_star] - 1)
m[:r_k_star] = m[:spr]*m[:rstar]*m[:Upsilon] - (1-m[:δ])
m[:wstar] = (m[:α]^m[:α] * (1-m[:α])^(1-m[:α]) * m[:r_k_star]^(-m[:α]) / m[:Φ])^(1/(1-m[:α]))
m[:Lstar] = 1.
m[:kstar] = (m[:α]/(1-m[:α])) * m[:wstar] * m[:Lstar] / m[:r_k_star]
m[:kbarstar] = m[:kstar] * (1+m[:γ]) * m[:Upsilon]^(1 / (1-m[:α]))
m[:istar] = m[:kbarstar] * (1-((1-m[:δ])/((1+m[:γ]) * m[:Upsilon]^(1/(1-m[:α])))))
m[:ystar] = (m[:kstar]^m[:α]) * (m[:Lstar]^(1-m[:α])) / m[:Φ]
m[:cstar] = (1-m[:g_star])*m[:ystar] - m[:istar]
m[:wl_c] = (m[:wstar]*m[:Lstar])/(m[:cstar]*m[:λ_w])
# FINANCIAL FRICTIONS ADDITIONS
# solve for σ_ω_star and zω_star
zω_star = quantile(Normal(), m[:Fω].scaledvalue)
σ_ω_star = SIGWSTAR_ZERO
try
σ_ω_star = fzero(sigma -> ζ_spb_fn(zω_star, sigma, m[:spr]) - m[:ζ_spb], 0.5)
catch ex
σ_ω_star = SIGWSTAR_ZERO
if !isa(ex, ConvergenceFailed)
rethrow(ex)
else
σ_ω_star = SIGWSTAR_ZERO
end
end
# evaluate ωbarstar
ωbarstar = ω_fn(zω_star, σ_ω_star)
# evaluate all BGG function elasticities
Gstar = G_fn(zω_star, σ_ω_star)
Γstar = Γ_fn(zω_star, σ_ω_star)
dGdω_star = dG_dω_fn(zω_star, σ_ω_star)
d2Gdω2star = d2G_dω2_fn(zω_star, σ_ω_star)
dΓdω_star = dΓ_dω_fn(zω_star)
d2Γdω2star = d2Γ_dω2_fn(zω_star, σ_ω_star)
dGdσstar = dG_dσ_fn(zω_star, σ_ω_star)
d2Gdωdσstar = d2G_dωdσ_fn(zω_star, σ_ω_star)
dΓdσstar = dΓ_dσ_fn(zω_star, σ_ω_star)
d2Γdωdσstar = d2Γ_dωdσ_fn(zω_star, σ_ω_star)
# evaluate μ, nk, and Rhostar
μ_estar = μ_fn(zω_star, σ_ω_star, m[:spr])
nkstar = nk_fn(zω_star, σ_ω_star, m[:spr])
Rhostar = 1/nkstar - 1
# evaluate wekstar and vkstar
if subspec(m) in ["ss2", "ss5"]
wekstar = (1-m[:γ_star]/m[:β])*nkstar - m[:γ_star]/m[:β]*(m[:spr]*(1-μ_estar*Gstar) - 1)
vkstar = (nkstar-wekstar)/m[:γ_star]
else
betabar_inverse = exp( (m[:σ_c] -1) * m[:z_star]) / m[:β]
wekstar = (1-(m[:γ_star]*betabar_inverse))*nkstar - m[:γ_star]*betabar_inverse*(m[:spr]*(1-μ_estar*Gstar) - 1)
vkstar = (nkstar-wekstar)/m[:γ_star]
end
# evaluate nstar and vstar
if subspec(m) in ["ss2", "ss5"]
m[:nstar] = nkstar*m[:kstar]
m[:vstar] = vkstar*m[:kstar]
else
m[:nstar] = nkstar*m[:kbarstar]
m[:vstar] = vkstar*m[:kbarstar]
end
# a couple of combinations
ΓμG = Γstar - μ_estar*Gstar
ΓμGprime = dΓdω_star - μ_estar*dGdω_star
# elasticities wrt ωbar
ζ_bw = ζ_bω_fn(zω_star, σ_ω_star, m[:spr])
ζ_zw = ζ_zω_fn(zω_star, σ_ω_star, m[:spr])
ζ_bw_zw = ζ_bw/ζ_zw
# elasticities wrt σ_ω
ζ_bσ_ω = σ_ω_star * (((1 - μ_estar*dGdσstar/dΓdσstar) /
(1 - μ_estar*dGdω_star/dΓdω_star) - 1)*dΓdσstar*m[:spr] + μ_estar*nkstar*
(dGdω_star*d2Γdωdσstar - dΓdω_star*d2Gdωdσstar)/ΓμGprime^2) /
((1 - Γstar)*m[:spr] + dΓdω_star/ΓμGprime*(1-nkstar))
ζ_zσ_ω = σ_ω_star * (dΓdσstar - μ_estar*dGdσstar) / ΓμG
m[:ζ_spσ_ω] = (ζ_bw_zw*ζ_zσ_ω - ζ_bσ_ω) / (1-ζ_bw_zw)
# elasticities wrt μ_e
if subspec(m) in ["ss2", "ss5"]
ζ_bμ_e = μ_estar * (nkstar*dΓdω_star*dGdω_star/ΓμGprime+dΓdω_star*Gstar*m[:spr]) /
((1-Γstar)*ΓμGprime*m[:spr] + dΓdω_star*(1-nkstar))
else
ζ_bμ_e = -μ_estar * (nkstar*dΓdω_star*dGdω_star/ΓμGprime+dΓdω_star*Gstar*m[:spr]) /
((1-Γstar)*ΓμGprime*m[:spr] + dΓdω_star*(1-nkstar))
end
ζ_zμ_e = -μ_estar*Gstar/ΓμG
m[:ζ_spμ_e] = (ζ_bw_zw*ζ_zμ_e - ζ_bμ_e) / (1-ζ_bw_zw)
# some ratios/elasticities
Rkstar = m[:spr]*m[:π_star]*m[:rstar] # (r_k_star+1-δ)/Upsilon*π_star
ζ_gw = dGdω_star/Gstar*ωbarstar
ζ_Gσ_ω = dGdσstar/Gstar*σ_ω_star
# elasticities for the net worth evolution
m[:ζ_nRk] = m[:γ_star]*Rkstar/m[:π_star]/exp(m[:z_star])*(1+Rhostar)*(1 - μ_estar*Gstar*(1 - ζ_gw/ζ_zw))
if subspec(m) in ["ss2", "ss5"]
m[:ζ_nR] = m[:γ_star]/m[:β]*(1+Rhostar)*(1 - nkstar + μ_estar*Gstar*m[:spr]*ζ_gw/ζ_zw)
m[:ζ_nqk] = m[:γ_star]*Rkstar/m[:π_star]/exp(m[:z_star])*(1+Rhostar)*(1 - μ_estar*Gstar*(1+ζ_gw/ζ_zw/Rhostar)) - m[:γ_star]/m[:β]*(1+Rhostar)
m[:ζ_nn] = m[:γ_star]/m[:β] + m[:γ_star]*Rkstar/m[:π_star]/exp(m[:z_star])*(1+Rhostar)*μ_estar*Gstar*ζ_gw/ζ_zw/Rhostar
else
m[:ζ_nR] = m[:γ_star]*betabar_inverse*(1+Rhostar)*(1 - nkstar + μ_estar*Gstar*m[:spr]*ζ_gw/ζ_zw)
m[:ζ_nqk] = m[:γ_star]*Rkstar/m[:π_star]/exp(m[:z_star])*(1+Rhostar)*(1 - μ_estar*Gstar*(1+ζ_gw/ζ_zw/Rhostar)) - m[:γ_star]*betabar_inverse*(1+Rhostar)
m[:ζ_nn] = m[:γ_star]*betabar_inverse + m[:γ_star]*Rkstar/m[:π_star]/exp(m[:z_star])*(1+Rhostar)*μ_estar*Gstar*ζ_gw/ζ_zw/Rhostar
end
m[:ζ_nμ_e] = m[:γ_star]*Rkstar/m[:π_star]/exp(m[:z_star])*(1+Rhostar)*μ_estar*Gstar*(1 - ζ_gw*ζ_zμ_e/ζ_zw)
m[:ζ_nσ_ω] = m[:γ_star]*Rkstar/m[:π_star]/exp(m[:z_star])*(1+Rhostar)*μ_estar*Gstar*(ζ_Gσ_ω-ζ_gw/ζ_zw*ζ_zσ_ω)
return m
end
function model_settings!(m::Model990)
default_settings!(m)
# Data
m <= Setting(:data_id, 2, "Dataset identifier")
m <= Setting(:cond_full_names, [:obs_gdp, :obs_corepce, :obs_spread, :obs_nominalrate, :obs_longrate],
"Observables used in conditional forecasts")
m <= Setting(:cond_semi_names, [:obs_spread, :obs_nominalrate, :obs_longrate],
"Observables used in semiconditional forecasts")
# Forecast
m <= Setting(:shockdec_startdate, Nullable(quartertodate("2007-Q1")))
end
"""
```
shock_groupings(m::Model990)
```
Returns a `Vector{ShockGroup}`, which must be passed in to
`plot_shock_decomposition`. See `?ShockGroup` for details.
"""
function shock_groupings(m::Model990)
gov = ShockGroup("g", [:g_sh], RGB(0.70, 0.13, 0.13)) # firebrick
bet = ShockGroup("b", [:b_sh], RGB(0.3, 0.3, 1.0))
fin = ShockGroup("FF", [:γ_sh, :μ_e_sh, :σ_ω_sh], RGB(0.29, 0.0, 0.51)) # indigo
tfp = ShockGroup("z", [:z_sh], RGB(1.0, 0.55, 0.0)) # darkorange
pmu = ShockGroup("p-mkp", [:λ_f_sh], RGB(0.60, 0.80, 0.20)) # yellowgreen
wmu = ShockGroup("w-mkp", [:λ_w_sh], RGB(0.0, 0.5, 0.5)) # teal
pol = ShockGroup("pol", vcat([:rm_sh], [Symbol("rm_shl$i") for i = 1:n_mon_anticipated_shocks(m)]),
RGB(1.0, 0.84, 0.0)) # gold
pis = ShockGroup("pi-LR", [:π_star_sh], RGB(1.0, 0.75, 0.793)) # pink
mei = ShockGroup("mu", [:μ_sh], :cyan)
mea = ShockGroup("me", [:lr_sh, :tfp_sh, :gdpdef_sh, :corepce_sh], RGB(0.0, 0.8, 0.0))
zpe = ShockGroup("zp", [:zp_sh], RGB(0.0, 0.3, 0.0))
det = ShockGroup("dt", [:dettrend], :gray40)
return [gov, bet, fin, tfp, pmu, wmu, pol, pis, mei, mea, zpe, det]
end
| {
"pile_set_name": "Github"
} |
<snippet>
<content><![CDATA[
Do
$0
Loop Until ${1:statement}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>do</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.vbs</scope>
<description>Do Loop Until</description>
</snippet>
| {
"pile_set_name": "Github"
} |
#
# Makefile for the drm device driver. This driver provides support for the
# Direct Rendering Infrastructure (DRI) in XFree86 4.1.0 and higher.
ccflags-y := -Iinclude/drm
hostprogs-y := mkregtable
quiet_cmd_mkregtable = MKREGTABLE $@
cmd_mkregtable = $(obj)/mkregtable $< > $@
$(obj)/rn50_reg_safe.h: $(src)/reg_srcs/rn50 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/r100_reg_safe.h: $(src)/reg_srcs/r100 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/r200_reg_safe.h: $(src)/reg_srcs/r200 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/rv515_reg_safe.h: $(src)/reg_srcs/rv515 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/r300_reg_safe.h: $(src)/reg_srcs/r300 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/r420_reg_safe.h: $(src)/reg_srcs/r420 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/rs600_reg_safe.h: $(src)/reg_srcs/rs600 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/r600_reg_safe.h: $(src)/reg_srcs/r600 $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/evergreen_reg_safe.h: $(src)/reg_srcs/evergreen $(obj)/mkregtable
$(call if_changed,mkregtable)
$(obj)/r100.o: $(obj)/r100_reg_safe.h $(obj)/rn50_reg_safe.h
$(obj)/r200.o: $(obj)/r200_reg_safe.h
$(obj)/rv515.o: $(obj)/rv515_reg_safe.h
$(obj)/r300.o: $(obj)/r300_reg_safe.h
$(obj)/r420.o: $(obj)/r420_reg_safe.h
$(obj)/rs600.o: $(obj)/rs600_reg_safe.h
$(obj)/r600_cs.o: $(obj)/r600_reg_safe.h
$(obj)/evergreen_cs.o: $(obj)/evergreen_reg_safe.h
radeon-y := radeon_drv.o radeon_cp.o radeon_state.o radeon_mem.o \
radeon_irq.o r300_cmdbuf.o r600_cp.o
# add KMS driver
radeon-y += radeon_device.o radeon_asic.o radeon_kms.o \
radeon_atombios.o radeon_agp.o atombios_crtc.o radeon_combios.o \
atom.o radeon_fence.o radeon_ttm.o radeon_object.o radeon_gart.o \
radeon_legacy_crtc.o radeon_legacy_encoders.o radeon_connectors.o \
radeon_encoders.o radeon_display.o radeon_cursor.o radeon_i2c.o \
radeon_clocks.o radeon_fb.o radeon_gem.o radeon_ring.o radeon_irq_kms.o \
radeon_cs.o radeon_bios.o radeon_benchmark.o r100.o r300.o r420.o \
rs400.o rs600.o rs690.o rv515.o r520.o r600.o rv770.o radeon_test.o \
r200.o radeon_legacy_tv.o r600_cs.o r600_blit.o r600_blit_shaders.o \
r600_blit_kms.o radeon_pm.o atombios_dp.o r600_audio.o r600_hdmi.o \
evergreen.o evergreen_cs.o
radeon-$(CONFIG_COMPAT) += radeon_ioc32.o
radeon-$(CONFIG_VGA_SWITCHEROO) += radeon_atpx_handler.o
radeon-$(CONFIG_ACPI) += radeon_acpi.o
obj-$(CONFIG_DRM_RADEON)+= radeon.o
| {
"pile_set_name": "Github"
} |
/****************************************************************************
Copyright (c) 2013-2015 scutgame.com
http://www.scutgame.com
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.
****************************************************************************/
using ZyGames.Framework.Common.Configuration;
using ZyGames.Framework.Config;
using ZyGames.Framework.Event;
using ZyGames.Framework.Model;
namespace ZyGames.Framework.Cache.Generic
{
/// <summary>
/// The cache setting info.
/// </summary>
public class CacheSetting
{
private CacheSection _cacheConfig;
/// <summary>
/// The cache setting init.
/// </summary>
public CacheSetting()
{
AutoRunEvent = true;
_cacheConfig = ConfigManager.Configger.GetFirstOrAddConfig<CacheSection>();
}
/// <summary>
/// is auto run listen event.
/// </summary>
public bool AutoRunEvent { get; set; }
/// <summary>
/// The cache expiry interval.
/// </summary>
public int ExpiredInterval
{
get { return _cacheConfig.ExpiredInterval; }
set { _cacheConfig.ExpiredInterval = value; }
}
/// <summary>
/// The cache update interval.
/// </summary>
public int UpdateInterval
{
get { return _cacheConfig.UpdateInterval; }
set { _cacheConfig.UpdateInterval = value; }
}
/// <summary>
/// Redis data is storage to Db.
/// </summary>
public bool IsStorageToDb
{
get { return _cacheConfig.IsStorageToDb; }
set { _cacheConfig.IsStorageToDb = value; }
}
/// <summary>
/// The entity has be changed event notify.
/// </summary>
public event EntityChangedNotifyEvent ChangedHandle;
internal void OnChangedNotify(AbstractEntity sender, CacheItemEventArgs e)
{
if (ChangedHandle != null)
{
ChangedHandle(sender, e);
}
}
}
} | {
"pile_set_name": "Github"
} |
//===- RewriteBuffer.h - Buffer rewriting interface -------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_REWRITE_CORE_REWRITEBUFFER_H
#define LLVM_CLANG_REWRITE_CORE_REWRITEBUFFER_H
#include "clang/Basic/LLVM.h"
#include "clang/Rewrite/Core/DeltaTree.h"
#include "clang/Rewrite/Core/RewriteRope.h"
#include "llvm/ADT/StringRef.h"
namespace clang {
/// RewriteBuffer - As code is rewritten, SourceBuffer's from the original
/// input with modifications get a new RewriteBuffer associated with them. The
/// RewriteBuffer captures the modified text itself as well as information used
/// to map between SourceLocation's in the original input and offsets in the
/// RewriteBuffer. For example, if text is inserted into the buffer, any
/// locations after the insertion point have to be mapped.
class RewriteBuffer {
friend class Rewriter;
/// Deltas - Keep track of all the deltas in the source code due to insertions
/// and deletions.
DeltaTree Deltas;
RewriteRope Buffer;
public:
using iterator = RewriteRope::const_iterator;
iterator begin() const { return Buffer.begin(); }
iterator end() const { return Buffer.end(); }
unsigned size() const { return Buffer.size(); }
/// Initialize - Start this rewrite buffer out with a copy of the unmodified
/// input buffer.
void Initialize(const char *BufStart, const char *BufEnd) {
Buffer.assign(BufStart, BufEnd);
}
void Initialize(StringRef Input) {
Initialize(Input.begin(), Input.end());
}
/// Write to \p Stream the result of applying all changes to the
/// original buffer.
/// Note that it isn't safe to use this function to overwrite memory mapped
/// files in-place (PR17960). Consider using a higher-level utility such as
/// Rewriter::overwriteChangedFiles() instead.
///
/// The original buffer is not actually changed.
raw_ostream &write(raw_ostream &Stream) const;
/// RemoveText - Remove the specified text.
void RemoveText(unsigned OrigOffset, unsigned Size,
bool removeLineIfEmpty = false);
/// InsertText - Insert some text at the specified point, where the offset in
/// the buffer is specified relative to the original SourceBuffer. The
/// text is inserted after the specified location.
void InsertText(unsigned OrigOffset, StringRef Str,
bool InsertAfter = true);
/// InsertTextBefore - Insert some text before the specified point, where the
/// offset in the buffer is specified relative to the original
/// SourceBuffer. The text is inserted before the specified location. This is
/// method is the same as InsertText with "InsertAfter == false".
void InsertTextBefore(unsigned OrigOffset, StringRef Str) {
InsertText(OrigOffset, Str, false);
}
/// InsertTextAfter - Insert some text at the specified point, where the
/// offset in the buffer is specified relative to the original SourceBuffer.
/// The text is inserted after the specified location.
void InsertTextAfter(unsigned OrigOffset, StringRef Str) {
InsertText(OrigOffset, Str);
}
/// ReplaceText - This method replaces a range of characters in the input
/// buffer with a new string. This is effectively a combined "remove/insert"
/// operation.
void ReplaceText(unsigned OrigOffset, unsigned OrigLength,
StringRef NewStr);
private:
/// getMappedOffset - Given an offset into the original SourceBuffer that this
/// RewriteBuffer is based on, map it into the offset space of the
/// RewriteBuffer. If AfterInserts is true and if the OrigOffset indicates a
/// position where text is inserted, the location returned will be after any
/// inserted text at the position.
unsigned getMappedOffset(unsigned OrigOffset,
bool AfterInserts = false) const{
return Deltas.getDeltaAt(2*OrigOffset+AfterInserts)+OrigOffset;
}
/// AddInsertDelta - When an insertion is made at a position, this
/// method is used to record that information.
void AddInsertDelta(unsigned OrigOffset, int Change) {
return Deltas.AddDelta(2*OrigOffset, Change);
}
/// AddReplaceDelta - When a replacement/deletion is made at a position, this
/// method is used to record that information.
void AddReplaceDelta(unsigned OrigOffset, int Change) {
return Deltas.AddDelta(2*OrigOffset+1, Change);
}
};
} // namespace clang
#endif // LLVM_CLANG_REWRITE_CORE_REWRITEBUFFER_H
| {
"pile_set_name": "Github"
} |
LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY
The authors and publisher of the book "UNIX Network Programming" have
used their best efforts in preparing this software. These efforts
include the development, research, and testing of the theories and
programs to determine their effectiveness. The authors and publisher
make no warranty of any kind, express or implied, with regard to
these programs or the documentation contained in the book. The authors
and publisher shall not be liable in any event for incidental or
consequential damages in connection with, or arising out of, the
furnishing, performance, or use of these programs.
| {
"pile_set_name": "Github"
} |
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
"use strict";
function TeamcityReport(opts) {
opts = opts || {};
this.file = opts.file || null;
this.blockName = opts.blockName || 'Code Coverage Summary';
}
function lineForKey(value, teamcityVar) {
return '##teamcity[buildStatisticValue key=\'' + teamcityVar + '\' value=\'' + value + '\']';
}
TeamcityReport.prototype.onStart = function (node, context) {
var metrics = node.getCoverageSummary(),
cw;
cw = context.writer.writeFile(this.file);
cw.println('');
cw.println('##teamcity[blockOpened name=\''+ this.blockName +'\']');
//Statements Covered
cw.println(lineForKey(metrics.statements.covered, 'CodeCoverageAbsBCovered'));
cw.println(lineForKey(metrics.statements.total, 'CodeCoverageAbsBTotal'));
//Branches Covered
cw.println(lineForKey(metrics.branches.covered, 'CodeCoverageAbsRCovered'));
cw.println(lineForKey(metrics.branches.total, 'CodeCoverageAbsRTotal'));
//Functions Covered
cw.println(lineForKey(metrics.functions.covered, 'CodeCoverageAbsMCovered'));
cw.println(lineForKey(metrics.functions.total, 'CodeCoverageAbsMTotal'));
//Lines Covered
cw.println(lineForKey(metrics.lines.covered, 'CodeCoverageAbsLCovered'));
cw.println(lineForKey(metrics.lines.total, 'CodeCoverageAbsLTotal'));
cw.println('##teamcity[blockClosed name=\''+ this.blockName +'\']');
cw.close();
};
module.exports = TeamcityReport;
| {
"pile_set_name": "Github"
} |
syntax = "proto3";
package POGOProtos.Map.Fort;
message FortSummary {
string fort_summary_id = 1;
int64 last_modified_timestamp_ms = 2;
double latitude = 3;
double longitude = 4;
}
| {
"pile_set_name": "Github"
} |
@import url(normalize.css);
@import "theme/colors";
@import "theme/icons";
@import "theme/general";
@import "theme/utilites";
@import "theme/theme";
@import "theme/post";
@import "theme/third-party";
@import "theme/pagination";
@import "theme/footer";
@import "theme/media";
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 157a1cf487ff418438e2c95295262b32
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
{
"ver": "2.2.0",
"uuid": "9139051d-f174-4c03-92a7-e4a39902fac4",
"type": "sprite",
"wrapMode": "clamp",
"filterMode": "bilinear",
"premultiplyAlpha": false,
"subMetas": {
"heitao_small": {
"ver": "1.0.3",
"uuid": "71d34242-1ca6-4e9c-8258-9ef646e5e856",
"rawTextureUuid": "9139051d-f174-4c03-92a7-e4a39902fac4",
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 16,
"height": 16,
"rawWidth": 16,
"rawHeight": 16,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"subMetas": {}
}
}
} | {
"pile_set_name": "Github"
} |
require "def.k"
// `requires Z ==Int incPos(Y)` - Function in requires, used in RHS. Does not affect matching.
module DEF02-SPEC
imports DEF
rule <k> start X => end X +Int 1 </k>
<var> _ </var>
requires X >=Int 0
rule <k> mid Y => end Z </k>
<var> _ </var>
requires Z ==Int incPos(Y)
[trusted]
endmodule
| {
"pile_set_name": "Github"
} |
// { dg-do run { target c++14 } }
// Copyright (C) 2015-2019 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 8.2.1 Class template shared_ptr [memory.smartptr.shared]
#include <experimental/memory>
#include <testsuite_hooks.h>
struct A { };
// C++14 §20.8.2.2.4
// swap
int
test01()
{
A * const a1 = new A[5];
A * const a2 = new A[5];
std::experimental::shared_ptr<A[5]> p1(a1);
std::experimental::shared_ptr<A[5]> p2(a2);
p1.swap(p2);
VERIFY( p1.get() == a2 );
VERIFY( p2.get() == a1 );
return 0;
}
int
main()
{
test01();
return 0;
}
| {
"pile_set_name": "Github"
} |
@echo off
:##############################################################################
:# #
:# Filename hosts.bat #
:# #
:# Description Open Notepad to edit the system's /etc/hosts file #
:# #
:# Notes The hosts file can be seen by all users, #
:# but it can only be updated by administrators. #
:# This script attemps to switch to administrator mode, #
:# to avoid getting stuck with changes that can't be saved. #
:# #
:# History #
:# 2013-09-10 JFL [email protected] created this script. #
:# 2018-06-28 JFL Use elevate.exe if it is available, else do without. #
:# Added option -X to test what command is executed. #
:# 2018-07-23 JFL Exit from the script without waiting for notepad to exit. #
:# 2018-08-27 JFL Added -V option to display the script version. #
:# 2018-09-17 JFL Added the ability to search entries in the hosts file. #
:# Added a help screen. #
:# #
:# © Copyright 2016-2018 Hewlett Packard Enterprise Development LP #
:# Licensed under the Apache 2.0 license www.apache.org/licenses/LICENSE-2.0 #
:##############################################################################
setlocal EnableExtensions EnableDelayedExpansion
set "VERSION=2018-09-17"
goto :main
:# runas /user:Administrator "%windir%\System32\notepad.exe" "%windir%\System32\Drivers\etc\hosts"
:# runas /user:%USERDOMAIN%\%USERNAME% "%windir%\System32\notepad.exe" "%windir%\System32\Drivers\etc\hosts"
:# Display arguments, skipping spaces ahead
:echo
echo %*
exit /b
:# Quote file pathnames that require it. %1=Input/output variable.
:condquote
:# Assumes EnableExtensions EnableDelayedExpansion
:# If the value is empty, don't go any further.
if not defined %1 set "%1=""" & exit /b
:# Remove double quotes inside %1. (Fails if %1 is empty, which we excluded above)
set ^"%1=!%1:"=!"
:# Look for any special character that needs "quoting". See list from (cmd /?).
:# Added "@" that needs quoting ahead of commands.
:# Added "|&<>" that are not valid in file names, but that do need quoting if used in an argument string.
echo."!%1!"|findstr /C:" " /C:"&" /C:"(" /C:")" /C:"[" /C:"]" /C:"{" /C:"}" /C:"^^" /C:"=" /C:";" /C:"!" /C:"'" /C:"+" /C:"," /C:"`" /C:"~" /C:"@" /C:"|" /C:"&" /C:"<" /C:">" >NUL
if not errorlevel 1 set %1="!%1!"
exit /b
:# Test if the user has administrator rights
:IsAdmin
>NUL 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
goto :eof
:help
echo hosts file manager
echo.
echo Usage: hosts [OPTIONS] [NAMES]
echo.
echo Options:
echo -? Display this help screen and exit
echo -V Display the script version and exit
echo -X Display the command to run, but don't run it
echo.
echo Names: List of names to search in the hosts file.
echo Default: Edit the hosts file.
echo.
echo Note: When started from a non-Administrator Command Prompt, Notepad cannot
echo save the hosts file.
echo In this case, to prevent this problem, this script attemps to switch to
echo administrator mode. For that, it needs the free elevate.exe tool,
echo available at: http://www.winability.com/elevate
echo If you don't have elevate.exe in your PATH, or don't want to use it,
echo always run this script in an Administrator Command Prompt.
exit /b
:##############################################################################
:# Main routine
:main
set "ELEVATE="
set "EXEC=start"
set "NOTEPAD=%windir%\System32\notepad.exe"
set "HOSTS=%windir%\System32\Drivers\etc\hosts"
goto :get_arg
:next_arg
shift
:get_arg
if [%1]==[] goto :edit_hosts
if [%1]==[-V] (echo %VERSION%) & exit /b &:# Display the script version and exit
if [%1]==[-X] set "EXEC=call :echo" & goto :next_arg &:# Display the command, but don't run it
if [%1]==[-?] goto :help &:# Display the help screen and exit
if [%1]==[/?] goto :help &:# Display the help screen and exit
:##############################################################################
:# Search entries in the hosts file
:show_ip
if "%EXEC%"=="start" set "EXEC="
%EXEC% findstr /R "\<%~1\>" %HOSTS%
shift
if not [%1]==[] goto :show_ip
exit /b
:##############################################################################
:# Edit the hosts file
:edit_hosts
:# Check if we're running as administrator already
call :IsAdmin
if not errorlevel 1 goto :go &:# We are. Go run the notepad command directly.
:# We're not running as administrator. Find a way to switch to administrator mode.
:# The elevate tool from http://www.winability.com/elevate is the most convenient,
:# as it avoids the need for prompting the user with the admin password.
where elevate >NUL 2>&1 &:# Check if elevate.exe is available
if not errorlevel 1 set "ELEVATE=elevate" & goto :go
echo Warning: This shell is not running as Administrator, so you won't be allowed to save any change.
:go
call :condquote NOTEPAD
call :condquote HOSTS
%EXEC% %ELEVATE% %NOTEPAD% %HOSTS%
| {
"pile_set_name": "Github"
} |
/* crypto/asn1/f_enum.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/buffer.h>
#include <openssl/asn1.h>
/* Based on a_int.c: equivalent ENUMERATED functions */
int i2a_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *a)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
char buf[2];
if (a == NULL)
return (0);
if (a->length == 0) {
if (BIO_write(bp, "00", 2) != 2)
goto err;
n = 2;
} else {
for (i = 0; i < a->length; i++) {
if ((i != 0) && (i % 35 == 0)) {
if (BIO_write(bp, "\\\n", 2) != 2)
goto err;
n += 2;
}
buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
if (BIO_write(bp, buf, 2) != 2)
goto err;
n += 2;
}
}
return (n);
err:
return (-1);
}
int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size)
{
int ret = 0;
int i, j, k, m, n, again, bufsize;
unsigned char *s = NULL, *sp;
unsigned char *bufp;
int num = 0, slen = 0, first = 1;
bs->type = V_ASN1_ENUMERATED;
bufsize = BIO_gets(bp, buf, size);
for (;;) {
if (bufsize < 1)
goto err_sl;
i = bufsize;
if (buf[i - 1] == '\n')
buf[--i] = '\0';
if (i == 0)
goto err_sl;
if (buf[i - 1] == '\r')
buf[--i] = '\0';
if (i == 0)
goto err_sl;
again = (buf[i - 1] == '\\');
for (j = 0; j < i; j++) {
if (!(((buf[j] >= '0') && (buf[j] <= '9')) ||
((buf[j] >= 'a') && (buf[j] <= 'f')) ||
((buf[j] >= 'A') && (buf[j] <= 'F')))) {
i = j;
break;
}
}
buf[i] = '\0';
/*
* We have now cleared all the crap off the end of the line
*/
if (i < 2)
goto err_sl;
bufp = (unsigned char *)buf;
if (first) {
first = 0;
if ((bufp[0] == '0') && (buf[1] == '0')) {
bufp += 2;
i -= 2;
}
}
k = 0;
i -= again;
if (i % 2 != 0) {
ASN1err(ASN1_F_A2I_ASN1_ENUMERATED, ASN1_R_ODD_NUMBER_OF_CHARS);
goto err;
}
i /= 2;
if (num + i > slen) {
if (s == NULL)
sp = (unsigned char *)OPENSSL_malloc((unsigned int)num +
i * 2);
else
sp = (unsigned char *)OPENSSL_realloc(s,
(unsigned int)num +
i * 2);
if (sp == NULL) {
ASN1err(ASN1_F_A2I_ASN1_ENUMERATED, ERR_R_MALLOC_FAILURE);
if (s != NULL)
OPENSSL_free(s);
goto err;
}
s = sp;
slen = num + i * 2;
}
for (j = 0; j < i; j++, k += 2) {
for (n = 0; n < 2; n++) {
m = bufp[k + n];
if ((m >= '0') && (m <= '9'))
m -= '0';
else if ((m >= 'a') && (m <= 'f'))
m = m - 'a' + 10;
else if ((m >= 'A') && (m <= 'F'))
m = m - 'A' + 10;
else {
ASN1err(ASN1_F_A2I_ASN1_ENUMERATED,
ASN1_R_NON_HEX_CHARACTERS);
goto err;
}
s[num + j] <<= 4;
s[num + j] |= m;
}
}
num += i;
if (again)
bufsize = BIO_gets(bp, buf, size);
else
break;
}
bs->length = num;
bs->data = s;
ret = 1;
err:
if (0) {
err_sl:
ASN1err(ASN1_F_A2I_ASN1_ENUMERATED, ASN1_R_SHORT_LINE);
}
return (ret);
}
| {
"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.
*/
package org.apache.hadoop.fs.permission;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.io.*;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Store permission related information.
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Unstable
public class PermissionStatus implements Writable {
static final WritableFactory FACTORY = new WritableFactory() {
@Override
public Writable newInstance() { return new PermissionStatus(); }
};
static { // register a ctor
WritableFactories.setFactory(PermissionStatus.class, FACTORY);
}
/** Create an immutable {@link PermissionStatus} object. */
public static PermissionStatus createImmutable(
String user, String group, FsPermission permission) {
return new PermissionStatus(user, group, permission) {
@Override
public PermissionStatus applyUMask(FsPermission umask) {
throw new UnsupportedOperationException();
}
@Override
public void readFields(DataInput in) throws IOException {
throw new UnsupportedOperationException();
}
};
}
private String username;
private String groupname;
private FsPermission permission;
private PermissionStatus() {}
/** Constructor */
public PermissionStatus(String user, String group, FsPermission permission) {
username = user;
groupname = group;
this.permission = permission;
}
/** Return user name */
public String getUserName() {return username;}
/** Return group name */
public String getGroupName() {return groupname;}
/** Return permission */
public FsPermission getPermission() {return permission;}
/**
* Apply umask.
* @see FsPermission#applyUMask(FsPermission)
*/
public PermissionStatus applyUMask(FsPermission umask) {
permission = permission.applyUMask(umask);
return this;
}
@Override
public void readFields(DataInput in) throws IOException {
username = Text.readString(in, Text.DEFAULT_MAX_LEN);
groupname = Text.readString(in, Text.DEFAULT_MAX_LEN);
permission = FsPermission.read(in);
}
@Override
public void write(DataOutput out) throws IOException {
write(out, username, groupname, permission);
}
/**
* Create and initialize a {@link PermissionStatus} from {@link DataInput}.
*/
public static PermissionStatus read(DataInput in) throws IOException {
PermissionStatus p = new PermissionStatus();
p.readFields(in);
return p;
}
/**
* Serialize a {@link PermissionStatus} from its base components.
*/
public static void write(DataOutput out,
String username,
String groupname,
FsPermission permission) throws IOException {
Text.writeString(out, username, Text.DEFAULT_MAX_LEN);
Text.writeString(out, groupname, Text.DEFAULT_MAX_LEN);
permission.write(out);
}
@Override
public String toString() {
return username + ":" + groupname + ":" + permission;
}
}
| {
"pile_set_name": "Github"
} |
package ml.docilealligator.infinityforreddit.BottomSheetFragment;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.deishelon.roundedbottomsheet.RoundedBottomSheetDialogFragment;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.R;
/**
* A simple {@link Fragment} subclass.
*/
public class CopyTextBottomSheetFragment extends RoundedBottomSheetDialogFragment {
public static final String EXTRA_RAW_TEXT = "ERT";
public static final String EXTRA_MARKDOWN = "EM";
@BindView(R.id.copy_raw_text_text_view_copy_text_bottom_sheet_fragment)
TextView copyRawTextTextView;
@BindView(R.id.copy_markdown_text_view_copy_text_bottom_sheet_fragment)
TextView copyMarkdownTextView;
@BindView(R.id.copy_all_raw_text_text_view_copy_text_bottom_sheet_fragment)
TextView copyAllRawTextTextView;
@BindView(R.id.copy_all_markdown_text_view_copy_text_bottom_sheet_fragment)
TextView copyAllMarkdownTextView;
private Activity activity;
public CopyTextBottomSheetFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_copy_text_bottom_sheet, container, false);
ButterKnife.bind(this, rootView);
String rawText = getArguments().getString(EXTRA_RAW_TEXT);
String markdownText = getArguments().getString(EXTRA_MARKDOWN);
copyRawTextTextView.setOnClickListener(view -> {
showCopyDialog(rawText);
dismiss();
});
copyAllRawTextTextView.setOnClickListener(view -> {
copyText(rawText);
dismiss();
});
if (markdownText != null) {
copyMarkdownTextView.setOnClickListener(view -> {
showCopyDialog(markdownText);
dismiss();
});
copyAllMarkdownTextView.setOnClickListener(view -> {
copyText(markdownText);
dismiss();
});
} else {
copyMarkdownTextView.setVisibility(View.GONE);
copyAllMarkdownTextView.setVisibility(View.GONE);
}
return rootView;
}
private void showCopyDialog(String text) {
LayoutInflater inflater = activity.getLayoutInflater();
View layout = inflater.inflate(R.layout.copy_text_material_dialog, null);
TextView textView = layout.findViewById(R.id.text_view_copy_text_material_dialog);
textView.setText(text);
new MaterialAlertDialogBuilder(activity, R.style.CopyTextMaterialAlertDialogTheme)
.setTitle(R.string.copy_text)
.setView(layout)
.setPositiveButton(R.string.copy_all, (dialogInterface, i) -> copyText(text))
.setNegativeButton(R.string.cancel, null)
.show();
}
private void copyText(String text) {
ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null) {
ClipData clip = ClipData.newPlainText("simple text", text);
clipboard.setPrimaryClip(clip);
Toast.makeText(activity, R.string.copy_success, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, R.string.copy_link_failed, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
activity = (Activity) context;
}
}
| {
"pile_set_name": "Github"
} |
// SampSharp
// Copyright 2020 Tim Potze
//
// 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.
using Microsoft.Extensions.DependencyInjection;
using SampSharp.Entities.SAMP.Commands;
using static SampSharp.Entities.SAMP.SampEntities;
namespace SampSharp.Entities.SAMP
{
/// <summary>
/// Provides methods for enabling SA:MP systems in an <see cref="IEcsBuilder" /> instance.
/// </summary>
public static class SampEcsBuilderExtensions
{
/// <summary>
/// Enables player commands.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnablePlayerCommands(this IEcsBuilder builder)
{
return builder.UseMiddleware<PlayerCommandProcessingMiddleware>("OnPlayerCommandText");
}
/// <summary>
/// Enables RCON commands.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnableRconCommands(this IEcsBuilder builder)
{
return builder.UseMiddleware<RconCommandProcessingMiddleware>("OnRconCommand");
}
/// <summary>
/// Enables all actor, player related SA:MP events.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnableSampEvents(this IEcsBuilder builder)
{
return builder
.EnableActorEvents()
.EnablePlayerEvents()
.EnableObjectEvents()
.EnableRconEvents()
.EnableVehicleEvents();
}
/// <summary>
/// Enables all actor related SA:MP events.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnableActorEvents(this IEcsBuilder builder)
{
builder.EnableEvent<int, int>("OnActorStreamIn");
builder.EnableEvent<int, int>("OnActorStreamOut");
builder.UseMiddleware<EntityMiddleware>("OnActorStreamIn", 0, ActorType, true);
builder.UseMiddleware<EntityMiddleware>("OnActorStreamIn", 1, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnActorStreamOut", 0, ActorType, true);
builder.UseMiddleware<EntityMiddleware>("OnActorStreamOut", 1, PlayerType, true);
return builder;
}
/// <summary>
/// Enables all player related SA:MP events.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnablePlayerEvents(this IEcsBuilder builder)
{
builder.EnableEvent<int>("OnPlayerConnect");
builder.EnableEvent<int, int>("OnPlayerDisconnect");
builder.EnableEvent<int>("OnPlayerSpawn");
builder.EnableEvent<int, int, int>("OnPlayerDeath");
builder.EnableEvent<int, string>("OnPlayerText");
builder.EnableEvent<int, string>("OnPlayerCommandText");
builder.EnableEvent<int, int>("OnPlayerRequestClass");
builder.EnableEvent<int, int, bool>("OnPlayerEnterVehicle");
builder.EnableEvent<int, int>("OnPlayerExitVehicle");
builder.EnableEvent<int, int, int>("OnPlayerStateChange");
builder.EnableEvent<int>("OnPlayerEnterCheckpoint");
builder.EnableEvent<int>("OnPlayerLeaveCheckpoint");
builder.EnableEvent<int>("OnPlayerEnterRaceCheckpoint");
builder.EnableEvent<int>("OnPlayerLeaveRaceCheckpoint");
builder.EnableEvent<int>("OnPlayerRequestSpawn");
builder.EnableEvent<int, int>("OnPlayerPickUpPickup");
builder.EnableEvent<int, int>("OnPlayerSelectedMenuRow");
builder.EnableEvent<int>("OnPlayerExitedMenu");
builder.EnableEvent<int, int, int>("OnPlayerInteriorChange");
builder.EnableEvent<int, int, int>("OnPlayerKeyStateChange");
builder.EnableEvent<int>("OnPlayerUpdate");
builder.EnableEvent<int, int>("OnPlayerStreamIn");
builder.EnableEvent<int, int>("OnPlayerStreamOut");
builder.EnableEvent<int, int, float, int, int>("OnPlayerTakeDamage");
builder.EnableEvent<int, int, float, int, int>("OnPlayerGiveDamage");
builder.EnableEvent<int, int, float, int, int>("OnPlayerGiveDamageActor");
builder.EnableEvent<int, float, float, float>("OnPlayerClickMap");
builder.EnableEvent<int, int>("OnPlayerClickTextDraw");
builder.EnableEvent<int, int>("OnPlayerClickPlayerTextDraw");
builder.EnableEvent<int, int, int>("OnPlayerClickPlayer");
builder.EnableEvent<int, bool, int, int, float, float, float, float, float, float>("OnPlayerEditObject");
builder.EnableEvent<int, int, int, int, int, float, float, float, float, float, float, float, float, float>(
"OnPlayerEditAttachedObject");
builder.EnableEvent<int, int, int, int, float, float, float>("OnPlayerSelectObject");
builder.EnableEvent<int, int, int, int, float, float, float>("OnPlayerWeaponShot");
builder.EnableEvent<int, bool, int>("OnEnterExitModShop");
builder.EnableEvent<int, int, int, int, string>("OnDialogResponse");
builder.EnableEvent<int, string, int>("OnIncomingConnection"); // Don't swap out player id
void AddPlayerTarget(string callback)
{
builder.UseMiddleware<EntityMiddleware>(callback, 0, PlayerType, true);
}
builder.UseMiddleware<PlayerConnectMiddleware>("OnPlayerConnect");
builder.UseMiddleware<PlayerDisconnectMiddleware>("OnPlayerDisconnect");
AddPlayerTarget("OnPlayerSpawn");
AddPlayerTarget("OnPlayerDeath");
builder.UseMiddleware<EntityMiddleware>("OnPlayerDeath", 1, PlayerType, false);
AddPlayerTarget("OnPlayerText");
AddPlayerTarget("OnPlayerCommandText");
AddPlayerTarget("OnPlayerRequestClass");
AddPlayerTarget("OnPlayerEnterVehicle");
builder.UseMiddleware<EntityMiddleware>("OnPlayerEnterVehicle", 1, VehicleType, true);
AddPlayerTarget("OnPlayerExitVehicle");
builder.UseMiddleware<EntityMiddleware>("OnPlayerExitVehicle", 1, VehicleType, true);
AddPlayerTarget("OnPlayerStateChange");
AddPlayerTarget("OnPlayerEnterCheckpoint");
AddPlayerTarget("OnPlayerLeaveCheckpoint");
AddPlayerTarget("OnPlayerEnterRaceCheckpoint");
AddPlayerTarget("OnPlayerLeaveRaceCheckpoint");
AddPlayerTarget("OnPlayerRequestSpawn");
AddPlayerTarget("OnPlayerPickUpPickup");
builder.UseMiddleware<EntityMiddleware>("OnPlayerPickUpPickup", 1, SampEntities.PickupType, true);
AddPlayerTarget("OnPlayerSelectedMenuRow");
AddPlayerTarget("OnPlayerExitedMenu");
AddPlayerTarget("OnPlayerInteriorChange");
AddPlayerTarget("OnPlayerKeyStateChange");
AddPlayerTarget("OnPlayerUpdate");
AddPlayerTarget("OnPlayerStreamIn");
builder.UseMiddleware<EntityMiddleware>("OnPlayerStreamIn", 1, PlayerType, true);
AddPlayerTarget("OnPlayerStreamOut");
builder.UseMiddleware<EntityMiddleware>("OnPlayerStreamOut", 1, PlayerType, true);
AddPlayerTarget("OnPlayerTakeDamage");
builder.UseMiddleware<EntityMiddleware>("OnPlayerTakeDamage", 1, PlayerType, false);
AddPlayerTarget("OnPlayerGiveDamage");
builder.UseMiddleware<EntityMiddleware>("OnPlayerGiveDamage", 1, PlayerType, true);
AddPlayerTarget("OnPlayerGiveDamageActor");
builder.UseMiddleware<EntityMiddleware>("OnPlayerGiveDamageActor", 1, ActorType, true);
builder.UseMiddleware<PlayerClickMapMiddleware>("OnPlayerClickMap");
builder.UseMiddleware<TextDrawClickMiddleware>("OnPlayerClickTextDraw");
builder.UseMiddleware<PlayerTextDrawMiddleware>("OnPlayerClickPlayerTextDraw");
AddPlayerTarget("OnPlayerClickPlayer");
builder.UseMiddleware<EntityMiddleware>("OnPlayerClickPlayer", 1, PlayerType, true);
builder.UseMiddleware<PlayerEditObjectMiddleware>("OnPlayerEditObject");
builder.UseMiddleware<PlayerEditAttachedObjectMiddleware>("OnPlayerEditAttachedObject");
builder.UseMiddleware<PlayerSelectObjectMiddleware>("OnPlayerSelectObject");
builder.UseMiddleware<PlayerWeaponShotMiddleware>("OnPlayerWeaponShot");
AddPlayerTarget("OnEnterExitModShop");
AddPlayerTarget("OnDialogResponse");
return builder;
}
/// <summary>
/// Enables all object related SA:MP events.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnableObjectEvents(this IEcsBuilder builder)
{
builder.EnableEvent<int>("OnObjectMoved");
builder.EnableEvent<int, int>("OnPlayerObjectMoved");
builder.UseMiddleware<EntityMiddleware>("OnObjectMoved", 0, SampEntities.ObjectType, false);
builder.UseMiddleware<PlayerObjectMiddleware>("OnPlayerObjectMoved");
return builder;
}
/// <summary>
/// Enables all RCON related SA:MP events.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnableRconEvents(this IEcsBuilder builder)
{
builder.EnableEvent<string>("OnRconCommand");
builder.EnableEvent<string, string, bool>("OnRconLoginAttempt");
return builder;
}
/// <summary>
/// Enables all vehicle related SA:MP events.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The builder.</returns>
public static IEcsBuilder EnableVehicleEvents(this IEcsBuilder builder)
{
builder.EnableEvent<int>("OnVehicleSpawn");
builder.EnableEvent<int, int>("OnVehicleDeath");
builder.EnableEvent<int, int, int>("OnVehicleMod");
builder.EnableEvent<int, int, int>("OnVehiclePaintjob");
builder.EnableEvent<int, int, int, int>("OnVehicleRespray");
builder.EnableEvent<int, int>("OnVehicleDamageStatusUpdate");
builder.EnableEvent<int, int>("OnVehicleStreamIn");
builder.EnableEvent<int, int>("OnVehicleStreamOut");
builder.EnableEvent<int, int, int>("OnVehicleSirenStateChange");
builder.EnableEvent<int, int>("OnTrailerUpdate");
builder.EnableEvent<int, int, int, float, float, float, float, float, float>("OnUnoccupiedVehicleUpdate");
builder.UseMiddleware<EntityMiddleware>("OnVehicleSpawn", 0, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleDeath", 0, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleDeath", 1, PlayerType, false);
builder.UseMiddleware<EntityMiddleware>("OnVehicleMod", 0, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleMod", 1, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehiclePaintjob", 0, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehiclePaintjob", 1, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleRespray", 0, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleRespray", 1, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleDamageStatusUpdate", 0, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleDamageStatusUpdate", 1, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamIn", 0, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamIn", 1, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamOut", 0, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleStreamOut", 1, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleSirenStateChange", 0, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnVehicleSirenStateChange", 1, VehicleType, true);
builder.UseMiddleware<EntityMiddleware>("OnTrailerUpdate", 0, PlayerType, true);
builder.UseMiddleware<EntityMiddleware>("OnTrailerUpdate", 1, VehicleType, true);
builder.UseMiddleware<UnoccupiedVehicleUpdateMiddleware>("OnUnoccupiedVehicleUpdate");
return builder;
}
}
} | {
"pile_set_name": "Github"
} |
## Building and using Docker development images.
These Dockerfiles will create a MAVSDK development container image based on whichever flavour of Ubuntu or Fedora you prefer.
Docker images are built by the project and are hosted on Docker Hub.
You can use them simply by :
```bash
cd /whereever/MAVSDK
./run-docker.sh
```
Should you wish to create and use your own local images, use the following.
To create an image :
```bash
cd /whereever/MAVSDK/docker
docker build -t mavsdk/mavsdk-ubuntu-18.04 -f Dockerfile-Ubuntu-18.04 .
```
To use the image :
```bash
cd /whereever/MAVSDK
./run-docker.sh
```
This will create and run a container based on your image.
/whereever/MAVSDK will be mounted inside the container at /home/user/MAVSDK
```bash
user@a476023ed255:~/MAVSDK$
```
| {
"pile_set_name": "Github"
} |
from .special import *
from .slugify import *
__author__ = 'Val Neekman @ Neekware Inc. [@vneekman]'
__description__ = 'A Python slugify application that also handles Unicode'
__version__ = '4.0.1'
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
*
* Module Name: hwpci - Obtain PCI bus, device, and function numbers
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2015, Intel Corp.
* All rights reserved.
*
* 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,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("hwpci")
/* PCI configuration space values */
#define PCI_CFG_HEADER_TYPE_REG 0x0E
#define PCI_CFG_PRIMARY_BUS_NUMBER_REG 0x18
#define PCI_CFG_SECONDARY_BUS_NUMBER_REG 0x19
/* PCI header values */
#define PCI_HEADER_TYPE_MASK 0x7F
#define PCI_TYPE_BRIDGE 0x01
#define PCI_TYPE_CARDBUS_BRIDGE 0x02
typedef struct acpi_pci_device {
acpi_handle device;
struct acpi_pci_device *next;
} acpi_pci_device;
/* Local prototypes */
static acpi_status
acpi_hw_build_pci_list(acpi_handle root_pci_device,
acpi_handle pci_region,
struct acpi_pci_device **return_list_head);
static acpi_status
acpi_hw_process_pci_list(struct acpi_pci_id *pci_id,
struct acpi_pci_device *list_head);
static void acpi_hw_delete_pci_list(struct acpi_pci_device *list_head);
static acpi_status
acpi_hw_get_pci_device_info(struct acpi_pci_id *pci_id,
acpi_handle pci_device,
u16 *bus_number, u8 *is_bridge);
/*******************************************************************************
*
* FUNCTION: acpi_hw_derive_pci_id
*
* PARAMETERS: pci_id - Initial values for the PCI ID. May be
* modified by this function.
* root_pci_device - A handle to a PCI device object. This
* object must be a PCI Root Bridge having a
* _HID value of either PNP0A03 or PNP0A08
* pci_region - A handle to a PCI configuration space
* Operation Region being initialized
*
* RETURN: Status
*
* DESCRIPTION: This function derives a full PCI ID for a PCI device,
* consisting of a Segment number, Bus number, Device number,
* and function code.
*
* The PCI hardware dynamically configures PCI bus numbers
* depending on the bus topology discovered during system
* initialization. This function is invoked during configuration
* of a PCI_Config Operation Region in order to (possibly) update
* the Bus/Device/Function numbers in the pci_id with the actual
* values as determined by the hardware and operating system
* configuration.
*
* The pci_id parameter is initially populated during the Operation
* Region initialization. This function is then called, and is
* will make any necessary modifications to the Bus, Device, or
* Function number PCI ID subfields as appropriate for the
* current hardware and OS configuration.
*
* NOTE: Created 08/2010. Replaces the previous OSL acpi_os_derive_pci_id
* interface since this feature is OS-independent. This module
* specifically avoids any use of recursion by building a local
* temporary device list.
*
******************************************************************************/
acpi_status
acpi_hw_derive_pci_id(struct acpi_pci_id *pci_id,
acpi_handle root_pci_device, acpi_handle pci_region)
{
acpi_status status;
struct acpi_pci_device *list_head = NULL;
ACPI_FUNCTION_TRACE(hw_derive_pci_id);
if (!pci_id) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Build a list of PCI devices, from pci_region up to root_pci_device */
status =
acpi_hw_build_pci_list(root_pci_device, pci_region, &list_head);
if (ACPI_SUCCESS(status)) {
/* Walk the list, updating the PCI device/function/bus numbers */
status = acpi_hw_process_pci_list(pci_id, list_head);
/* Delete the list */
acpi_hw_delete_pci_list(list_head);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_build_pci_list
*
* PARAMETERS: root_pci_device - A handle to a PCI device object. This
* object is guaranteed to be a PCI Root
* Bridge having a _HID value of either
* PNP0A03 or PNP0A08
* pci_region - A handle to the PCI configuration space
* Operation Region
* return_list_head - Where the PCI device list is returned
*
* RETURN: Status
*
* DESCRIPTION: Builds a list of devices from the input PCI region up to the
* Root PCI device for this namespace subtree.
*
******************************************************************************/
static acpi_status
acpi_hw_build_pci_list(acpi_handle root_pci_device,
acpi_handle pci_region,
struct acpi_pci_device **return_list_head)
{
acpi_handle current_device;
acpi_handle parent_device;
acpi_status status;
struct acpi_pci_device *list_element;
struct acpi_pci_device *list_head = NULL;
/*
* Ascend namespace branch until the root_pci_device is reached, building
* a list of device nodes. Loop will exit when either the PCI device is
* found, or the root of the namespace is reached.
*/
current_device = pci_region;
while (1) {
status = acpi_get_parent(current_device, &parent_device);
if (ACPI_FAILURE(status)) {
/* Must delete the list before exit */
acpi_hw_delete_pci_list(*return_list_head);
return (status);
}
/* Finished when we reach the PCI root device (PNP0A03 or PNP0A08) */
if (parent_device == root_pci_device) {
*return_list_head = list_head;
return (AE_OK);
}
list_element = ACPI_ALLOCATE(sizeof(struct acpi_pci_device));
if (!list_element) {
/* Must delete the list before exit */
acpi_hw_delete_pci_list(*return_list_head);
return (AE_NO_MEMORY);
}
/* Put new element at the head of the list */
list_element->next = list_head;
list_element->device = parent_device;
list_head = list_element;
current_device = parent_device;
}
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_process_pci_list
*
* PARAMETERS: pci_id - Initial values for the PCI ID. May be
* modified by this function.
* list_head - Device list created by
* acpi_hw_build_pci_list
*
* RETURN: Status
*
* DESCRIPTION: Walk downward through the PCI device list, getting the device
* info for each, via the PCI configuration space and updating
* the PCI ID as necessary. Deletes the list during traversal.
*
******************************************************************************/
static acpi_status
acpi_hw_process_pci_list(struct acpi_pci_id *pci_id,
struct acpi_pci_device *list_head)
{
acpi_status status = AE_OK;
struct acpi_pci_device *info;
u16 bus_number;
u8 is_bridge = TRUE;
ACPI_FUNCTION_NAME(hw_process_pci_list);
ACPI_DEBUG_PRINT((ACPI_DB_OPREGION,
"Input PciId: Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X\n",
pci_id->segment, pci_id->bus, pci_id->device,
pci_id->function));
bus_number = pci_id->bus;
/*
* Descend down the namespace tree, collecting PCI device, function,
* and bus numbers. bus_number is only important for PCI bridges.
* Algorithm: As we descend the tree, use the last valid PCI device,
* function, and bus numbers that are discovered, and assign them
* to the PCI ID for the target device.
*/
info = list_head;
while (info) {
status = acpi_hw_get_pci_device_info(pci_id, info->device,
&bus_number, &is_bridge);
if (ACPI_FAILURE(status)) {
return (status);
}
info = info->next;
}
ACPI_DEBUG_PRINT((ACPI_DB_OPREGION,
"Output PciId: Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X "
"Status %X BusNumber %X IsBridge %X\n",
pci_id->segment, pci_id->bus, pci_id->device,
pci_id->function, status, bus_number, is_bridge));
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_delete_pci_list
*
* PARAMETERS: list_head - Device list created by
* acpi_hw_build_pci_list
*
* RETURN: None
*
* DESCRIPTION: Free the entire PCI list.
*
******************************************************************************/
static void acpi_hw_delete_pci_list(struct acpi_pci_device *list_head)
{
struct acpi_pci_device *next;
struct acpi_pci_device *previous;
next = list_head;
while (next) {
previous = next;
next = previous->next;
ACPI_FREE(previous);
}
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_get_pci_device_info
*
* PARAMETERS: pci_id - Initial values for the PCI ID. May be
* modified by this function.
* pci_device - Handle for the PCI device object
* bus_number - Where a PCI bridge bus number is returned
* is_bridge - Return value, indicates if this PCI
* device is a PCI bridge
*
* RETURN: Status
*
* DESCRIPTION: Get the device info for a single PCI device object. Get the
* _ADR (contains PCI device and function numbers), and for PCI
* bridge devices, get the bus number from PCI configuration
* space.
*
******************************************************************************/
static acpi_status
acpi_hw_get_pci_device_info(struct acpi_pci_id *pci_id,
acpi_handle pci_device,
u16 *bus_number, u8 *is_bridge)
{
acpi_status status;
acpi_object_type object_type;
u64 return_value;
u64 pci_value;
/* We only care about objects of type Device */
status = acpi_get_type(pci_device, &object_type);
if (ACPI_FAILURE(status)) {
return (status);
}
if (object_type != ACPI_TYPE_DEVICE) {
return (AE_OK);
}
/* We need an _ADR. Ignore device if not present */
status = acpi_ut_evaluate_numeric_object(METHOD_NAME__ADR,
pci_device, &return_value);
if (ACPI_FAILURE(status)) {
return (AE_OK);
}
/*
* From _ADR, get the PCI Device and Function and
* update the PCI ID.
*/
pci_id->device = ACPI_HIWORD(ACPI_LODWORD(return_value));
pci_id->function = ACPI_LOWORD(ACPI_LODWORD(return_value));
/*
* If the previous device was a bridge, use the previous
* device bus number
*/
if (*is_bridge) {
pci_id->bus = *bus_number;
}
/*
* Get the bus numbers from PCI Config space:
*
* First, get the PCI header_type
*/
*is_bridge = FALSE;
status = acpi_os_read_pci_configuration(pci_id,
PCI_CFG_HEADER_TYPE_REG,
&pci_value, 8);
if (ACPI_FAILURE(status)) {
return (status);
}
/* We only care about bridges (1=pci_bridge, 2=card_bus_bridge) */
pci_value &= PCI_HEADER_TYPE_MASK;
if ((pci_value != PCI_TYPE_BRIDGE) &&
(pci_value != PCI_TYPE_CARDBUS_BRIDGE)) {
return (AE_OK);
}
/* Bridge: Get the Primary bus_number */
status = acpi_os_read_pci_configuration(pci_id,
PCI_CFG_PRIMARY_BUS_NUMBER_REG,
&pci_value, 8);
if (ACPI_FAILURE(status)) {
return (status);
}
*is_bridge = TRUE;
pci_id->bus = (u16)pci_value;
/* Bridge: Get the Secondary bus_number */
status = acpi_os_read_pci_configuration(pci_id,
PCI_CFG_SECONDARY_BUS_NUMBER_REG,
&pci_value, 8);
if (ACPI_FAILURE(status)) {
return (status);
}
*bus_number = (u16)pci_value;
return (AE_OK);
}
| {
"pile_set_name": "Github"
} |
#ifndef BOOST_METAPARSE_V1_FOLDR_HPP
#define BOOST_METAPARSE_V1_FOLDR_HPP
// Copyright Abel Sinkovics ([email protected]) 2011 - 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/metaparse/v1/return_.hpp>
#include <boost/metaparse/v1/foldr_start_with_parser.hpp>
namespace boost
{
namespace metaparse
{
namespace v1
{
template <class P, class State, class BackwardOp>
struct foldr : foldr_start_with_parser<P, return_<State>, BackwardOp> {};
}
}
}
#endif
| {
"pile_set_name": "Github"
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['feed.xml'] = 'gitblog/feed';
$route['page/(:num).html'] = 'gitblog/page/$1';
$route['category/(:any)/page/(:num).html'] = 'gitblog/category/$1/$2';
$route['category/(:any).html'] = 'gitblog/category/$1';
$route['tags/(:any)/page/(:num).html'] = 'gitblog/tags/$1/$2';
$route['tags/(:any).html'] = 'gitblog/tags/$1';
$route['archive/(:any)/page/(:num).html'] = 'gitblog/archive/$1/$2';
$route['archive/(:num).html'] = 'gitblog/archive/$1';
$route['blog/(.+).html'] = 'gitblog/blog';
$route['search'] = 'gitblog/search';
$route['export'] = 'gitblog/exportSite';
$route['wp2gb'] = 'Wp2Gb';
$route['default_controller'] = 'gitblog';
$route['404_override'] = 'gitblog/go404';
$route['translate_uri_dashes'] = FALSE;
| {
"pile_set_name": "Github"
} |
import { utilGetAllNodes } from '../util';
export function actionScale(ids, pivotLoc, scaleFactor, projection) {
return function(graph) {
return graph.update(function(graph) {
let point, radial;
utilGetAllNodes(ids, graph).forEach(function(node) {
point = projection(node.loc);
radial = [
point[0] - pivotLoc[0],
point[1] - pivotLoc[1]
];
point = [
pivotLoc[0] + (scaleFactor * radial[0]),
pivotLoc[1] + (scaleFactor * radial[1])
];
graph = graph.replace(node.move(projection.invert(point)));
});
});
};
}
| {
"pile_set_name": "Github"
} |
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2015 Stephen Warren
# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
# Test operation of shell commands relating to environment variables.
import pytest
import u_boot_utils
# FIXME: This might be useful for other tests;
# perhaps refactor it into ConsoleBase or some other state object?
class StateTestEnv(object):
"""Container that represents the state of all U-Boot environment variables.
This enables quick determination of existant/non-existant variable
names.
"""
def __init__(self, u_boot_console):
"""Initialize a new StateTestEnv object.
Args:
u_boot_console: A U-Boot console.
Returns:
Nothing.
"""
self.u_boot_console = u_boot_console
self.get_env()
self.set_var = self.get_non_existent_var()
def get_env(self):
"""Read all current environment variables from U-Boot.
Args:
None.
Returns:
Nothing.
"""
if self.u_boot_console.config.buildconfig.get(
'config_version_variable', 'n') == 'y':
with self.u_boot_console.disable_check('main_signon'):
response = self.u_boot_console.run_command('printenv')
else:
response = self.u_boot_console.run_command('printenv')
self.env = {}
for l in response.splitlines():
if not '=' in l:
continue
(var, value) = l.split('=', 1)
self.env[var] = value
def get_existent_var(self):
"""Return the name of an environment variable that exists.
Args:
None.
Returns:
The name of an environment variable.
"""
for var in self.env:
return var
def get_non_existent_var(self):
"""Return the name of an environment variable that does not exist.
Args:
None.
Returns:
The name of an environment variable.
"""
n = 0
while True:
var = 'test_env_' + str(n)
if var not in self.env:
return var
n += 1
ste = None
@pytest.fixture(scope='function')
def state_test_env(u_boot_console):
"""pytest fixture to provide a StateTestEnv object to tests."""
global ste
if not ste:
ste = StateTestEnv(u_boot_console)
return ste
def unset_var(state_test_env, var):
"""Unset an environment variable.
This both executes a U-Boot shell command and updates a StateTestEnv
object.
Args:
state_test_env: The StateTestEnv object to update.
var: The variable name to unset.
Returns:
Nothing.
"""
state_test_env.u_boot_console.run_command('setenv %s' % var)
if var in state_test_env.env:
del state_test_env.env[var]
def set_var(state_test_env, var, value):
"""Set an environment variable.
This both executes a U-Boot shell command and updates a StateTestEnv
object.
Args:
state_test_env: The StateTestEnv object to update.
var: The variable name to set.
value: The value to set the variable to.
Returns:
Nothing.
"""
bc = state_test_env.u_boot_console.config.buildconfig
if bc.get('config_hush_parser', None):
quote = '"'
else:
quote = ''
if ' ' in value:
pytest.skip('Space in variable value on non-Hush shell')
state_test_env.u_boot_console.run_command(
'setenv %s %s%s%s' % (var, quote, value, quote))
state_test_env.env[var] = value
def validate_empty(state_test_env, var):
"""Validate that a variable is not set, using U-Boot shell commands.
Args:
var: The variable name to test.
Returns:
Nothing.
"""
response = state_test_env.u_boot_console.run_command('echo $%s' % var)
assert response == ''
def validate_set(state_test_env, var, value):
"""Validate that a variable is set, using U-Boot shell commands.
Args:
var: The variable name to test.
value: The value the variable is expected to have.
Returns:
Nothing.
"""
# echo does not preserve leading, internal, or trailing whitespace in the
# value. printenv does, and hence allows more complete testing.
response = state_test_env.u_boot_console.run_command('printenv %s' % var)
assert response == ('%s=%s' % (var, value))
def test_env_echo_exists(state_test_env):
"""Test echoing a variable that exists."""
var = state_test_env.get_existent_var()
value = state_test_env.env[var]
validate_set(state_test_env, var, value)
@pytest.mark.buildconfigspec('cmd_echo')
def test_env_echo_non_existent(state_test_env):
"""Test echoing a variable that doesn't exist."""
var = state_test_env.set_var
validate_empty(state_test_env, var)
def test_env_printenv_non_existent(state_test_env):
"""Test printenv error message for non-existant variables."""
var = state_test_env.set_var
c = state_test_env.u_boot_console
with c.disable_check('error_notification'):
response = c.run_command('printenv %s' % var)
assert(response == '## Error: "%s" not defined' % var)
@pytest.mark.buildconfigspec('cmd_echo')
def test_env_unset_non_existent(state_test_env):
"""Test unsetting a nonexistent variable."""
var = state_test_env.get_non_existent_var()
unset_var(state_test_env, var)
validate_empty(state_test_env, var)
def test_env_set_non_existent(state_test_env):
"""Test set a non-existant variable."""
var = state_test_env.set_var
value = 'foo'
set_var(state_test_env, var, value)
validate_set(state_test_env, var, value)
def test_env_set_existing(state_test_env):
"""Test setting an existant variable."""
var = state_test_env.set_var
value = 'bar'
set_var(state_test_env, var, value)
validate_set(state_test_env, var, value)
@pytest.mark.buildconfigspec('cmd_echo')
def test_env_unset_existing(state_test_env):
"""Test unsetting a variable."""
var = state_test_env.set_var
unset_var(state_test_env, var)
validate_empty(state_test_env, var)
def test_env_expansion_spaces(state_test_env):
"""Test expanding a variable that contains a space in its value."""
var_space = None
var_test = None
try:
var_space = state_test_env.get_non_existent_var()
set_var(state_test_env, var_space, ' ')
var_test = state_test_env.get_non_existent_var()
value = ' 1${%(var_space)s}${%(var_space)s} 2 ' % locals()
set_var(state_test_env, var_test, value)
value = ' 1 2 '
validate_set(state_test_env, var_test, value)
finally:
if var_space:
unset_var(state_test_env, var_space)
if var_test:
unset_var(state_test_env, var_test)
@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_checksum_no_size(state_test_env):
"""Test that omitted ('-') size parameter with checksum validation fails the
env import function.
"""
c = state_test_env.u_boot_console
ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
addr = '%08x' % ram_base
with c.disable_check('error_notification'):
response = c.run_command('env import -c %s -' % addr)
assert(response == '## Error: external checksum format must pass size')
@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_whitelist_checksum_no_size(state_test_env):
"""Test that omitted ('-') size parameter with checksum validation fails the
env import function when variables are passed as parameters.
"""
c = state_test_env.u_boot_console
ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
addr = '%08x' % ram_base
with c.disable_check('error_notification'):
response = c.run_command('env import -c %s - foo1 foo2 foo4' % addr)
assert(response == '## Error: external checksum format must pass size')
@pytest.mark.buildconfigspec('cmd_exportenv')
@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_whitelist(state_test_env):
"""Test importing only a handful of env variables from an environment."""
c = state_test_env.u_boot_console
ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
addr = '%08x' % ram_base
set_var(state_test_env, 'foo1', 'bar1')
set_var(state_test_env, 'foo2', 'bar2')
set_var(state_test_env, 'foo3', 'bar3')
c.run_command('env export %s' % addr)
unset_var(state_test_env, 'foo1')
set_var(state_test_env, 'foo2', 'test2')
set_var(state_test_env, 'foo4', 'bar4')
# no foo1 in current env, foo2 overridden, foo3 should be of the value
# before exporting and foo4 should be of the value before importing.
c.run_command('env import %s - foo1 foo2 foo4' % addr)
validate_set(state_test_env, 'foo1', 'bar1')
validate_set(state_test_env, 'foo2', 'bar2')
validate_set(state_test_env, 'foo3', 'bar3')
validate_set(state_test_env, 'foo4', 'bar4')
# Cleanup test environment
unset_var(state_test_env, 'foo1')
unset_var(state_test_env, 'foo2')
unset_var(state_test_env, 'foo3')
unset_var(state_test_env, 'foo4')
@pytest.mark.buildconfigspec('cmd_exportenv')
@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_whitelist_delete(state_test_env):
"""Test importing only a handful of env variables from an environment, with.
deletion if a var A that is passed to env import is not in the
environment to be imported.
"""
c = state_test_env.u_boot_console
ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
addr = '%08x' % ram_base
set_var(state_test_env, 'foo1', 'bar1')
set_var(state_test_env, 'foo2', 'bar2')
set_var(state_test_env, 'foo3', 'bar3')
c.run_command('env export %s' % addr)
unset_var(state_test_env, 'foo1')
set_var(state_test_env, 'foo2', 'test2')
set_var(state_test_env, 'foo4', 'bar4')
# no foo1 in current env, foo2 overridden, foo3 should be of the value
# before exporting and foo4 should be empty.
c.run_command('env import -d %s - foo1 foo2 foo4' % addr)
validate_set(state_test_env, 'foo1', 'bar1')
validate_set(state_test_env, 'foo2', 'bar2')
validate_set(state_test_env, 'foo3', 'bar3')
validate_empty(state_test_env, 'foo4')
# Cleanup test environment
unset_var(state_test_env, 'foo1')
unset_var(state_test_env, 'foo2')
unset_var(state_test_env, 'foo3')
unset_var(state_test_env, 'foo4')
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2012, 2017 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package jakarta.ws.rs.client;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import jakarta.ws.rs.core.Configuration;
import jakarta.ws.rs.core.Cookie;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.MessageBodyWriter;
/**
* Client request filter context.
*
* A mutable class that provides request-specific information for the filter, such as request URI, message headers,
* message entity or request-scoped properties. The exposed setters allow modification of the exposed request-specific
* information.
*
* @author Marek Potociar
* @since 2.0
*/
public interface ClientRequestContext {
/**
* Returns the property with the given name registered in the current request/response exchange context, or {@code null}
* if there is no property by that name.
* <p>
* A property allows a JAX-RS filters and interceptors to exchange additional custom information not already provided by
* this interface.
* </p>
* <p>
* A list of supported properties can be retrieved using {@link #getPropertyNames()}. Custom property names should
* follow the same convention as package names.
* </p>
*
* @param name a {@code String} specifying the name of the property.
* @return an {@code Object} containing the value of the property, or {@code null} if no property exists matching the
* given name.
* @see #getPropertyNames()
*/
public Object getProperty(String name);
/**
* Returns an immutable {@link Collection collection} containing the property names available within the context of the
* current request/response exchange context.
* <p>
* Use the {@link #getProperty} method with a property name to get the value of a property.
* </p>
*
* @return an immutable {@link Collection collection} of property names.
* @see #getProperty
*/
public Collection<String> getPropertyNames();
/**
* Binds an object to a given property name in the current request/response exchange context. If the name specified is
* already used for a property, this method will replace the value of the property with the new value.
* <p>
* A property allows a JAX-RS filters and interceptors to exchange additional custom information not already provided by
* this interface.
* </p>
* <p>
* A list of supported properties can be retrieved using {@link #getPropertyNames()}. Custom property names should
* follow the same convention as package names.
* </p>
* <p>
* If a {@code null} value is passed, the effect is the same as calling the {@link #removeProperty(String)} method.
* </p>
*
* @param name a {@code String} specifying the name of the property.
* @param object an {@code Object} representing the property to be bound.
*/
public void setProperty(String name, Object object);
/**
* Removes a property with the given name from the current request/response exchange context. After removal, subsequent
* calls to {@link #getProperty} to retrieve the property value will return {@code null}.
*
* @param name a {@code String} specifying the name of the property to be removed.
*/
public void removeProperty(String name);
/**
* Get the request URI.
*
* @return request URI.
*/
public URI getUri();
/**
* Set a new request URI.
*
* @param uri new request URI.
*/
public void setUri(URI uri);
/**
* Get the request method.
*
* @return the request method.
* @see jakarta.ws.rs.HttpMethod
*/
public String getMethod();
/**
* Set the request method.
*
* @param method new request method.
* @see jakarta.ws.rs.HttpMethod
*/
public void setMethod(String method);
/**
* Get the mutable request headers multivalued map.
*
* @return mutable multivalued map of request headers.
* @see #getStringHeaders()
* @see #getHeaderString(String)
*/
public MultivaluedMap<String, Object> getHeaders();
/**
* Get a string view of header values associated with the message.
*
* Changes in the underlying {@link #getHeaders() headers map} are reflected in this view.
* <p>
* The method converts the non-string header values to strings using a
* {@link jakarta.ws.rs.ext.RuntimeDelegate.HeaderDelegate} if one is available via
* {@link jakarta.ws.rs.ext.RuntimeDelegate#createHeaderDelegate(java.lang.Class)} for the class of the value or using the
* values {@code toString} method if a header delegate is not available.
* </p>
*
* @return response headers as a string view of header values.
* @see #getHeaders()
* @see #getHeaderString(String)
*/
public abstract MultivaluedMap<String, String> getStringHeaders();
/**
* Get a message header as a single string value.
*
* Each single header value is converted to String using a {@link jakarta.ws.rs.ext.RuntimeDelegate.HeaderDelegate} if one
* is available via {@link jakarta.ws.rs.ext.RuntimeDelegate#createHeaderDelegate(java.lang.Class)} for the header value
* class or using its {@code toString} method if a header delegate is not available.
*
* @param name the message header.
* @return the message header value. If the message header is not present then {@code null} is returned. If the message
* header is present but has no value then the empty string is returned. If the message header is present more than once
* then the values of joined together and separated by a ',' character.
* @see #getHeaders()
* @see #getStringHeaders()
*/
public String getHeaderString(String name);
/**
* Get message date.
*
* @return the message date, otherwise {@code null} if not present.
*/
public Date getDate();
/**
* Get the language of the entity.
*
* @return the language of the entity or {@code null} if not specified
*/
public Locale getLanguage();
/**
* Get the media type of the entity.
*
* @return the media type or {@code null} if not specified (e.g. there's no request entity).
*/
public MediaType getMediaType();
/**
* Get a list of media types that are acceptable for the response.
*
* @return a read-only list of requested response media types sorted according to their q-value, with highest preference
* first.
*/
public List<MediaType> getAcceptableMediaTypes();
/**
* Get a list of languages that are acceptable for the response.
*
* @return a read-only list of acceptable languages sorted according to their q-value, with highest preference first.
*/
public List<Locale> getAcceptableLanguages();
/**
* Get any cookies that accompanied the request.
*
* @return a read-only map of cookie name (String) to {@link Cookie}.
*/
public Map<String, Cookie> getCookies();
/**
* Check if there is an entity available in the request.
*
* The method returns {@code true} if the entity is present, returns {@code false} otherwise.
*
* @return {@code true} if there is an entity present in the message, {@code false} otherwise.
*/
public boolean hasEntity();
/**
* Get the message entity Java instance.
*
* Returns {@code null} if the message does not contain an entity.
*
* @return the message entity or {@code null} if message does not contain an entity body.
*/
public Object getEntity();
/**
* Get the raw entity type information.
*
* @return raw entity type.
*/
public Class<?> getEntityClass();
/**
* Get the generic entity type information.
*
* @return generic entity type.
*/
public Type getEntityType();
/**
* Set a new message entity. The existing entity {@link #getEntityAnnotations() annotations} and {@link #getMediaType()
* media type} are preserved.
* <p>
* It is the callers responsibility to wrap the actual entity with {@link jakarta.ws.rs.core.GenericEntity} if
* preservation of its generic type is required.
* </p>
*
* @param entity entity object.
* @see #setEntity(Object, java.lang.annotation.Annotation[], jakarta.ws.rs.core.MediaType)
* @see MessageBodyWriter
*/
public void setEntity(final Object entity);
/**
* Set a new message entity, including the attached annotations and the media type.
* <p>
* It is the callers responsibility to wrap the actual entity with {@link jakarta.ws.rs.core.GenericEntity} if
* preservation of its generic type is required.
* </p>
*
* @param entity entity object.
* @param annotations annotations attached to the entity instance.
* @param mediaType entity media type.
* @see #setEntity(Object)
* @see MessageBodyWriter
*/
public void setEntity(
final Object entity,
final Annotation[] annotations,
final MediaType mediaType);
/**
* Get the annotations attached to the entity instance.
* <p>
* Note that the returned annotations array contains only those annotations explicitly attached to entity instance (such
* as the ones attached using
* {@link Entity#Entity(Object, jakarta.ws.rs.core.MediaType, java.lang.annotation.Annotation[])} method). The entity
* instance annotations array does not include annotations declared on the entity implementation class or its ancestors.
* </p>
*
* @return annotations attached to the entity instance.
*/
public Annotation[] getEntityAnnotations();
/**
* Get the entity output stream. The JAX-RS runtime is responsible for closing the output stream.
*
* @return entity output stream.
*/
public OutputStream getEntityStream();
/**
* Set a new entity output stream. The JAX-RS runtime is responsible for closing the output stream.
*
* @param outputStream new entity output stream.
*/
public void setEntityStream(OutputStream outputStream);
/**
* Get the client instance associated with the request.
*
* @return client instance associated with the request.
*/
public Client getClient();
/**
* Get the immutable configuration of the request.
*
* @return immutable request configuration.
*/
public Configuration getConfiguration();
/**
* Abort the filter chain with a response.
*
* This method breaks the filter chain processing and returns the provided response back to the client. The provided
* response goes through the chain of applicable response filters.
*
* @param response response to be sent back to the client.
*/
public void abortWith(Response response);
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* 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.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
/**
* Zend_Db_Adapter_Db2_Exception
*
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Db2_Exception extends Zend_Db_Adapter_Exception
{
protected $code = '00000';
protected $message = 'unknown exception';
function __construct($message = 'unknown exception', $code = '00000', Exception $e = null)
{
parent::__construct($message, $code, $e);
}
}
| {
"pile_set_name": "Github"
} |
# How to contribute
We are glad you are reading this, because we need volunteer developers
to help this project come to fruition.
If you don't have anything you are working on we have a
[**list of newbie friendly issues**](https://github.com/Harvey-OS/harvey/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22+label%3A%22good+first+issue%22)
you can help out with.
If you haven't already, come find us on our
[mailing list](https://groups.google.com/forum/#!forum/harvey). We
want you working on things you're excited about.
Harvey, like most other open source projects, has a
[Code of Conduct](https://github.com/Harvey-OS/harvey/wiki/Code-of-Conduct)
that it expects its contributors and core team members to adhere to.
Here are some important resources:
* Our [mailing list](https://groups.google.com/forum/#!forum/harvey)
is where the development discussion happens.
* [Man Pages](https://sevki.io/harvey/sys/man/1/0intro) are where
you can documentation from head of the repository.
* The [Issue Tracker](https://github.com/Harvey-OS/harvey/issues) is
our day-to-day project management space.
## Testing
We make use Travis-CI and make sure we can build your pull-requests
before we can accept your contributions.
## Submitting a patch
Harvey uses Github Pull Requests to accept contributions.
1. Clone the repository:
`git clone https://github.com/Harvey-OS/harvey.git`.
It is also possible to use `git` instead of `https` if you have an
SSH public key stored on Github:
`git clone [email protected]:Harvey-OS/harvey.git`.
This makes submitting contributions easier. For the rest of this
manual we assume to use https.
2. Check out a feature branch for your work on by executing:
`git checkout -b feature-name`.
For example, @keedon selected the branch name `statscrash` for
issue #70.
3. Make changes
4. Commit with a descriptive message and [signed-off-by:](https://github.com/docker/Harvey-OS/harvey/main/CONTRIBUTING.md#sign-your-work):
```
$ git commit -m -s "A brief summary of the commit
>
> A paragraph describing what changed and its impact."
```
For a representative example, look at @keedon's
[commit message](https://github.com/keedon/harvey/commit/09fe3a21fa8b42088bc8ad83287928e9e7cc96ef)
for issue #70 mentioned above. You can also use graphical git
tools such as `git gui` if you like.
5. Fork the repo (only once).

6. Add the repo as a remote (every time you clone the repository)
`git remote add yourname https://github.com/yourusername/harvey.git`
where "yourname" is your github login name.
`git remote -v` should look like this:
```
$ git remote -v
yourname https://github.com/yourname/harvey.git (fetch)
yourname https://github.com/yourname/harvey.git (push)
origin https://github.com/Harvey-OS/harvey.git (fetch)
origin https://github.com/Harvey-OS/harvey.git (push)
```
7. Push your branch to your forked repository:
`git push yourname feature-name`
8. Create a pull request by going to
`https://github.com/yourname/harvey/pull/new/feature-name`
or clicking the PR button

9. Add details of what you have worked on and your motivation.

When you send a pull request, we greatly appreciate if you include
`emu` output and additional tests: we can always use more test
coverage. Please follow our coding conventions and make sure all
of your commits are atomic in the sense of having one feature per
commit.
### Iterating on your work
- A Github pull request or a Gerrit CL roughly serve the same purpose:
they are feedback loops for people to give feedback and for you to
iterate on your work in response to that feedback, so be ready to
repeat steps!
- When iterating on your work continue committing to the same branch
and push the changes up to your fork. Github will track the changes
and update the pull request accordingly.
- Most of the time, when you are ready to submit your pull request,
someone else will have merged something to main, at which point
your branch will have been outdated, GitHub provides a convenient
way of updating your branch right from your pull request.

- When you click that button, GitHub will update your branch, at which
point you will have to `git pull yourname feature-name` and update
your local repo before committing more changes.
- If your changes conflict with something that was merged into the
branch, you will have to resolve the changes manually before
submitting the changes.
### Keeping up to date with the main branch
If you're working in a branch that is outdated with respect to the
master branch, just do a `git pull --rebase`. This will put your
changes after the pull. In the case that there would be conflicts, you
will have to solve them manually, but they are marked with something
like "`>>>>>HEAD`" and git will tell you about which files are in
conflict.
#### More information
- [How to use Pull Requests](http://help.github.com/pull-requests/)
- [GitHub Flow](https://guides.github.com/introduction/flow/)
- [Hub: A command line application for GH Flow](https://hub.github.com)
- [Video: Pull Requests](https://www.youtube.com/watch?v=81uKcXZoQ2A)
- [Video: Workflows](https://www.youtube.com/watch?v=EwWZbyjDs9c)
- [Github Desktop Client](https://desktop.github.com/)
- [Video: Undo, Redo & Rebase Your Git History](https://www.youtube.com/watch?v=W39CfI3-JFc)
- [Video: Git Rebase](https://www.youtube.com/watch?v=SxzjZtJwOgo)
### Sign your work
The sign-off is a simple line at the end of the explanation for the patch. Your
signature certifies that you wrote the patch or otherwise have the right to pass
it on as an open-source patch. The rules are pretty simple: if you can certify
the below (from [developercertificate.org](http://developercertificate.org/)):
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
Then you just add a line to every git commit message:
Signed-off-by: Joe Smith <[email protected]>
Use your real name (sorry, no pseudonyms or anonymous contributions.)
If you set your `user.name` and `user.email` git configs, you can sign your
commit automatically with `git commit -s`.
## Coding conventions
If you read the code you should get a hang of it but a loose listing
of our
[Style-Guide](https://github.com/Harvey-OS/harvey/wiki/Style-Guide)
exists, we recommend you check it out.
We have also automated the process via
[clang-format](http://clang.llvm.org/docs/ClangFormat.html)
so before you submit a change please format your diff.
[How to clang-format a diff](http://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting)
_Adopted from [Open Government Contribution Guidelines](https://github.com/opengovernment/opengovernment/blob/master/CONTRIBUTING.md)_
| {
"pile_set_name": "Github"
} |
/*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2009-2012
* All rights reserved
*
* This file is part of GPAC / Platinum UPnP module
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC 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 library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* ----------------------------------------------------------------------------------
* PLATINUM IS LICENSED UNDER GPL or commercial agreement - cf platinum license
* ----------------------------------------------------------------------------------
*
*/
#include "GPACPlatinum.h"
GPAC_MediaController::GPAC_MediaController(PLT_CtrlPointReference& ctrlPoint, GF_UPnP *upnp)
{
m_MediaController = new PLT_MediaController(ctrlPoint, this);
m_MediaBrowser = new PLT_MediaBrowser(ctrlPoint, this);
m_MediaServers = gf_list_new();
m_MediaRenderers = gf_list_new();
m_ControlPointLock = gf_mx_new("AVControlPoint");
m_pUPnP = upnp;
}
GPAC_MediaController::~GPAC_MediaController()
{
delete m_MediaController;
m_MediaController=NULL;
delete m_MediaBrowser;
m_MediaBrowser=NULL;
while (gf_list_count(m_MediaServers)) {
GPAC_MediaServerItem*ms = (GPAC_MediaServerItem*)gf_list_get(m_MediaServers, 0);
gf_list_rem(m_MediaServers, 0);
delete ms;
}
gf_list_del(m_MediaServers);
while (gf_list_count(m_MediaRenderers)) {
GPAC_MediaRendererItem *ms = (GPAC_MediaRendererItem *)gf_list_get(m_MediaRenderers, 0);
gf_list_rem(m_MediaRenderers, 0);
delete ms;
}
gf_list_del(m_MediaRenderers);
gf_mx_del(m_ControlPointLock);
}
bool
GPAC_MediaController::OnMRAdded(PLT_DeviceDataReference& device)
{
NPT_String uuid = device->GetUUID();
gf_mx_p(m_ControlPointLock);
// test if it's a media renderer
PLT_Service* service;
if (NPT_SUCCEEDED(device->FindServiceByType("urn:schemas-upnp-org:service:AVTransport:1", service))) {
gf_list_add(m_MediaRenderers, new GPAC_MediaRendererItem(device, uuid) );
}
m_pUPnP->OnMediaRendererAdd(device, 1);
gf_mx_v(m_ControlPointLock);
return true;
}
void
GPAC_MediaController::OnMRRemoved(PLT_DeviceDataReference& device)
{
NPT_String uuid = device->GetUUID();
gf_mx_p(m_ControlPointLock);
u32 i, count;
count = gf_list_count(m_MediaRenderers);
for (i=0; i<count; i++) {
GPAC_MediaRendererItem *ms = (GPAC_MediaRendererItem *) gf_list_get(m_MediaRenderers, i);
if (ms->m_UUID==uuid) {
delete ms;
gf_list_rem(m_MediaRenderers, i);
break;
}
}
m_pUPnP->OnMediaRendererAdd(device, 0);
gf_mx_v(m_ControlPointLock);
}
bool
GPAC_MediaController::OnMSAdded(PLT_DeviceDataReference& device)
{
NPT_String uuid = device->GetUUID();
gf_mx_p(m_ControlPointLock);
// test if it's a media server
PLT_Service* service;
if (NPT_SUCCEEDED(device->FindServiceByType("urn:schemas-upnp-org:service:ContentDirectory:1", service))) {
gf_list_add(m_MediaServers, new GPAC_MediaServerItem(device, uuid) );
}
m_pUPnP->OnMediaServerAdd(device, 1);
gf_mx_v(m_ControlPointLock);
return true;
}
void
GPAC_MediaController::OnMSRemoved(PLT_DeviceDataReference& device)
{
NPT_String uuid = device->GetUUID();
gf_mx_p(m_ControlPointLock);
u32 i, count;
count = gf_list_count(m_MediaServers);
for (i=0; i<count; i++) {
GPAC_MediaServerItem *ms = (GPAC_MediaServerItem *) gf_list_get(m_MediaServers, i);
if (ms->m_UUID==uuid) {
delete ms;
gf_list_rem(m_MediaServers, i);
break;
}
}
m_pUPnP->OnMediaServerAdd(device, 0);
gf_mx_v(m_ControlPointLock);
}
NPT_Result
GPAC_MediaController::OnActionResponse(NPT_Result res,
PLT_ActionReference& action,
void* userdata)
{
return NPT_SUCCESS;
}
NPT_Result GPAC_MediaController::OnEventNotify(PLT_Service* service, NPT_List<PLT_StateVariable*>* vars)
{
return NPT_SUCCESS;
}
void GPAC_MediaController::OnMRStateVariablesChanged(PLT_Service* service, NPT_List<PLT_StateVariable*>* vars )
{
u32 count;
u32 i;
s32 render_idx = -1;
count = gf_list_count(m_MediaRenderers);
for (i=0; i<count; i++) {
GPAC_MediaRendererItem *mr = (GPAC_MediaRendererItem *) gf_list_get(m_MediaRenderers, i);
if ( mr->m_device.AsPointer() == service->GetDevice() ) {
render_idx = i;
break;
}
}
if (render_idx < 0) return;
count = vars->GetItemCount();
for (i=0; i<count; i++) {
PLT_StateVariable *svar;
vars->Get(i, svar);
if (svar->GetName() == NPT_String("AbsoluteTimePosition")) {
u32 h, m, s;
if (sscanf((char *) svar->GetValue(), "%d:%d:%d", &h, &m, &s)==3) {
Double time = h*3600 + m*60 + s;
this->m_pUPnP->onTimeChanged(render_idx, time);
}
}
else if (svar->GetName() == NPT_String("CurrentTrackDuration")) {
u32 h, m, s;
if (sscanf((char *) svar->GetValue(), "%d:%d:%d", &h, &m, &s)==3) {
Double time = h*3600 + m*60 + s;
this->m_pUPnP->onDurationChanged(render_idx, time);
}
}
}
}
void GPAC_MediaController::OnBrowseResult(NPT_Result res, PLT_DeviceDataReference& device, PLT_BrowseInfo* info, void* userdata)
{
NPT_COMPILER_UNUSED(device);
NPT_COMPILER_UNUSED(device);
if (!userdata) return;
GPAC_BrowseDataReference* data = (GPAC_BrowseDataReference*) userdata;
(*data)->res = res;
if (NPT_SUCCEEDED(res) && info) {
(*data)->info = *info;
}
(*data)->shared_var.SetValue(1);
delete data;
}
void
GPAC_MediaController::OnMSStateVariablesChanged(PLT_Service* service, NPT_List<PLT_StateVariable*>* vars)
{
GPAC_MediaServerItem *ms = NULL;
gf_mx_p(m_ControlPointLock);
u32 i, count;
count = gf_list_count(m_MediaServers);
for (i=0; i<count; i++) {
GPAC_MediaServerItem *ms = (GPAC_MediaServerItem *) gf_list_get(m_MediaServers, i);
if (ms->m_UUID==service->GetDevice()->GetUUID()) {
break;
}
ms = NULL;
}
if (!ms) {
gf_mx_v(m_ControlPointLock);
return;
}
PLT_StateVariable* var = PLT_StateVariable::Find(*vars, "ContainerUpdateIDs");
if (var) {
// variable found, parse value
NPT_String value = var->GetValue();
NPT_String item_id, update_id;
int index;
while (value.GetLength()) {
// look for container id
index = value.Find(',');
if (index < 0) break;
item_id = value.Left(index);
value = value.SubString(index+1);
// look for update id
if (value.GetLength()) {
index = value.Find(',');
update_id = (index<0)?value:value.Left(index);
value = (index<0)?"":value.SubString(index+1);
m_pUPnP->ContainerChanged(ms->m_device, item_id, update_id);
}
}
}
gf_mx_v(m_ControlPointLock);
}
NPT_Result
GPAC_MediaController::WaitForResponse(NPT_SharedVariable& shared_var)
{
return shared_var.WaitUntilEquals(1, 30000);
}
NPT_Result
GPAC_MediaController::Browse(GPAC_BrowseDataReference& browse_data,
PLT_DeviceDataReference& device,
const char* object_id,
NPT_Int32 index,
NPT_Int32 count,
bool browse_metadata,
const char* filter,
const char* sort)
{
NPT_Result res;
browse_data->shared_var.SetValue(0);
// send off the browse packet. Note that this will
// not block. There is a call to WaitForResponse in order
// to block until the response comes back.
res = m_MediaBrowser->Browse(device,
(const char*)object_id,
index,
count,
browse_metadata,
filter,
sort,
new GPAC_BrowseDataReference(browse_data));
NPT_CHECK_SEVERE(res);
return WaitForResponse(browse_data->shared_var);
}
NPT_Result
GPAC_MediaController::Browse(GPAC_MediaServerItem *server, const char *object_id, const char *filter)
{
NPT_Result res = NPT_FAILURE;
NPT_Int32 index = 0;
// reset output params
server->m_BrowseResults = NULL;
do {
GPAC_BrowseDataReference browse_data(new GPAC_BrowseData());
// send off the browse packet. Note that this will
// not block. There is a call to WaitForResponse in order
// to block until the response comes back.
res = Browse(browse_data,
server->m_device,
(const char*)object_id,
index,
1024,
false,
filter,
"");
NPT_CHECK_LABEL_WARNING(res, done);
if (NPT_FAILED(browse_data->res)) {
res = browse_data->res;
NPT_CHECK_LABEL_WARNING(res, done);
}
if (browse_data->info.items->GetItemCount() == 0)
break;
if (server->m_BrowseResults.IsNull()) {
server->m_BrowseResults = browse_data->info.items;
} else {
server->m_BrowseResults->Add(*browse_data->info.items);
// clear the list items so that the data inside is not
// cleaned up by PLT_MediaItemList dtor since we copied
// each pointer into the new list.
browse_data->info.items->Clear();
}
// stop now if our list contains exactly what the server said it had
if (browse_data->info.tm && browse_data->info.tm == server->m_BrowseResults->GetItemCount())
break;
// ask for the next chunk of entries
index = server->m_BrowseResults->GetItemCount();
} while(1);
done:
return res;
}
| {
"pile_set_name": "Github"
} |
/* TODO change to
#include <../src/mat/impls/dense/seq/dense.h>
*/
#include <../src/mat/impls/dense/mpi/mpidense.h>
#include <petsc/private/isimpl.h>
#include <petsc/private/vecimpl.h>
#include <petsclayouthdf5.h>
#if defined(PETSC_HAVE_HDF5)
PetscErrorCode MatLoad_Dense_HDF5(Mat mat, PetscViewer viewer)
{
hid_t scalartype; /* scalar type (H5T_NATIVE_FLOAT or H5T_NATIVE_DOUBLE) */
PetscLayout vmap;
PetscViewerFormat format;
PetscScalar *a = NULL;
const char *mat_name = NULL;
MPI_Comm comm;
PetscMPIInt rank, size;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscViewerGetFormat(viewer, &format);CHKERRQ(ierr);
switch (format) {
case PETSC_VIEWER_HDF5_PETSC:
case PETSC_VIEWER_DEFAULT:
case PETSC_VIEWER_NATIVE:
case PETSC_VIEWER_HDF5_MAT:
break;
default:
SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"PetscViewerFormat %s not supported for HDF5 input.",PetscViewerFormats[format]);
}
if (!((PetscObject)mat)->name) SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat name must be set with PetscObjectSetName() before MatLoad()");
#if defined(PETSC_USE_REAL_SINGLE)
scalartype = H5T_NATIVE_FLOAT;
#elif defined(PETSC_USE_REAL___FLOAT128)
#error "HDF5 output with 128 bit floats not supported."
#elif defined(PETSC_USE_REAL___FP16)
#error "HDF5 output with 16 bit floats not supported."
#else
scalartype = H5T_NATIVE_DOUBLE;
#endif
ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)mat,&mat_name);CHKERRQ(ierr);
/* Convert user-defined rmap and cmap to the dataset layout */
ierr = PetscLayoutCreate(PetscObjectComm((PetscObject)mat),&vmap);CHKERRQ(ierr);
if (mat->rmap->n >= 0 && mat->cmap->N < 0) {
/* We need to know mat->cmap->N if user specifies custom mat->rmap->n, otherwise the latter would get ignored below */
ierr = PetscViewerHDF5ReadSizes(viewer, mat_name, &mat->cmap->N, NULL);CHKERRQ(ierr);
}
vmap->bs = mat->cmap->N;
vmap->n = (mat->rmap->n < 0 || mat->cmap->N < 0) ? -1 : mat->rmap->n * mat->cmap->N;
vmap->N = (mat->rmap->N < 0 || mat->cmap->N < 0) ? -1 : mat->rmap->N * mat->cmap->N;
/* Read the dataset and setup its layout */
/* Note: PetscViewerHDF5ReadSizes_Private takes into account that the dataset is transposed for MATLAB MAT files */
ierr = PetscViewerHDF5Load(viewer, mat_name, vmap, scalartype, (void**)&a);CHKERRQ(ierr);
/* Convert the dataset layout back to rmap and cmap */
mat->cmap->N = vmap->bs;
mat->rmap->n = vmap->n / mat->cmap->N;
mat->rmap->N = vmap->N / mat->cmap->N;
ierr = PetscLayoutSetUp(mat->rmap);CHKERRQ(ierr);
ierr = PetscLayoutSetUp(mat->cmap);CHKERRQ(ierr);
ierr = PetscLayoutDestroy(&vmap);CHKERRQ(ierr);
/* TODO adding PetscCopyMode flag to MatSeqDenseSetPreallocation would make this code cleaner and simpler */
{
PetscBool flg;
Mat_SeqDense *impl;
ierr = PetscObjectTypeCompare((PetscObject)mat,MATSEQDENSE,&flg);CHKERRQ(ierr);
if (flg) {
impl = (Mat_SeqDense*)mat->data;
ierr = MatSeqDenseSetPreallocation(mat,a);CHKERRQ(ierr);
} else {
Mat_MPIDense *implm = (Mat_MPIDense*)mat->data;
ierr = MatMPIDenseSetPreallocation(mat,a);CHKERRQ(ierr);
impl = (Mat_SeqDense*)implm->A->data;
}
impl->user_alloc = PETSC_FALSE;
}
ierr = MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#endif
| {
"pile_set_name": "Github"
} |
Require Export Coq.Program.Basics.
Require Export Coq.Relations.Relation_Definitions.
Require Export Coq.Classes.Morphisms.
Require Setoid.
Require Export Delay.
(** * Prerequisites *)
(** Some instances that would normally cause loops can be used
nontheless if we insist that some parameters cannot be existential
variables. One way to do this is to use this guard class, similar in
spirit to [Unconvertible]. *)
Class NotEvar {A} (x: A).
Hint Extern 1 (NotEvar ?x) =>
not_evar x; constructor : typeclass_instances.
(** This version of [Unconvertible] does not assume that [a] and [b]
have convertible types. *)
Class Unconvertible {A B} (a: A) (b: B) := unconvertible : unit.
Ltac unconvertible a b :=
first
[ unify a b with typeclass_instances; fail 1
| exact tt ].
Hint Extern 1 (Unconvertible ?a ?b) =>
unconvertible a b : typeclass_instances.
(** Sometimes we may want to introduce an auxiliary variable to help
with unification. *)
Class Convertible {A} (x y: A) :=
convertible: x = y.
Hint Extern 1 (Convertible ?x ?y) =>
eapply eq_refl : typeclass_instances.
(** The following class can be used to inhibit backtracking. *)
Class Once P := once : P.
Hint Extern 1 (Once ?P) =>
red; once typeclasses eauto : typeclass_instances.
(** * Relations *)
(** The constructions in [Coq.Relations.Relation_Definitions] are only
concerned with relations within a single type, so that [relation A]
is defined as [A -> A -> Prop]. We will need more general
relations, and so I define [rel A B] as [A -> B -> Prop]. *)
Definition rel (A1 A2: Type) := A1 -> A2 -> Prop.
Delimit Scope rel_scope with rel.
Bind Scope rel_scope with rel.
(** Make sure that the existing definitions based on
[Relation_Definitions.relation] use our [rel_scope] as well. *)
Bind Scope rel_scope with Relation_Definitions.relation.
(** ** Proof step *)
(** This is a catch-all class for any applicable strategy allowing us
to make progress towards solving a relational goal. The proposition
[P] should encode the new subgoals, in the format expected by
[Delay.split_conjunction], and is decomposed accordingly in the
[rstep] tactic.
At the moment, the following priorities are used for our different
[RStep] instances. Generally speaking, the most specific, quick
tactics should be registered with higher priority (lower numbers),
and the more general, slow tactics that are likely to instantiate
evars incorrectly or spawn them too early should have lower priority
(higher numbers):
- 10 [RIntro]
- 30 [preorder]
- 40 [RDestruct]
- 50 [Monotonicity] (includes [Reflexivity] -- we may want to split)
- 70 [RExists] *)
Class RStep (P Q: Prop) :=
rstep: P -> Q.
Ltac rstep :=
lazymatch goal with
| |- ?Q =>
apply (rstep (Q := Q));
Delay.split_conjunction
end.
(** ** Proof automation *)
(** The following class solves the goal [Q] automatically. The
typeclass resolution process allows for backtracking, trying every
possible [RStep] at a given time. *)
Class RAuto (Q: Prop) :=
rauto : Q.
Ltac rauto :=
lazymatch goal with
| |- ?Q =>
apply (rauto (Q := Q));
Delay.split_conjunction
end.
(** After applying each step, we need to decompose the premise into
individual subgoals, wrapping each one into a new [RAuto] goal so
that the process continues.
Note the use of [Once] below: while choosing a step to apply next
can involve some backtracking, once a step has been chosen [RAuto]
never backtracks. This avoids exponential blow up in the search
space, so that [RAuto] remains efficient even in case of failure.
From a usability perspective, it also encourages proper hygiene when
declaring instances, since extraneous or too broadly applicable
instance will cause failures (rather than silently add weight to the
system). *)
Class RAutoSubgoals (P: Prop) :=
rauto_subgoals : P.
Global Instance rauto_rstep P Q:
Once (RStep P Q) ->
RAutoSubgoals P ->
RAuto Q.
Proof.
firstorder.
Qed.
Ltac rauto_split :=
red;
Delay.split_conjunction;
lazymatch goal with
| |- ?Q => change (RAuto Q)
end.
Hint Extern 1 (RAutoSubgoals _) =>
rauto_split : typeclass_instances.
(** If [rauto] is run under the [delayed] tactical and we don't know
how to make progress, bail out. Note that this will inhibit
backtracking. *)
Hint Extern 1000 (RAuto _) =>
red; solve [ delay ] : typeclass_instances.
(** ** Introduction rules *)
(** In effect, [RIntro] is pretty much identical to [RStep], but we
like to separate introduction rules and the [rintro] tactic. *)
Class RIntro {A B} (P: Prop) (R: rel A B) (m: A) (n: B): Prop :=
rintro: P -> R m n.
Arguments RIntro {A%type B%type} P%type R%rel m n.
Ltac rintro :=
lazymatch goal with
| |- ?R ?m ?n =>
apply (rintro (R:=R) (m:=m) (n:=n));
Delay.split_conjunction
end.
Global Instance rintro_rstep:
forall `(RIntro), RStep P (R m n) | 10.
Proof.
firstorder.
Qed.
(** Most introduction rules are entierly reversible. For instance,
suppose we use the introduction rule for [++>] on a goal of the form
[(R1 ++> R2) f g], to obtain [Hxy: R1 x y |- R2 (f x) (g y)]. If at
a later stage we manage to prove our old goal [Hfg: (R1 ++> R2) f g],
we can always use the elimination rule for [++>] in conjunction with
the two hypotheses to prove [R2 (f x) (g y)].
On the other hand, whenever a new existential variable is involved,
this reversibility is lost: the time of introduction of the evar
determines what a valid instantiation is, and there is no way to go
back if we want to use components introduced later, say by
destructing one of the hypotheses.
For this reason, we want such introduction rules to be used only as
a last resort, and segregate them as instances of the following
class rather than [RIntro]. Moreover, to make sure that we don't
leave the user in a dead-end, we only use it if we can immediately
solve the resulting subgoal. *)
Class RExists {A B} (P: Prop) (R: rel A B) (m: A) (n: B): Prop :=
rexists: P -> R m n.
Arguments RExists {A%type B%type} P%type R%rel m n.
Ltac reexists :=
lazymatch goal with
| |- ?R ?m ?n =>
apply (rexists (R:=R) (m:=m) (n:=n));
Delay.split_conjunction
end.
Global Instance rexists_rstep {A B} P R (m:A) (n:B):
RExists P R m n ->
NonDelayed (RAutoSubgoals P) ->
RStep True (R m n) | 70.
Proof.
firstorder.
Qed.
(** ** Using relations *)
(** As we extend our relations language with new relators, we need to
be able to extend the ways in which corresponding relational
properties can be applied to a given goal. The following type class
expresses that the relational property [R m n] can be applied to a
goal of type [Q], generating the subgoal [P]. *)
Class RElim {A B} (R: rel A B) (m: A) (n: B) (P Q: Prop): Prop :=
relim: R m n -> P -> Q.
Arguments RElim {A%type B%type} R%rel m n P%type Q%type.
Ltac relim H :=
lazymatch goal with
| |- ?Q =>
apply (relim (Q:=Q) H)
end.
(** The resolution process is directed by the syntax of [R]. We define
an instance for each function relator. The base case simply uses the
relational property as-is. *)
Global Instance relim_base {A B} (R: rel A B) m n:
RElim R m n True (R m n) | 10.
Proof.
firstorder.
Qed.
(** ** Destructing relational hypotheses *)
(** To make progress when the goal relates two pattern matching
constructions, we need to show that the two matched terms are
related, then destruct that hypothesis in a such a way that the two
terms reduce to constructors.
For most relators of inductive types, the constructors of the
relator will simply follow the constructors of the corresponding
type, so that destructing the relational hypothesis in the usual way
will produce the desired outcome. However, sometimes it is more
convenient to define such relators in a different way (see for
instance [prod_rel]). In that case, we can use the following
typeclass to specify an alternative way to destruct corresponding
hypotheses.
An instance of [RDestruct] is somewhat similar to a stylized
induction principle. [T] expands to a conjunction of subgoals in the
format expected by [Delay.split_conjunction]. For instance, the
induction principle for [sum_rel] is:
<<
sum_rel_ind:
forall ...,
(forall a1 a2, RA a1 a2 -> P (inl a1) (inl a2)) ->
(forall b1 b2, RB b1 b2 -> P (inr b1) (inr b2)) ->
(forall p1 p2, (RA + RB) p1 p2 -> P p1 p2)
>>
A corresponding instance of [RDestruct] would be:
<<
sum_rdestruct:
RDestruct
(sum_rel RA RB)
(fun P =>
(forall a1 a2, RA a1 a2 -> P (inl a1) (inl a2)) /\
(forall b1 b2, RB b1 b2 -> P (inr b1) (inr b2)))
>>
In the case of [sum_rel] however, which is defined as an inductive
type with similar structure to [sum], we can rely on the default
instance of [RDestruct], which simply uses the [destruct] tactic. *)
Class RDestruct {A B: Type} (R: rel A B) (T: rel A B -> Prop) :=
rdestruct m n: R m n -> forall P, T P -> P m n.
(** See the [RDestruct] library for the corresponding instance of
[RStep], the default instance of [RDestruct], and a way to control
whether or not we should keep equations for the destructed terms. *)
(** ** Monotonicity properties *)
(** We use the class [Related] for the user to declare monotonicity
properties. This is a generalization of [Morphisms.Proper] from the
Coq standard library: although we expect that most of the time the
left- and right-hand side terms will be identical, they could be
slightly different partial applications of the same function.
Usually the differing arguments will be implicit, so that the user
can still rely on the [Monotonic] notation below. Occasionally, you
may need to spell out the two different terms and use the actual
class instead.
Note that the argument order below eschews the precedent of [Proper],
which has the relation first, followed by the proper element. This is
deliberate: we want the type parameters [A] and [B] to be unified in
priority against the type of [f] and [g], rather than that of [R].
In particular, the relator [forall_rel] yields an eta-expanded type
of the form [(fun x => T x) x] for its arguments. When [A] and [B]
take this peculiar form, instances declared using [forall_rel]
become unusable (I assume because no second-order unification is
performed when looking up the typeclass instance database). By
contrast the type of [f] and [g] is much more likely to be in a
"reasonable" form. *)
Class Related {A B} (f: A) (g: B) (R: rel A B) :=
related: R f g.
Arguments Related {A%type B%type} _ _ R%rel.
Notation "'@' 'Monotonic' T m R" := (@Related T T m m R%rel)
(at level 10, T at next level, R at next level, m at next level).
Notation Monotonic m R := (Related m m R%rel).
(** We provide a [RStep] instance for unfolding [Related]. *)
Lemma unfold_monotonic_rstep {A B} (R: rel A B) m n:
RStep (R m n) (Related m n R).
Proof.
firstorder.
Qed.
Hint Extern 1 (RStep _ (Related _ _ _)) =>
eapply unfold_monotonic_rstep : typeclass_instances.
(** ** Order on relations *)
(** This is our generalization of [subrelation]. Like the original it
constitutes a preorder, and the union and intersection of relations
are the corresponding join and meet. *)
Definition subrel {A B}: rel (rel A B) (rel A B) :=
fun R1 R2 => forall x y, R1 x y -> R2 x y.
Arguments subrel {A%type B%type} R1%rel R2%rel.
Global Instance subrel_preorder A B:
@PreOrder (rel A B) subrel.
Proof.
split; firstorder.
Qed.
Global Instance eq_subrel {A} (R: rel A A):
Reflexive R ->
Related eq R subrel.
Proof.
intros HR x y H.
subst.
reflexivity.
Qed.
Instance subrel_impl_relim {A B} (R1 R2 : rel A B) x1 x2 y1 y2 P Q:
RElim impl (R1 x1 y1) (R2 x2 y2) P Q ->
RElim subrel R1 R2 (x1 = x2 /\ y1 = y2 /\ P) Q.
Proof.
cbv.
firstorder.
subst.
eauto.
Qed.
(** * Core relators *)
(** First, we introduce the core relators necessary for everything
else, namely those for function types. The next section provides a
more comprehensive library which covers many of the basic inductive
type constructors as well. *)
(** *** Non-dependent function types *)
(** First, I define relators for non-dependent functions. This
generalizes [respectful]. *)
Definition arrow_rel {A1 A2 B1 B2}:
rel A1 A2 -> rel B1 B2 -> rel (A1 -> B1) (A2 -> B2) :=
fun RA RB f g => forall x y, RA x y -> RB (f x) (g y).
Arguments arrow_rel {A1%type A2%type B1%type B2%type} RA%rel RB%rel _ _.
Notation "RA ==> RB" := (arrow_rel RA RB)
(at level 55, right associativity) : rel_scope.
Notation "RA ++> RB" := (arrow_rel RA RB)
(at level 55, right associativity) : rel_scope.
Notation "RA --> RB" := (arrow_rel (flip RA) RB)
(at level 55, right associativity) : rel_scope.
Global Instance arrow_subrel {A1 A2 B1 B2}:
Monotonic (@arrow_rel A1 A2 B1 B2) (subrel --> subrel ++> subrel).
Proof.
firstorder.
Qed.
Global Instance arrow_subrel_params:
Params (@arrow_rel) 4.
Lemma arrow_rintro {A1 A2 B1 B2} (RA: rel A1 A2) (RB: rel B1 B2) f g:
RIntro (forall x y, RA x y -> RB (f x) (g y)) (RA ++> RB) f g.
Proof.
firstorder.
Qed.
Hint Extern 0 (RIntro _ (_ ++> _) _ _) =>
eapply arrow_rintro : typeclass_instances.
Lemma arrow_relim {A1 A2 B1 B2} RA RB f g m n P Q:
@RElim B1 B2 RB (f m) (g n) P Q ->
@RElim (A1 -> B1) (A2 -> B2) (RA ++> RB) f g (RA m n /\ P) Q.
Proof.
firstorder.
Qed.
Hint Extern 1 (RElim (_ ++> _) _ _ _ _) =>
eapply arrow_relim : typeclass_instances.
(** *** Dependent products *)
(** Now we consider the dependent case. The definition of [forall_rel]
is somewhat involved, but you can think of relating [f] and [g] in
the context of a structure-preserving transformation from a quiver
([V], [E]) to the quiver ([Type], [rel]). Like a functor, it has two
components: [FV] maps nodes to types, and [FE] maps edges to
relations. Then, [forall_rel FE f g] states that given an edge
[(e : E v1 v2)], the images [f v1] and [g v2] are related by the
corresponding relation [FE v1 v2 e]. We will write [forall_rel FE f g]
as [(forallr e @ v1 v2 : E, FE[v1,v2,e]) f g]. Notice that this notation
binds [v1] and [v2] as well as [e].
If that makes no sense, you can think of specific source quivers. So
for instance, oftentimes we will want to use ([Type], [rel]) as the
source quiver too. This corresponds to parametric polymorphism. The
type of [Some] is [forall A : Type, A -> option A]; the corresponding
logical relation is [forallr R @ A1 A2 : rel, R ++> option_rel R]. Stating
that [Monotonic Some (foralr R @ A1 A2 : rel, R ++> option_rel R)] means that,
given any relation [R] and elements [x1] and [x2], if [R] relates
[x1] and [x2], then [option_rel R] will relate [Some x1] and [Some x2].
Another example from [liblayers] is the quiver of our data-indexed
simulation relations [simrel : layerdata -> layerdata -> Type].
Here the structure-preserving transformations are our simulation
relation diagrams, which have types such as
[lsim : forall D1 D2, simrel D1 D2 -> rel (layer D1) (layer D2)] or
[psim : forall {D1 D2}, simrel D1 D2 -> rel (primsem D1) (primsem D2)].
Then, the monotonicity of a data-indexed function —
say, [foo: forall D : layerdata, layer D -> primsem D] —
can be expressed as
[Monotonic foo (forall R @ D1 D2 : simrel, siml D1 D2 R ++> simp D1 D2 R) foo].
This definition is the same as [respectful_hetero]. *)
Definition forall_rel {V1 V2} {E: V1->V2->Type} {FV1: V1->Type} {FV2: V2->Type}:
(forall v1 v2, E v1 v2 -> rel (FV1 v1) (FV2 v2)) ->
rel (forall v1, FV1 v1) (forall v2, FV2 v2) :=
fun FE f g =>
forall v1 v2 (e: E v1 v2), FE v1 v2 e (f v1) (g v2).
Arguments forall_rel {V1%type V2%type E%type FV1%type FV2%type} FE%rel _ _.
Notation "'forallr' e @ v1 v2 : E , R" :=
(forall_rel (E := E) (fun v1 v2 e => R))
(at level 200, e ident, v1 ident, v2 ident, right associativity) : rel_scope.
Notation "'forallr' e @ v1 v2 , R" :=
(forall_rel (fun v1 v2 e => R))
(at level 200, e ident, v1 ident, v2 ident, right associativity) : rel_scope.
Notation "'forallr' e : E , R" :=
(forall_rel (E := E) (fun _ _ e => R))
(at level 200, e ident, right associativity) : rel_scope.
Notation "'forallr' e , R" :=
(forall_rel (fun _ _ e => R))
(at level 200, e ident, right associativity) : rel_scope.
Lemma forall_rintro {V1 V2 E F1 F2} (FE: forall x y, _ -> rel _ _) f g:
RIntro
(forall u v e, FE u v e (f u) (g v))
(@forall_rel V1 V2 E F1 F2 FE) f g.
Proof.
firstorder.
Qed.
Hint Extern 0 (RIntro _ (forall_rel _) _ _) =>
eapply forall_rintro : typeclass_instances.
Lemma forall_relim {V1 V2 E FV1 FV2} R f g v1 v2 e P Q:
RElim (R v1 v2 e) (f v1) (g v2) P Q ->
RElim (@forall_rel V1 V2 E FV1 FV2 R) f g P Q.
Proof.
firstorder.
Qed.
Hint Extern 1 (RElim (forall_rel _) _ _ _ _) =>
eapply forall_relim : typeclass_instances.
(** ** Inverse relation *)
(** We use [flip] as our inversion relator. To this end we
characterize its variance and introduce an [RElim] rule. *)
Global Instance flip_subrel {A B}:
Monotonic (@flip A B Prop) (subrel ++> subrel).
Proof.
firstorder.
Qed.
Global Instance flip_subrel_params:
Params (@flip) 3.
Lemma flip_rintro {A B} (R: rel A B) m n:
RIntro (R n m) (flip R) m n.
Proof.
firstorder.
Qed.
Hint Extern 1 (RIntro _ (flip _) _ _) =>
eapply flip_rintro : typeclass_instances.
Lemma flip_relim {A B} (R: rel A B) m n P Q:
RElim R n m P Q ->
RElim (flip R) m n P Q.
Proof.
firstorder.
Qed.
Hint Extern 1 (RElim (flip _) _ _ _ _) =>
eapply flip_relim : typeclass_instances.
Lemma flip_rdestruct {A B} (R: rel A B) T:
RDestruct R T ->
RDestruct (flip R) (fun P => T (flip P)).
Proof.
firstorder.
Qed.
Hint Extern 1 (RDestruct (flip _) _) =>
eapply flip_rdestruct : typeclass_instances.
| {
"pile_set_name": "Github"
} |
<?php
namespace framework\database;
/**
* DB接口类
*/
interface DbInterface{
public function query($sql); //执行SQL
public function fetch($sql); //从结果集中取出一行
public function fetchAll($sql); //从结果集中取出全部数据
public function getInsertId(); //获取最后插入主键ID
public function getAffectedRows(); //获取受影响的记录数
public function getVersion(); //获取数据库版本
public function beginTrans(); //开启事务
public function commit(); //提交事务
public function rollback(); //回滚事务
public function escapeString($str); //数据安全处理
public function close(); //资源回收
public function __destruct(); //析构函数
} | {
"pile_set_name": "Github"
} |
<?php
/**
*
* License, TERMS and CONDITIONS
*
* This software is licensed under the GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
* Please read the license here : http://www.gnu.org/licenses/lgpl-3.0.txt
*
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* ATTRIBUTION REQUIRED
* 4. All web pages generated by the use of this software, or at least
* the page that lists the recent questions (usually home page) must include
* a link to the http://www.lampcms.com and text of the link must indicate that
* the website\'s Questions/Answers functionality is powered by lampcms.com
* An example of acceptable link would be "Powered by <a href="http://www.lampcms.com">LampCMS</a>"
* The location of the link is not important, it can be in the footer of the page
* but it must not be hidden by style attributes
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 FREEBSD PROJECT 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.
*
* This product includes GeoLite data created by MaxMind,
* available from http://www.maxmind.com/
*
*
* @author Dmitri Snytkine <[email protected]>
* @copyright 2005-2012 (or current year) Dmitri Snytkine
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
* @link http://www.lampcms.com Lampcms.com project
* @version Release: @package_version@
*
*
*/
namespace Lampcms\Controllers;
use Lampcms\Mongo\Schema\Answer as AnswerSchema;
use Lampcms\Mongo\Schema\Question as QuestionSchema;
use Lampcms\Request;
use Lampcms\Responder;
use Lampcms\String\HTMLStringParser;
use Lampcms\Utf8String;
/**
* Controller for processing "Edit"
* form for editing Question or Answer
*
* @todo should move the parsing to
* new class so the whole parsing thing
* can later be used from the API and not just
* from this controller.
*
* @author Dmitri Snytkine
*
*/
class Editor extends Edit
{
protected $membersOnly = true;
protected $requireToken = true;
protected $bRequirePost = true;
protected $aRequired = array('rid', 'rtype');
/**
* @var object Utf8String Submitted parsed body converted to plaintext
* but still represented as an Utf8String object (not string)
*/
protected $plainTextBody;
/**
* Object Utf8String represents body
* of question
*
* @var object of type Utf8string
*/
protected $Body;
protected function main()
{
$this->getResource()
->checkPermission()
->makeForm();
if ($this->Form->validate()) {
$this->process()->updateQuestion()->returnResult();
} else {
$this->returnErrors();
}
}
protected function returnErrors()
{
d('cp');
if (Request::isAjax()) {
d('cp');
$aErrors = $this->Form->getErrors();
Responder::sendJSON(array('formErrors' => $aErrors));
}
$this->makeTopTabs()
->makeMemo()
->setForm();
}
/**
*
* Process submitted form values
*
* edge cases with category: if category was required
* when question was posted but now it's optional
* then it's possible to change the category from selected one
* to empty (no category) by simply selecting the "no category"
* in the drop down menu. Also if category support was removed completely
* by admin by setting CATEGORIES to empty in !config.ini
* then submitted value will be empty - in this case we don't want to
* update an existing category with an empty one. So the only way we can
* accept the empty category is when CATEGORIES are optional and empty value is submitted
*
*
*
*
* @return \Lampcms\Controllers\Editor
*/
protected function process()
{
$this->Registry->Dispatcher->post($this->Resource, 'onBeforeEdit');
$formVals = $this->Form->getSubmittedValues();
d('formVals: ' . json_encode($formVals));
$htmlBody = $this->makeBody($formVals['qbody']);
$this->Resource[QuestionSchema::BODY] = $htmlBody;
$this->Resource[QuestionSchema::WORDS_COUNT] = $this->Body->asPlainText()->getWordsCount();
/**
* @important Don't attempt to edit the value of title
* for the answer since it technically does not have the title
* If we don't skip this step for Answer then title
* of answer will be removed
*/
if ($this->Resource instanceof \Lampcms\Question) {
$hash = hash('md5', strtolower($htmlBody . json_encode($this->Resource[QuestionSchema::TAGS_ARRAY])));
$origTitle = $this->Resource[QuestionSchema::TITLE];
$origCategoryId = $this->Resource[QuestionSchema::CATEGORY_ID];
d('$origTitle: ' . $origTitle . ' $origCategoryId: ' . $origCategoryId);
$oTitle = $this->makeTitle($formVals['title']);
$title = $oTitle->valueOf();
$categoryId = \array_key_exists('category', $formVals) ? $formVals['category'] : 0;
$categoryId = (int)$categoryId;
$this->Resource[QuestionSchema::TITLE] = $title;
$this->Resource[QuestionSchema::URL] = $oTitle->toASCII()->makeLinkTitle()->valueOf();
$this->Resource[QuestionSchema::TITLE_ARRAY] = \Lampcms\TitleTokenizer::factory($oTitle)->getArrayCopy();
$this->Resource[QuestionSchema::INTRO] = $this->plainTextBody->truncate(150)->valueOf();
$this->Resource[QuestionSchema::BODY_HASH] = $hash;
/**
*
* Need to update 'title' of all answers to this question
* But first check to see if title has actually changed
*
* ONLY if Question status is POSTED (don't do anything for pending)
*
*/
if ($this->Resource[QuestionSchema::RESOURCE_STATUS_ID] === QuestionSchema::POSTED) {
if ($origTitle !== $title) {
$this->updateAnswersTitle($title);
}
if ($origCategoryId !== $categoryId) {
/**
* If Submitted category ID is empty
* then allow it ONLY if category support is optional ( value of CATEGORIES is 1 in !config.ini)
*/
if ($categoryId > 0 || $this->Registry->Ini->CATEGORIES == 1) {
$this->Resource[QuestionSchema::CATEGORY_ID] = $categoryId;
$this->updateCategoryCounter($origCategoryId, $categoryId);
/**
* Post onCategoryUpdate event
* It will cause the CacheObserver to unset the cached categories html blocks
*/
$this->Registry->Dispatcher->post($this->Resource, 'onCategoryUpdate');
}
}
}
}
$this->Resource->setEdited($this->Registry->Viewer, \strip_tags($formVals['reason']));
$this->Resource->touch()->save();
$this->Registry->Dispatcher->post($this->Resource, 'onEdit');
return $this;
}
/**
*
* Update the contents of body
* with edited content
* If this is a question do extra steps;
* unhighlight (just in case that actual highlighed words
* have been edited), then re-apply highlightWords()
* just in case some of the new word that belong to
* tags have been added
*
* @param string $body
*
* @return string html of new body
*
*/
protected function makeBody($body)
{
/**
* Must pass array('drop-proprietary-attributes' => false)
* otherwise tidy removes rel="code"
*/
$aEditorConfig = $this->Registry->Ini->getSection('EDITOR');
$tidyConfig = ($aEditorConfig['ENABLE_CODE_EDITOR']) ? array('drop-proprietary-attributes' => false) : null;
$this->Body = Utf8String::stringFactory($body)
->tidy($tidyConfig)
->safeHtml()
->asHtml();
$Body = HTMLStringParser::stringFactory($this->Body)->parseCodeTags()->linkify()->reload()->setNofollow();
if ($this->Resource instanceof \Lampcms\Question) {
$Body->unhilight()->hilightWords($this->Resource[QuestionSchema::TAGS_ARRAY]);
}
$this->plainTextBody = $this->Body->asPlainText();
d('plain text body: ' . $this->plainTextBody);
$htmlBody = $Body->valueOf();
d('after HTMLStringParser: ' . $htmlBody);
return $htmlBody;
}
/**
* Make new value of title
*
* @param string $title
*
* @return object of type Utf8String
*/
protected function makeTitle($title)
{
$oTitle = Utf8String::stringFactory($title)->htmlentities()->trim();
d('$oTitle ' . $oTitle);
return $oTitle;
}
/**
* If Edited resource was an ANSWER then we must update
* last-modified of its QUESTION
*
* @return object $this
*/
protected function updateQuestion()
{
if ('ANSWERS' === $this->collection) {
d('need to update QUESTION');
try {
$this->Registry->Mongo->QUESTIONS->update(array('_id' => $this->Resource['i_qid']),
array(
'$set' => array(
'i_lm_ts' => time(),
'i_etag' => time())
)
);
} catch ( \MongoException $e ) {
d('unable to update question ' . $e->getMessage());
}
}
return $this;
}
/**
* If ID of category of question changes
* must update the counter of questions in the new category (+1)
* and decrease count in old category (-1)
*
* If question has any answers must update counter of answers in old category (-$numAnswers)
* and increase counter in new category (+$numAnswers)
*
* @param $oldCategoryId
* @param $newCategoryId
*
* @return $this
* @throws \InvalidArgumentException if $oldId or $newId is not an integer
* @internal param int $oldId
* @internal param int $newId
*
*/
protected function updateCategoryCounter($oldCategoryId, $newCategoryId)
{
if (!is_int($oldCategoryId)) {
throw new \InvalidArgumentException('$oldCategoryId is not an integer');
}
if (!is_int($newCategoryId)) {
throw new \InvalidArgumentException('$newCategoryId is not an integer');
}
$CategoryUpdator = new \Lampcms\Category\Updator($this->Registry->Mongo);
$CategoryUpdator->removeQuestionById($this->Resource[QuestionSchema::PRIMARY], $oldCategoryId);
$CategoryUpdator->increaseQuestionCount($newCategoryId);
$answersCount = $this->Resource[QuestionSchema::NUM_ANSWERS];
d('Count of answers: ' . $answersCount);
if ($answersCount > 0) {
$CategoryUpdator->decreaseAnswerCount($oldCategoryId, $answersCount);
$CategoryUpdator->increaseAnswerCount($newCategoryId, $answersCount);
}
return $this;
}
/**
* Update all answers for the edited question
* with the new title.
* This method is called only if the title of the question
* has changed
*
* @param string $newTitle
*
* @return $this
*/
protected function updateAnswersTitle($newTitle)
{
/**
* We called this method after we already made sure that
* the edit is for the Question , not for the Answer
* but it's so important to make sure that this is the Question edit
* that we will check it again here.
*
*
*/
if ($this->Resource instanceof \Lampcms\Question) {
d('updating all questions with new title: ' . $newTitle);
$AnswerParser = new \Lampcms\AnswerParser($this->Registry);
$AnswerParser->updateTitle($this->Resource[QuestionSchema::PRIMARY], $newTitle);
}
return $this;
}
protected function returnResult()
{
Responder::redirectToPage($this->Resource->getUrl());
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build freebsd
package unix
import (
errorspkg "errors"
"fmt"
)
// Go implementation of C mostly found in /usr/src/sys/kern/subr_capability.c
const (
// This is the version of CapRights this package understands. See C implementation for parallels.
capRightsGoVersion = CAP_RIGHTS_VERSION_00
capArSizeMin = CAP_RIGHTS_VERSION_00 + 2
capArSizeMax = capRightsGoVersion + 2
)
var (
bit2idx = []int{
-1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1,
4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
}
)
func capidxbit(right uint64) int {
return int((right >> 57) & 0x1f)
}
func rightToIndex(right uint64) (int, error) {
idx := capidxbit(right)
if idx < 0 || idx >= len(bit2idx) {
return -2, fmt.Errorf("index for right 0x%x out of range", right)
}
return bit2idx[idx], nil
}
func caprver(right uint64) int {
return int(right >> 62)
}
func capver(rights *CapRights) int {
return caprver(rights.Rights[0])
}
func caparsize(rights *CapRights) int {
return capver(rights) + 2
}
// CapRightsSet sets the permissions in setrights in rights.
func CapRightsSet(rights *CapRights, setrights []uint64) error {
// This is essentially a copy of cap_rights_vset()
if capver(rights) != CAP_RIGHTS_VERSION_00 {
return fmt.Errorf("bad rights version %d", capver(rights))
}
n := caparsize(rights)
if n < capArSizeMin || n > capArSizeMax {
return errorspkg.New("bad rights size")
}
for _, right := range setrights {
if caprver(right) != CAP_RIGHTS_VERSION_00 {
return errorspkg.New("bad right version")
}
i, err := rightToIndex(right)
if err != nil {
return err
}
if i >= n {
return errorspkg.New("index overflow")
}
if capidxbit(rights.Rights[i]) != capidxbit(right) {
return errorspkg.New("index mismatch")
}
rights.Rights[i] |= right
if capidxbit(rights.Rights[i]) != capidxbit(right) {
return errorspkg.New("index mismatch (after assign)")
}
}
return nil
}
// CapRightsClear clears the permissions in clearrights from rights.
func CapRightsClear(rights *CapRights, clearrights []uint64) error {
// This is essentially a copy of cap_rights_vclear()
if capver(rights) != CAP_RIGHTS_VERSION_00 {
return fmt.Errorf("bad rights version %d", capver(rights))
}
n := caparsize(rights)
if n < capArSizeMin || n > capArSizeMax {
return errorspkg.New("bad rights size")
}
for _, right := range clearrights {
if caprver(right) != CAP_RIGHTS_VERSION_00 {
return errorspkg.New("bad right version")
}
i, err := rightToIndex(right)
if err != nil {
return err
}
if i >= n {
return errorspkg.New("index overflow")
}
if capidxbit(rights.Rights[i]) != capidxbit(right) {
return errorspkg.New("index mismatch")
}
rights.Rights[i] &= ^(right & 0x01FFFFFFFFFFFFFF)
if capidxbit(rights.Rights[i]) != capidxbit(right) {
return errorspkg.New("index mismatch (after assign)")
}
}
return nil
}
// CapRightsIsSet checks whether all the permissions in setrights are present in rights.
func CapRightsIsSet(rights *CapRights, setrights []uint64) (bool, error) {
// This is essentially a copy of cap_rights_is_vset()
if capver(rights) != CAP_RIGHTS_VERSION_00 {
return false, fmt.Errorf("bad rights version %d", capver(rights))
}
n := caparsize(rights)
if n < capArSizeMin || n > capArSizeMax {
return false, errorspkg.New("bad rights size")
}
for _, right := range setrights {
if caprver(right) != CAP_RIGHTS_VERSION_00 {
return false, errorspkg.New("bad right version")
}
i, err := rightToIndex(right)
if err != nil {
return false, err
}
if i >= n {
return false, errorspkg.New("index overflow")
}
if capidxbit(rights.Rights[i]) != capidxbit(right) {
return false, errorspkg.New("index mismatch")
}
if (rights.Rights[i] & right) != right {
return false, nil
}
}
return true, nil
}
func capright(idx uint64, bit uint64) uint64 {
return ((1 << (57 + idx)) | bit)
}
// CapRightsInit returns a pointer to an initialised CapRights structure filled with rights.
// See man cap_rights_init(3) and rights(4).
func CapRightsInit(rights []uint64) (*CapRights, error) {
var r CapRights
r.Rights[0] = (capRightsGoVersion << 62) | capright(0, 0)
r.Rights[1] = capright(1, 0)
err := CapRightsSet(&r, rights)
if err != nil {
return nil, err
}
return &r, nil
}
// CapRightsLimit reduces the operations permitted on fd to at most those contained in rights.
// The capability rights on fd can never be increased by CapRightsLimit.
// See man cap_rights_limit(2) and rights(4).
func CapRightsLimit(fd uintptr, rights *CapRights) error {
return capRightsLimit(int(fd), rights)
}
// CapRightsGet returns a CapRights structure containing the operations permitted on fd.
// See man cap_rights_get(3) and rights(4).
func CapRightsGet(fd uintptr) (*CapRights, error) {
r, err := CapRightsInit(nil)
if err != nil {
return nil, err
}
err = capRightsGet(capRightsGoVersion, int(fd), r)
if err != nil {
return nil, err
}
return r, nil
}
| {
"pile_set_name": "Github"
} |
// Normal comment here
//<if debug>
var lorem = {
ipsum: true,
// Nested if here
//<if browser=ie browserVersion=7>
if_here: 'blah',
//<elseif browser="!ie">
elseif_here: 'tada',
//<else>
else_here: 'ok',
//</if>
other: 'thing'
};
//</if>
//<unknownTag>
var testing = 123; | {
"pile_set_name": "Github"
} |
import takeAll from "./takeAll.js";
import deepFlatL from "../Lazy/deepFlatL.js";
export default function deepFlat(iter) {
return takeAll(deepFlatL(iter));
}
| {
"pile_set_name": "Github"
} |
; COMMAND-LINE: --finite-model-find --no-check-models
; EXPECT: sat
(set-logic ALL)
(declare-sort U 0)
(declare-fun g (U) Int)
(declare-sort V 0)
(declare-fun f (V) Int)
(assert (and
(forall ((?i U)) (not (forall ((?z V)) (not (= (f ?z) (div (- 1) (g ?i))))) ))
))
(declare-fun k () U)
(assert (= (g k) 22))
(check-sat)
| {
"pile_set_name": "Github"
} |
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
// peripheral RTC
namespace RtcWtcr1{ ///< register WTCR1
using Addr = Register::Address<0x4003b000,0x0000e082,0x00000000,unsigned>;
/// bitfield INTCRIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> intcrie{};
/// bitfield INTERIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> interie{};
/// bitfield INTALIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> intalie{};
/// bitfield INTTMIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> inttmie{};
/// bitfield INTHIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> inthie{};
/// bitfield INTMIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> intmie{};
/// bitfield INTSIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> intsie{};
/// bitfield INTSSIE
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> intssie{};
/// bitfield INTCRI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> intcri{};
/// bitfield INTERI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> interi{};
/// bitfield INTALI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> intali{};
/// bitfield INTTMI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> inttmi{};
/// bitfield INTHI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> inthi{};
/// bitfield INTMI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> intmi{};
/// bitfield INTSI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> intsi{};
/// bitfield INTSSI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> intssi{};
/// bitfield YEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> yen{};
/// bitfield MOEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> moen{};
/// bitfield DEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> den{};
/// bitfield HEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> hen{};
/// bitfield MIEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> mien{};
/// bitfield BUSY
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> busy{};
/// bitfield SCRST
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> scrst{};
/// bitfield SCST
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> scst{};
/// bitfield SRST
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> srst{};
/// bitfield RUN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> run{};
/// bitfield ST
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> st{};
}
namespace RtcWtcr2{ ///< register WTCR2
using Addr = Register::Address<0x4003b004,0xfffff8fe,0x00000000,unsigned>;
/// bitfield TMRUN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tmrun{};
/// bitfield TMEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> tmen{};
/// bitfield TMST
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> tmst{};
/// bitfield CREAD
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> cread{};
}
namespace RtcWtbr{ ///< register WTBR
using Addr = Register::Address<0x4003b008,0xff000000,0x00000000,unsigned>;
/// bitfield BR23
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> br23{};
/// bitfield BR22
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> br22{};
/// bitfield BR21
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> br21{};
/// bitfield BR20
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> br20{};
/// bitfield BR19
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> br19{};
/// bitfield BR18
constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> br18{};
/// bitfield BR17
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> br17{};
/// bitfield BR16
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> br16{};
/// bitfield BR15
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> br15{};
/// bitfield BR14
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> br14{};
/// bitfield BR13
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> br13{};
/// bitfield BR12
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> br12{};
/// bitfield BR11
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> br11{};
/// bitfield BR10
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> br10{};
/// bitfield BR9
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> br9{};
/// bitfield BR8
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> br8{};
/// bitfield BR7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> br7{};
/// bitfield BR6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> br6{};
/// bitfield BR5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> br5{};
/// bitfield BR4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> br4{};
/// bitfield BR3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> br3{};
/// bitfield BR2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> br2{};
/// bitfield BR1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> br1{};
/// bitfield BR0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> br0{};
}
namespace RtcWtdr{ ///< register WTDR
using Addr = Register::Address<0x4003b00f,0xffffffc0,0x00000000,unsigned char>;
/// bitfield TD
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> td{};
/// bitfield D
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> d{};
}
namespace RtcWthr{ ///< register WTHR
using Addr = Register::Address<0x4003b00e,0xffffffc0,0x00000000,unsigned char>;
/// bitfield TH
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> th{};
/// bitfield H
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> h{};
}
namespace RtcWtmir{ ///< register WTMIR
using Addr = Register::Address<0x4003b00d,0xffffff80,0x00000000,unsigned char>;
/// bitfield TMI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> tmi{};
/// bitfield MI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> mi{};
}
namespace RtcWtsr{ ///< register WTSR
using Addr = Register::Address<0x4003b00c,0xffffff80,0x00000000,unsigned char>;
/// bitfield TS
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> ts{};
/// bitfield S
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> s{};
}
namespace RtcWtyr{ ///< register WTYR
using Addr = Register::Address<0x4003b012,0xffffff00,0x00000000,unsigned char>;
/// bitfield TY
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> ty{};
/// bitfield Y
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> y{};
}
namespace RtcWtmor{ ///< register WTMOR
using Addr = Register::Address<0x4003b011,0xffffffe0,0x00000000,unsigned char>;
/// bitfield TMO0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tmo0{};
/// bitfield MO
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> mo{};
}
namespace RtcWtdw{ ///< register WTDW
using Addr = Register::Address<0x4003b010,0xfffffff8,0x00000000,unsigned char>;
/// bitfield DW
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> dw{};
}
namespace RtcAldr{ ///< register ALDR
using Addr = Register::Address<0x4003b017,0xffffffc0,0x00000000,unsigned char>;
/// bitfield TAD
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> tad{};
/// bitfield AD
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> ad{};
}
namespace RtcAlhr{ ///< register ALHR
using Addr = Register::Address<0x4003b016,0xffffffc0,0x00000000,unsigned char>;
/// bitfield TAH
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> tah{};
/// bitfield AH
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> ah{};
}
namespace RtcAlmir{ ///< register ALMIR
using Addr = Register::Address<0x4003b015,0xffffff80,0x00000000,unsigned char>;
/// bitfield TAMI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> tami{};
/// bitfield AMI
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> ami{};
}
namespace RtcAlyr{ ///< register ALYR
using Addr = Register::Address<0x4003b01a,0xffffff00,0x00000000,unsigned char>;
/// bitfield TAY
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> tay{};
/// bitfield AY
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> ay{};
}
namespace RtcAlmor{ ///< register ALMOR
using Addr = Register::Address<0x4003b019,0xffffffe0,0x00000000,unsigned char>;
/// bitfield TAMO0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tamo0{};
/// bitfield AMO
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> amo{};
}
namespace RtcWttr{ ///< register WTTR
using Addr = Register::Address<0x4003b01c,0xfffc0000,0x00000000,unsigned>;
/// bitfield TM17
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> tm17{};
/// bitfield TM16
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> tm16{};
/// bitfield TM15
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> tm15{};
/// bitfield TM14
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> tm14{};
/// bitfield TM13
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> tm13{};
/// bitfield TM12
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> tm12{};
/// bitfield TM11
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> tm11{};
/// bitfield TM10
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> tm10{};
/// bitfield TM9
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> tm9{};
/// bitfield TM8
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> tm8{};
/// bitfield TM7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> tm7{};
/// bitfield TM6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tm6{};
/// bitfield TM5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tm5{};
/// bitfield TM4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tm4{};
/// bitfield TM3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> tm3{};
/// bitfield TM2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tm2{};
/// bitfield TM1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> tm1{};
/// bitfield TM0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tm0{};
}
namespace RtcWtclks{ ///< register WTCLKS
using Addr = Register::Address<0x4003b020,0xfffffffe,0x00000000,unsigned char>;
/// bitfield WTCLKS
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> wtclks{};
}
namespace RtcWtclkm{ ///< register WTCLKM
using Addr = Register::Address<0x4003b021,0xfffffffc,0x00000000,unsigned char>;
/// bitfield WTCLKM
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wtclkm{};
}
namespace RtcWtcal{ ///< register WTCAL
using Addr = Register::Address<0x4003b024,0xfffffc00,0x00000000,unsigned>;
/// bitfield WTCAL
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,0),Register::ReadWriteAccess,unsigned> wtcal{};
}
namespace RtcWtcalen{ ///< register WTCALEN
using Addr = Register::Address<0x4003b026,0xfffffffe,0x00000000,unsigned char>;
/// bitfield WTCALEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> wtcalen{};
}
namespace RtcWtdiv{ ///< register WTDIV
using Addr = Register::Address<0x4003b028,0xfffffff0,0x00000000,unsigned char>;
/// bitfield WTDIV
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> wtdiv{};
}
namespace RtcWtdiven{ ///< register WTDIVEN
using Addr = Register::Address<0x4003b029,0xfffffffc,0x00000000,unsigned char>;
/// bitfield WTDIVRDY
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wtdivrdy{};
/// bitfield WTDIVEN
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> wtdiven{};
}
namespace RtcWtcalprd{ ///< register WTCALPRD
using Addr = Register::Address<0x4003b02c,0xffffffc0,0x00000000,unsigned char>;
/// bitfield WTCALPRD
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,0),Register::ReadWriteAccess,unsigned> wtcalprd{};
}
namespace RtcWtcosel{ ///< register WTCOSEL
using Addr = Register::Address<0x4003b030,0xfffffffe,0x00000000,unsigned char>;
/// bitfield WTCOSEL
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> wtcosel{};
}
}
| {
"pile_set_name": "Github"
} |
ympd is implemented only in C
By default, CMake assumes that the project is using both C and C++. By
explicitly passing 'C' as argument of the project() macro, we tell
CMake that only C is used, which prevents CMake from checking if a C++
compiler exists.
Signed-off-by: Thomas Petazzoni <[email protected]>
Index: b/CMakeLists.txt
===================================================================
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 2.6)
-project (ympd)
+project (ympd C)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake/")
set(CPACK_PACKAGE_VERSION_MAJOR "1")
set(CPACK_PACKAGE_VERSION_MINOR "2")
| {
"pile_set_name": "Github"
} |
package vn.vitk.tag;
/**
* @author Phuong LE-HONG
* <p>
* May 11, 2016, 5:53:37 PM
* <p>
* Markov order type, up the third order.
*/
public enum MarkovOrder {
FIRST, SECOND, THIRD
}
| {
"pile_set_name": "Github"
} |
---
id: version-v1.0.0-alpha-concepts
title: Concepts
original_id: concepts
---
Liftbridge is a durable stream augmentation for NATS, so it's important to
have a good grasp of the [key concepts in
NATS](https://nats-io.github.io/docs/developer/concepts/intro.html). NATS is a
pub/sub messaging system that centers around the concept of *subjects*. Clients
publish messages to subjects and receive messages from *subscriptions* to
subjects.
## Streams and Partitions
Fundamentally, Liftbridge is just a consumer of NATS subjects. It receives
messages received from NATS subjects and records them in a durable log which
is then exposed to subscribers. Specifically, Liftbridge centers around the
concept of a *stream*, which is a durable message stream attached to a NATS
subject. A stream consists of one or more *partitions*, which are ordered,
replicated, and durably stored on disk and serve as the unit of storage and
parallelism in Liftbridge.
Streams have a few key properties: a subject, which is the corresponding NATS
subject, a name, which is a human-readable identifier for the stream, and a
replication factor, which is the number of nodes the stream's partitions should
be replicated to for redundancy. Optionally, there is a group which is the name
of a load-balance group for the stream to join. When there are multiple streams
in the same group, messages will be balanced among them.
There can be multiple streams attached to the same NATS subject, but stream
names must be unique within a cluster.
By default, streams have a single partition. This partition maps directly to
the stream's NATS subject. If a stream has multiple partitions, each one maps
to a different NATS subject derived from the stream subject. For example, if a
stream with three partitions is attached to the subject "foo", the partitions
will map to the subjects "foo", "foo.1", and "foo.2", respectively.
Each partition has its own message log, leader, and set of followers.
### Write-Ahead Log
Each stream partition is backed by a durable write-ahead log. All reads and
writes to the log go through the partition *leader*, which is selected by the
cluster [controller](#controller). The leader sequences each message in the
partition and sends back an acknowledgement to publishers upon committing a
message to the log. A message is committed to the log once it has been
replicated to the partition's
[in-sync replica set (ISR)](#in-sync-replica-set-isr).
Consumers read committed messages from the log through a subscription on the
partition. They can read back from the log at any arbitrary position, or
*offset*. Additionally, consumers can wait for new messages to be appended
to the log.
### Scalability
Liftbridge is designed to be clustered and horizontally scalable. The
[controller](#controller) is responsible for creating stream partitions.
When a partition is created, the controller selects replicas based on the
stream's replication factor and replicates the partition to the cluster.
Once this replication completes, the partition has been created and the
leader begins processing messages.
As mentioned above, there can exist multiple streams attached to the same NATS
subject or even subjects that are semantically equivalent e.g. "foo.bar" and
"foo.*". Each of these streams will receive a copy of the message as NATS
handles this fan-out.
With this in mind, we can scale linearly by adding more nodes to the Liftbridge
cluster and creating more streams which will be distributed amongst the
cluster members. This has the advantage that we don't need to worry about
partitioning so long as NATS is able to withstand the load. The downside of this
is that it results in redundant processing of messages. Consumers of each stream
are all processing the same set of messages. The other issue is because each
stream is independent of each other, they have separate guarantees. Separate
leaders/followers, separate ISRs, and separate acking means the logs for each
stream are not guaranteed to be identical, even though they are bound to the
same NATS subject.
To accommodate this, streams are partitioned. By default, a stream consists of
just a single partition, but multiple partitions can be created for increased
parallelism. Messages can then be delivered to partitions based on their key,
in a round-robin fashion, randomly, or with some other partitioning strategy
on the client.
Additionally, streams can join a named load-balance group, which load balances
messages on a NATS subject amongst the streams in the group. Load-balance
groups do not affect message delivery to other streams not participating in
the group.
Currently, replicas in Liftbridge act only as a mechanism for high availability
and not scalability. However, there may be work in the future to allow them to
act as read replicas for further scale out.
The diagram below shows a cluster of three servers with a set of streams.
Partitions in yellow indicate the server is the leader for the partition.

### In-Sync Replica Set (ISR)
The In-Sync Replica set (ISR) is a key aspect of the replication protocol in
Liftbridge. The ISR consists of the set of partition replicas that are
currently caught up with the leader. It is equivalent to the [ISR concept in
Kafka](https://kafka.apache.org/documentation/#design_replicatedlog), and the
[replication protocol](./replication_protocol.md) works very similarly.
In order for a message to be committed to a partition's write-ahead log, it
must be acknowledged by all brokers in the ISR. To prevent a single slow
broker from blocking progress, replicas that fall too far behind the leader
are removed from the ISR. The leader does this by making a request to the
controller. In this case, the cluster enters an under-replicated state for
the partition.
Being "too far behind" is controlled by the `replica.max.lag.time`
configuration. This refers to both the maximum amount of time a replica can go
without making a replication request before it's removed and the amount of time
that can pass without being fully caught up with the leader before it's
removed. When a removed replica catches back up with the leader's log, it is
added back into the ISR and the cluster goes back into its fully replicated
state.
Under normal conditions, only a replica from the ISR can be elected the leader
of a partition. This favors data consistency over availability since if the ISR
shrinks too far, there is a risk of being unable to elect a new leader.
### Acknowledgement
Acknowledgements are an opt-in mechanism to guarantee message delivery. If a
[message envelope](#message-envelope) has an `AckInbox`, Liftbridge will send
an ack to this NATS inbox once the message has been committed. This is used to
ensure at-least-once delivery.
Messages can also have an optional `CorrelationId`, which is a user-defined
value which is also set on the server ack to correlate it to a published
message.
There are a couple of things to be aware of with message acknowledgements.
First, if the publisher doesn't care about ensuring its message is stored, it
need not set an `AckInbox`. Second, because there are potentially multiple
(or no) streams attached to a NATS subject (and creation of streams is
dynamic), it's not possible for the publisher to know how many acks to expect.
This is a trade-off we make for enabling subject fan-out and wildcards while
remaining scalable and fast. We make the assertion that if guaranteed delivery
is important, the publisher should be responsible for determining the
destination streams a priori. This allows attaching streams to a subject for
use cases that do not require strong guarantees without the publisher having to
be aware. Note that this might be an area for future improvement to increase
usability. However, this is akin to other similar systems, like Kafka, where
you must first create a topic and then you publish to that topic.
### Subscription
Subscriptions are how Liftbridge streams are consumed. A client subscribes to a
stream partition and specifies a starting offset to begin consuming from. At
this point, the server creates an ephemeral data stream for the client and
begins sending messages to it. Once it consumes up to the end of the log, the
server will wait for more messages to be published until the subscription is
closed by the client.
Subscriptions are not stateful objects. When a subscription is created, there
is no bookkeeping done by the server, aside from the in-memory objects tied to
the lifecycle of the subscription. As a result, the server does not track the
position of a client in the log beyond the scope of a subscription. Stateful
consumer groups will be coming in the near future which will allow a consumer
to pick up where it left off and provide fault-tolerant consumption of
streams.
### Stream Retention and Compaction
Streams support multiple log-retention rules: age-based, message-based, and
size-based. This, for example, allows semantics like "retain messages for 24
hours", "retain 100GB worth of messages", or "retain 1,000,000 messages".
Additionally, Liftbridge supports log *compaction*. Publishers can, optionally,
set a *key* on a [message envelope](#message-envelope). A stream can be
configured to compact by key. In this case, it retains only the last message
for each unique key. Messages that do not have a key are always retained.
## Controller
The controller is the metadata leader for the cluster. Specifically, it is the
*Raft* leader. All operations which require cluster coordination, such as
creating streams, expanding ISRs, shrinking ISRs, or electing stream leaders,
go through the controller and, subsequently, Raft to ensure linearizability.
Raft automatically handles failing over the controller in the event of a
failure for high availability.
Note that in order for the controller to make progress, a quorum (majority) of
the brokers must be running.
Controller is also referred to as "metadata leader" in some contexts.
## Message Envelope
Liftbridge extends NATS by allowing regular NATS messages to flow into durable
streams. This can be completely transparent to publishers. However, it also
allows publishers to *enhance* messages by providing additional metadata and
serializing their messages into *envelopes*. An envelope allows publishers to
set things like the `AckInbox`, `Key`, `Headers`, and other pieces of metadata.
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2000-2008 Apple Computer, Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*-
* Copyright (c) 1982, 1986, 1993
* The Regents of the University of California. All rights reserved.
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)subr_prof.c 8.3 (Berkeley) 9/23/93
*/
#ifdef GPROF
#include <libkern/kernel_mach_header.h>
#endif
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/proc_internal.h>
#include <sys/user.h>
#include <machine/machine_routines.h>
#include <sys/mount_internal.h>
#include <sys/sysproto.h>
#include <mach/mach_types.h>
#include <kern/kern_types.h>
#include <kern/cpu_number.h>
#include <kern/kalloc.h>
#ifdef GPROF
#include <sys/malloc.h>
#include <sys/gmon.h>
extern int sysctl_doprof(int *, u_int, user_addr_t, size_t *,
user_addr_t, size_t newlen);
extern int sysctl_struct(user_addr_t, size_t *,
user_addr_t, size_t, void *, int);
lck_spin_t * mcount_lock;
lck_grp_t * mcount_lock_grp;
lck_attr_t * mcount_lock_attr;
/*
* Froms is actually a bunch of unsigned shorts indexing tos
*/
struct gmonparam _gmonparam = { .state = GMON_PROF_OFF };
/*
* This code uses 32 bit mach object segment information from the currently
* running kernel.
*/
void
kmstartup(void)
{
tostruct_t *cp;
kernel_segment_command_t *sgp; /* 32 bit mach object file segment */
struct gmonparam *p = &_gmonparam;
sgp = getsegbyname("__TEXT");
p->lowpc = (u_int32_t)sgp->vmaddr;
p->highpc = (u_int32_t)(sgp->vmaddr + sgp->vmsize);
/*
* Round lowpc and highpc to multiples of the density we're using
* so the rest of the scaling (here and in gprof) stays in ints.
*/
p->lowpc = ROUNDDOWN(p->lowpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->highpc = ROUNDUP(p->highpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->textsize = p->highpc - p->lowpc;
printf("Profiling kernel, textsize=%lu [0x%016lx..0x%016lx]\n",
p->textsize, p->lowpc, p->highpc);
p->kcountsize = p->textsize / HISTFRACTION;
p->hashfraction = HASHFRACTION;
p->fromssize = p->textsize / HASHFRACTION;
p->tolimit = p->textsize * ARCDENSITY / 100;
if (p->tolimit < MINARCS)
p->tolimit = MINARCS;
else if (p->tolimit > MAXARCS)
p->tolimit = MAXARCS;
p->tossize = p->tolimit * sizeof(tostruct_t);
/* Why not use MALLOC with M_GPROF ? */
cp = (tostruct_t *)kalloc(p->kcountsize + p->fromssize + p->tossize);
if (cp == 0) {
printf("No memory for profiling.\n");
return;
}
bzero(cp, p->kcountsize + p->tossize + p->fromssize);
p->tos = cp;
cp = (tostruct_t *)((vm_offset_t)cp + p->tossize);
p->kcount = (u_short *)cp;
cp = (tostruct_t *)((vm_offset_t)cp + p->kcountsize);
p->froms = (u_short *)cp;
mcount_lock_grp = lck_grp_alloc_init("MCOUNT", LCK_GRP_ATTR_NULL);
mcount_lock_attr = lck_attr_alloc_init();
mcount_lock = lck_spin_alloc_init(mcount_lock_grp, mcount_lock_attr);
}
/*
* XXX These should be broken out into per-argument OID values,
* XXX since there are no sub-OID parameter values, but unfortunately
* XXX there is barely enough time for an initial conversion.
*
* Note: These items appear to be read/write.
*/
STATIC int
sysctl_doprofhandle SYSCTL_HANDLER_ARGS
{
sysctl_doprof(int *name, u_int namelen, user_addr_t oldp, size_t *oldlenp,
user_addr_t newp, size_t newlen)
{
__unused int cmd = oidp->oid_arg2; /* subcommand*/
int *name = arg1; /* oid element argument vector */
int namelen = arg2; /* number of oid element arguments */
user_addr_t oldp = req->oldptr; /* user buffer copy out address */
size_t *oldlenp = req->oldlen; /* user buffer copy out size */
user_addr_t newp = req->newptr; /* user buffer copy in address */
size_t newlen = req->newlen; /* user buffer copy in size */
struct gmonparam *gp = &_gmonparam;
int error = 0;
/* all sysctl names at this level are terminal */
if (namelen != 1)
return (ENOTDIR); /* overloaded */
switch (name[0]) {
case GPROF_STATE:
error = sysctl_int(oldp, oldlenp, newp, newlen, &gp->state);
if (error)
break;
if (gp->state == GMON_PROF_OFF)
stopprofclock(kernproc);
else
startprofclock(kernproc);
break;
case GPROF_COUNT:
error = sysctl_struct(oldp, oldlenp, newp, newlen,
gp->kcount, gp->kcountsize);
break;
case GPROF_FROMS:
error = sysctl_struct(oldp, oldlenp, newp, newlen,
gp->froms, gp->fromssize);
break;
case GPROF_TOS:
error = sysctl_struct(oldp, oldlenp, newp, newlen,
gp->tos, gp->tossize);
break;
case GPROF_GMONPARAM:
error = sysctl_rdstruct(oldp, oldlenp, newp, gp, sizeof *gp);
break;
default:
error = ENOTSUP;
break;
}
/* adjust index so we return the right required/consumed amount */
if (!error)
req->oldidx += req->oldlen;
return(error);
}
SYSCTL_PROC(_kern, KERN_PROF, prof, STLFLAG_NODE|CTLFLAG_RW | CTLFLAG_LOCKED,
0, /* Pointer argument (arg1) */
0, /* Integer argument (arg2) */
sysctl_doprofhandle, /* Handler function */
NULL, /* No explicit data */
"");
/*
* mcount() called with interrupts disabled.
*/
void
mcount(
uintptr_t frompc,
uintptr_t selfpc
)
{
unsigned short *frompcindex;
tostruct_t *top, *prevtop;
struct gmonparam *p = &_gmonparam;
long toindex;
/*
* check that we are profiling
* and that we aren't recursively invoked.
*/
if (p->state != GMON_PROF_ON)
return;
lck_spin_lock(mcount_lock);
/*
* check that frompcindex is a reasonable pc value.
* for example: signal catchers get called from the stack,
* not from text space. too bad.
*/
frompc -= p->lowpc;
if (frompc > p->textsize)
goto done;
frompcindex = &p->froms[frompc / (p->hashfraction * sizeof(*p->froms))];
toindex = *frompcindex;
if (toindex == 0) {
/*
* first time traversing this arc
*/
toindex = ++p->tos[0].link;
if (toindex >= p->tolimit) {
/* halt further profiling */
goto overflow;
}
*frompcindex = toindex;
top = &p->tos[toindex];
top->selfpc = selfpc;
top->count = 1;
top->link = 0;
goto done;
}
top = &p->tos[toindex];
if (top->selfpc == selfpc) {
/*
* arc at front of chain; usual case.
*/
top->count++;
goto done;
}
/*
* have to go looking down chain for it.
* top points to what we are looking at,
* prevtop points to previous top.
* we know it is not at the head of the chain.
*/
for (; /* goto done */; ) {
if (top->link == 0) {
/*
* top is end of the chain and none of the chain
* had top->selfpc == selfpc.
* so we allocate a new tostruct
* and link it to the head of the chain.
*/
toindex = ++p->tos[0].link;
if (toindex >= p->tolimit) {
goto overflow;
}
top = &p->tos[toindex];
top->selfpc = selfpc;
top->count = 1;
top->link = *frompcindex;
*frompcindex = toindex;
goto done;
}
/*
* otherwise, check the next arc on the chain.
*/
prevtop = top;
top = &p->tos[top->link];
if (top->selfpc == selfpc) {
/*
* there it is.
* increment its count
* move it to the head of the chain.
*/
top->count++;
toindex = prevtop->link;
prevtop->link = top->link;
top->link = *frompcindex;
*frompcindex = toindex;
goto done;
}
}
done:
lck_spin_unlock(mcount_lock);
return;
overflow:
p->state = GMON_PROF_ERROR;
lck_spin_unlock(mcount_lock);
printf("mcount: tos overflow\n");
return;
}
#endif /* GPROF */
#define PROFILE_LOCK(x)
#define PROFILE_UNLOCK(x)
/*
* Scale is a fixed-point number with the binary point 16 bits
* into the value, and is <= 1.0. pc is at most 32 bits, so the
* intermediate result is at most 48 bits.
*/
//K64todo - this doesn't fit into 64 bit any more, it needs 64+16
#define PC_TO_INDEX(pc, prof) \
((user_addr_t)(((u_quad_t)((pc) - (prof)->pr_off) * \
(u_quad_t)((prof)->pr_scale)) >> 16) & ~1)
/*
* Collect user-level profiling statistics; called on a profiling tick,
* when a process is running in user-mode. We use
* an AST that will vector us to trap() with a context in which copyin
* and copyout will work. Trap will then call addupc_task().
*
* Note that we may (rarely) not get around to the AST soon enough, and
* lose profile ticks when the next tick overwrites this one, but in this
* case the system is overloaded and the profile is probably already
* inaccurate.
*
* We can afford to take faults here. If the
* update fails, we simply turn off profiling.
*/
void
addupc_task(struct proc *p, user_addr_t pc, u_int ticks)
{
user_addr_t off;
u_short count;
/* Testing P_PROFIL may be unnecessary, but is certainly safe. */
if ((p->p_flag & P_PROFIL) == 0 || ticks == 0)
return;
if (proc_is64bit(p)) {
struct user_uprof *prof;
user_addr_t cell;
for (prof = &p->p_stats->user_p_prof; prof; prof = prof->pr_next) {
off = PC_TO_INDEX(pc, prof);
cell = (prof->pr_base + off);
if (cell >= prof->pr_base &&
cell < (prof->pr_size + prof->pr_base)) {
if (copyin(cell, (caddr_t) &count, sizeof(count)) == 0) {
count += ticks;
if(copyout((caddr_t) &count, cell, sizeof(count)) == 0)
return;
}
p->p_stats->user_p_prof.pr_scale = 0;
stopprofclock(p);
break;
}
}
}
else {
struct uprof *prof;
short *cell;
for (prof = &p->p_stats->p_prof; prof; prof = prof->pr_next) {
off = PC_TO_INDEX(pc,prof);
cell = (short *)(prof->pr_base + off);
if (cell >= (short *)prof->pr_base &&
cell < (short*)(prof->pr_size + prof->pr_base)) {
if (copyin(CAST_USER_ADDR_T(cell), (caddr_t) &count, sizeof(count)) == 0) {
count += ticks;
if(copyout((caddr_t) &count, CAST_USER_ADDR_T(cell), sizeof(count)) == 0)
return;
}
p->p_stats->p_prof.pr_scale = 0;
stopprofclock(p);
break;
}
}
}
}
| {
"pile_set_name": "Github"
} |
/* Not needed. */
| {
"pile_set_name": "Github"
} |
module.exports = require('@bugsnag/browser')
| {
"pile_set_name": "Github"
} |
# Выпуск №98
11 декабря 2017: Декодинг картинок, анимация и авторизация в браузерах, Webpack или Parcel, устаревший GIF и всё, что вы хотели знать про Smashing Magazine.
- Виталий Фридман
- Вадим Макеев
- Алексей Симоненко
## Содержание
- 00:04:19 События
- 00:23:16 Новинки браузеров
- 00:53:28 Webpack или Parcel
- 01:16:46 GIF устарел
- 01:26:30 Smashing Magazine
Слушайте: [Google Podcasts](https://podcasts.google.com/?feed=aHR0cHM6Ly93ZWItc3RhbmRhcmRzLnJ1L3BvZGNhc3QvZmVlZC8), [Apple Podcasts](https://podcasts.apple.com/podcast/id1080500016), [ВКонтакте](https://vk.com/podcasts-32017543), [Яндекс.Музыка](https://music.yandex.ru/album/6245956), [Spotify](https://open.spotify.com/show/3rzAcADjpBpXt73L0epTjV), [YouTube](https://www.youtube.com/playlist?list=PLMBnwIwFEFHcwuevhsNXkFTcadeX5R1Go), [SoundCloud](https://soundcloud.com/web-standards), [RSS](https://web-standards.ru/podcast/feed/).
Читайте: [Твиттер](https://twitter.com/webstandards_ru), [ВКонтакте](https://vk.com/webstandards_ru), [Фейсбук](https://www.facebook.com/webstandardsru), [Телеграм](https://t.me/webstandards_ru).
Поддержите: [Патреон](https://www.patreon.com/webstandards_ru), [Яндекс.Деньги](https://money.yandex.ru/to/41001119329753), [PayPal](https://www.paypal.me/pepelsbey).
[Обсуждайте в Слаке](http://slack.web-standards.ru/).
## События
- [HolyJS в Москве 10–11 декабря](https://holyjs-moscow.ru)
- [Pitercss_meetup №17 в Питере 20 декабря](https://pitercss.timepad.ru/event/627086/)
- [MinskJS Meetup 3 в Минске 25 января](http://minskjs.by/)
- [WSD в Москве 3 февраля](https://wsd.events/2018/02/03/)
- [Rolling Scopes в Минске 10–11 февраля](https://2018.conf.rollingscopes.com/)
- [Smashing Conf](https://smashingconf.com/)
## Новинки браузеров
- [Safari TP 45](https://webkit.org/blog/8039/release-notes-for-safari-technology-preview-45/)
- [Chrome 63](https://developers.google.com/web/updates/2017/12/nic63)
- [Intent to Ship: image decoding attribute](https://groups.google.com/a/chromium.org/d/msg/Blink-dev/MbXp16hQclY/bQjegyrbAgAJ)
- [Chrome 65 adding Web Animations API implementation](https://twitter.com/dancwilson/status/938138635953692672)
- [Intent to Ship: Web Authentication](https://groups.google.com/d/msg/mozilla.dev.platform/tsevyqfBHLE/lccldWNNBwAJ)
## Webpack или Parcel
- [Webpack 4.0.0-alpha.0](https://github.com/webpack/webpack/issues/6064)
- [Parcel](https://parceljs.org)
## GIF устарел
- [Эволюция `<img>` Gif без формата GIF](https://habr.ru/p/343958/)
- [Debugging Grid Layouts With Firefox Grid Inspector](https://www.smashingmagazine.com/2017/12/grid-inspector/)
## Smashing Magazine
- [Илья Пухальский](https://twitter.com/pukhalski)
- [Виталий Фридман](https://twitter.com/smashingmag)
| {
"pile_set_name": "Github"
} |
#' @importFrom insight get_parameters
#' @importFrom stats confint
.ci_profiled <- function(model, ci) {
glm_ci <- tryCatch(
{
out <- as.data.frame(stats::confint(model, level = ci), stringsAsFactors = FALSE)
names(out) <- c("CI_low", "CI_high")
out$CI <- ci * 100
out$Parameter <- insight::get_parameters(model, effects = "fixed", component = "conditional")$Parameter
out <- out[c("Parameter", "CI", "CI_low", "CI_high")]
rownames(out) <- NULL
out
},
error = function(e) {
NULL
}
)
if (is.null(glm_ci)) {
glm_ci <- ci_wald(model, ci = ci)
}
glm_ci
}
# we need this function for models where confint and get_parameters return
# different length (e.g. as for "polr" models)
#' @importFrom stats confint
.ci_profiled2 <- function(model, ci) {
glm_ci <- tryCatch(
{
out <- as.data.frame(stats::confint(model, level = ci), stringsAsFactors = FALSE)
names(out) <- c("CI_low", "CI_high")
out$CI <- ci * 100
out$Parameter <- .remove_backticks_from_string(rownames(out))
out <- out[c("Parameter", "CI", "CI_low", "CI_high")]
rownames(out) <- NULL
out
},
error = function(e) {
NULL
}
)
if (is.null(glm_ci)) {
glm_ci <- ci_wald(model, ci = ci)
}
glm_ci
}
#' @keywords internal
.ci_boot_merMod <- function(x, ci, ...) {
if (!requireNamespace("lme4", quietly = TRUE)) {
stop("Package 'lme4' required for this function to work. Please install it by running `install.packages('lme4')`.")
}
# Compute
out <- as.data.frame(lme4::confint.merMod(x, level = ci, method = "boot", ...))
rownames(out) <- gsub("`", "", rownames(out), fixed = TRUE)
out <- out[rownames(out) %in% insight::find_parameters(x, effects = "fixed")$conditional, ]
names(out) <- c("CI_low", "CI_high")
# Clean up
out$Parameter <- row.names(out)
out$CI <- ci
out <- out[c("Parameter", "CI", "CI_low", "CI_high")]
row.names(out) <- NULL
out
}
| {
"pile_set_name": "Github"
} |
# frozen_string_literal: true
require "test_helper"
describe Committee::Drivers::HyperSchema::Link do
before do
@hyper_schema_link = JsonSchema::Schema::Link.new
@hyper_schema_link.enc_type = "application/x-www-form-urlencoded"
@hyper_schema_link.href = "/apps"
@hyper_schema_link.media_type = "application/json"
@hyper_schema_link.method = "GET"
@hyper_schema_link.parent = { "title" => "parent" }
@hyper_schema_link.rel = "instances"
@hyper_schema_link.schema = { "title" => "input" }
@hyper_schema_link.target_schema = { "title" => "target" }
@link = Committee::Drivers::HyperSchema::Link.new(@hyper_schema_link)
end
it "proxies #enc_type" do
assert_equal "application/x-www-form-urlencoded", @link.enc_type
end
it "proxies #href" do
assert_equal "/apps", @link.href
end
it "proxies #media_type" do
assert_equal "application/json", @link.media_type
end
it "proxies #method" do
assert_equal "GET", @link.method
end
it "proxies #rel" do
assert_equal "instances", @link.rel
end
it "proxies #schema" do
assert_equal @hyper_schema_link.schema, @link.schema
end
it "generates 200 #status_success for non-create" do
assert_equal 200, @link.status_success
end
it "generates 201 #status_success for create" do
@hyper_schema_link.rel = "create"
assert_equal 201, @link.status_success
end
it "proxies #target_schema" do
assert_equal @hyper_schema_link.target_schema, @link.target_schema
end
end
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2015, Cisco Systems
// All rights reserved.
//
// 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 of the copyright holder 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 HOLDER 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.
// This file is autogenerated
//
// The following edits are possible, without affecting the validity of the
// file:
//
// * Fields may be renamed.
// * Fields may be deleted.
// * The unique numbered tag for a field may be changed, provided that
// the ordering of tags for fields within a message is preserved.
// * Message types may be renamed.
// * Message types may be deleted (if all fields that reference them
// have been deleted).
//
// All Cisco message and field extensions must be preserved (except when the
// field itself is being deleted).
syntax = "proto3";
package cisco_ios_xr_ip_rsvp_oper.rsvp.request_details.request_detail;
// Detailed Form of RSVP Request Info
message rsvp_mgmt_request_detail_KEYS {
string destination_address = 1;
uint32 destination_port = 2;
uint32 protocol = 3;
string extended_tunnel_id = 4;
string session_type = 5;
uint32 p2_mp_id = 6;
string source_address = 7;
uint32 source_port = 8;
string sub_group_origin = 9;
uint32 sub_group_id = 10;
string vrf_name = 11;
}
message rsvp_mgmt_request_detail {
// RSVP Session Information
rsvp_mgmt_session_info session = 50;
// RSVP S2L Sub-LSP information
rsvp_mgmt_s2l_sub_lsp_ipv4 s2_l_sub_lsp = 51;
// Flow Spec Information
rsvp_mgmt_flow_spec flow_spec = 52;
// Generic Flow Spec Information
rsvp_mgmt_gen_flow_spec generic_flow_spec = 53;
// RSVP Filter
rsvp_mgmt_filter_info filter = 54;
// RSVP Style
rsvp_mgmt_style style = 55;
// output Interface
string output_interface = 56;
// Request flags
rsvp_mgmt_request_flags req_flags = 57;
// Hop Infomation
rsvp_mgmt_hop_info hop = 58;
// RSVP Header Information
rsvp_mgmt_header_info header = 59;
// RSVP Policy Sources
rsvp_mgmt_policy_sources policy_sources = 60;
// RSVP Policy Flags
rsvp_mgmt_policy_flags policy_flags = 61;
// RSVP Query Flags
rsvp_mgmt_policy_query_flags policy_query_flags = 62;
// List of RSB keys
repeated rsvp_mgmt_key psb_keys = 63;
// List of RSB keys
repeated rsvp_mgmt_key rsb_keys = 64;
}
// RSVP S2L Sub-LSP
message rsvp_mgmt_s2l_sub_lsp_ipv4 {
// S2L Sub-LSP Destination Address
string s2_l_destination_address = 1;
}
// RSVP Filter
message rsvp_mgmt_filter_ipv4 {
// Source Address
string source_address = 1;
// Source Port
uint32 source_port = 2;
}
// RSVP P2MP IPv4 FilterSpec
message rsvp_mgmt_filter_p2mp_ipv4 {
// Source Address
string source_address = 1;
// Source Port
uint32 source_port = 2;
// Point to Multipoint SubGroup Origin
string p2_mp_sub_group_origin = 3;
// Point to Multipoint Subgroup ID
uint32 sub_group_id = 4;
}
// Union of the different RSVP filterspec types
message rsvp_filter_union {
string filter_type = 1;
// UDP IPV4 FilterSpec
rsvp_mgmt_filter_ipv4 udp_ipv4_session = 2;
// IPv4 P2MP LSP FilterSpec
rsvp_mgmt_filter_p2mp_ipv4 p2_mp_ipv4_session = 3;
}
// RSVP FilterSpec Info
message rsvp_mgmt_filter_info {
// RSVP Filter
rsvp_filter_union rsvp_filter = 1;
}
// RSVP UDP IPv4 Session
message rsvp_mgmt_session_udp_ipv4 {
// Destination address
string destination_address = 1;
// Protocol type (originally defined in RFC 790, further values in subsequent RFCs)
uint32 protocol = 2;
// The Session Destination Port
uint32 destination_port = 3;
}
// RSVP LSP-Tunnel-IPv4 Session
message rsvp_mgmt_session_lsp_tunnel_ipv4 {
// Destination address
string destination_address = 1;
// The Session Tunnel ID
uint32 tunnel_id = 2;
// The Session Extended Tunnel ID
string extended_tunnel_id = 3;
}
// RSVP UNI IPv4 Session
message rsvp_mgmt_session_uni_ipv4 {
// Destination address
string destination_address = 1;
// The Session Tunnel ID
uint32 tunnel_id = 2;
// The Session Extended Address
string extended_address = 3;
}
// RSVP P2MP-LSP-Tunnel-IPv4 Session
message rsvp_mgmt_session_p2mp_lsp_tunnel_ipv4 {
// The Point to Multipoint ID
uint32 p2_mp_id = 1;
// The Session Tunnel ID
uint32 tunnel_id = 2;
// The Session Extended Tunnel ID
string extended_tunnel_id = 3;
}
// Union of the different RSVP session types
message rsvp_session_union {
string session_type = 1;
// UDP IPv4 session
rsvp_mgmt_session_udp_ipv4 ipv4 = 2;
// IPv4 LSP session
rsvp_mgmt_session_lsp_tunnel_ipv4 ipv4_lsp_session = 3;
// IPv4 UNI session
rsvp_mgmt_session_uni_ipv4 ipv4_uni_session = 4;
// IPv4 P2MP LSP session
rsvp_mgmt_session_p2mp_lsp_tunnel_ipv4 ipv4_p2_mp_lsp_session = 5;
}
// RSVP Session Info
message rsvp_mgmt_session_info {
// RSVP Session
rsvp_session_union rsvp_session = 1;
}
// RSVP Reservation Style
message rsvp_mgmt_style {
// The Reservation Type: WF, SE or FF
string reservation_type = 1;
}
// RSVP Policy Sources
message rsvp_mgmt_policy_sources {
// Policy Source is TE Link
bool is_te_link = 1;
// Policy Source is Local
bool is_local = 2;
// Policy Source is COPS
bool is_cops = 3;
// Policy Source is Default
bool is_default = 4;
// Policy Source is Cable
bool is_cable = 5;
}
// RSVP Policy Flags
message rsvp_mgmt_policy_flags {
// Accepted
bool is_accepted = 1;
// Installed
bool is_installed = 2;
// Forwarding
bool is_forwarding = 3;
}
// Key to uniquely identify some RSVP records
message rsvp_mgmt_key {
// Point-to-multipoint ID
uint32 p2_mp_id = 1;
// Destination address
string destination_address = 2;
// Destination Port or Tunnel ID. For the LSP and OUNI session types this represents the Tunnel ID whereas for the UDP session type this represents the Destination Port
uint32 destination_port_or_tunnel_id = 3;
// Protocol. UDP session type this represents the Protocol (UDP not supported at present)
uint32 protocol = 4;
// Protocol or Extended Tunnel ID. For the LSP and OUNI sesion types this represents the Extended Tunnel ID
string extended_tunnel_id = 5;
// Session Type (e.g. LSP, OUNI or UDP)
string session_type = 6;
// Source Address
string source_address = 7;
// Source Port or LSP_ID. For the LSP and OUNI session types this represents the LSP_ID whereas for the UDP session type this represents the SourcePort
uint32 source_port_or_lsp_id = 8;
// Point to Multipoint SubGroup Origin
string p2_mp_sub_group_origin = 9;
// Point to Multipoint Subgroup ID
uint32 sub_group_id = 10;
// Signalling VRF ID
uint32 vrfid = 11;
}
// RSVP Policy Query Flags
message rsvp_mgmt_policy_query_flags {
// Needed
bool is_needed = 1;
// Report Required
bool is_report_required = 2;
// Resynchronization
bool is_resync = 3;
// Bypass
bool is_bypass = 4;
}
// RSVP Flow Spec
message rsvp_mgmt_flow_spec {
// The Flow Average Rate in bytes per second
uint64 flow_average_rate = 1;
// The Flow Maximum Burst
uint64 flow_max_burst = 2;
// The Flow Peak Rate in bytes per second
uint64 flow_peak_rate = 3;
// The Flow Minimum Unit
uint32 flow_min_unit = 4;
// The Flow Maximum Unit
uint32 flow_max_unit = 5;
// The Flow Requested Rate in bytes per second
uint64 flow_requested_rate = 6;
// The Flow Slack
uint32 flow_slack = 7;
// The Flow Quality of Service
string flow_qos = 8;
}
// RSVP G709 OTN FlowSpec Info
message rsvp_mgmt_flow_spec_g709_otn {
// G709 OTN Flow Signal Type (Refer G709 v3)
uint32 flow_signal_type = 1;
// G709 OTN Flow NVC
uint32 flow_nvc = 2;
// G709 OTN Flow Multiplier
uint32 flow_multiplier = 3;
// G709 OTN Flow Bit Rate
uint64 flow_bit_rate = 4;
}
// Union of different RSVP Generic FlowSpec types
message rsvp_mgmt_gen_flow_spec {
string flow_spec_type = 1;
// G709 OTN FlowSpec
rsvp_mgmt_flow_spec_g709_otn g709_otn_flow_spec = 2;
}
// Hop Info
message rsvp_mgmt_hop_info {
// IP address of the neighbor
string neighbor_address = 1;
// Neighbor Logical Interface Name
string neighbor_logical_interface_name = 2;
}
// RSVP/IP Header Info
message rsvp_mgmt_header_info {
// RSVP Version
uint32 rsvp_version = 1;
// RSVP Header Flags (defined in RFC2205 Section 3.1.1)
uint32 rsvp_header_flags = 2;
// RSVP TTL
uint32 rsvp_ttl = 3;
// RSVP Message Type
uint32 rsvp_message_type = 4;
// IP Type of Service
uint32 ip_tos = 5;
// IP TTL
uint32 ip_ttl = 6;
// IP Source Address
string ip_source_address = 7;
}
// Request state flags
message rsvp_mgmt_request_flags {
// Local Receiver
bool is_local_receiver = 1;
// Is neighbor refreshing
bool is_refreshing = 2;
// Send Confirm message
bool is_send_confirm = 3;
// Is ACK message outstanding
bool is_ack_outstanding = 4;
// Is MessageID allocated
bool is_message_id_allocated = 5;
// A NACK message was received
bool is_nack_received = 6;
// Retransmit the message
bool is_retransmit = 7;
// Message is paced
bool is_paced = 8;
// The Path message contains Label Request
bool is_label_request_in_path = 9;
// The Path message contains RRO
bool is_rro_in_path = 10;
// Path has Session-Attr object with Record Labels set
bool is_record_label_in_path = 11;
// Is node a Merge Point
bool is_merge_point = 12;
}
| {
"pile_set_name": "Github"
} |
# GStreamer core libraries API
| {
"pile_set_name": "Github"
} |
package sdk_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/ovh/cds/sdk"
)
func TestWorkflowRunTag(t *testing.T) {
a := sdk.Action{
Enabled: true,
Requirements: sdk.RequirementList{
{Type: sdk.ModelRequirement, Value: "model1"},
{Type: sdk.ServiceRequirement, Value: "service1"},
},
Actions: []sdk.Action{{
Enabled: true,
Requirements: sdk.RequirementList{
{Type: sdk.HostnameRequirement, Value: "hostname1"},
{Type: sdk.ServiceRequirement, Value: "service2"},
},
}, {
Enabled: false,
Requirements: sdk.RequirementList{
{Type: sdk.ServiceRequirement, Value: "service3"},
},
}},
}
rs := a.FlattenRequirements()
assert.Equal(t, 4, len(rs))
assert.Equal(t, "model1", rs[0].Value)
assert.Equal(t, "service1", rs[1].Value)
assert.Equal(t, "hostname1", rs[2].Value)
assert.Equal(t, "service2", rs[3].Value)
}
| {
"pile_set_name": "Github"
} |
Version 2009-08-22
===========================
FREE USB-IDs FOR SHARED USE
===========================
Objective Development has reserved a set of USB Product-IDs for use according
to the guidelines outlined below. For more information about the concept of
USB IDs please see the file USB-ID-FAQ.txt. Objective Development guarantees
that the IDs listed below are not used by any USB compliant devices.
====================
MECHANISM OF SHARING
====================
From a technical point of view, two different devices can share the same USB
Vendor- and Product-ID if they require the same driver on operating system
level. We make use of this fact by assigning separate IDs for various device
classes. On application layer, devices must be distinguished by their textual
name or serial number. We offer separate sets of IDs for discrimination by
textual name and for serial number.
Examples for shared use of USB IDs are included with V-USB in the "examples"
subdirectory.
======================================
IDs FOR DISCRIMINATION BY TEXTUAL NAME
======================================
If you use one of the IDs listed below, your device and host-side software
must conform to these rules:
(1) The USB device MUST provide a textual representation of the manufacturer
and product identification. The manufacturer identification MUST be available
at least in USB language 0x0409 (English/US).
(2) The textual manufacturer identification MUST contain either an Internet
domain name (e.g. "mycompany.com") registered and owned by you, or an e-mail
address under your control (e.g. "[email protected]"). You can embed the domain
name or e-mail address in any string you like, e.g. "Objective Development
http://www.obdev.at/vusb/".
(3) You are responsible for retaining ownership of the domain or e-mail
address for as long as any of your products are in use.
(4) You may choose any string for the textual product identification, as long
as this string is unique within the scope of your textual manufacturer
identification.
(5) Application side device look-up MUST be based on the textual manufacturer
and product identification in addition to VID/PID matching. The driver
matching MUST be a comparison of the entire strings, NOT a sub-string match.
(6) For devices which implement a particular USB device class (e.g. HID), the
operating system's default class driver MUST be used. If an operating system
driver for Vendor Class devices is needed, this driver must be libusb or
libusb-win32 (see http://libusb.org/ and
http://libusb-win32.sourceforge.net/).
Table if IDs for discrimination by textual name:
PID dec (hex) | VID dec (hex) | Description of use
==============+===============+============================================
1500 (0x05dc) | 5824 (0x16c0) | For Vendor Class devices with libusb
--------------+---------------+--------------------------------------------
1503 (0x05df) | 5824 (0x16c0) | For generic HID class devices (which are
| | NOT mice, keyboards or joysticks)
--------------+---------------+--------------------------------------------
1505 (0x05e1) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
--------------+---------------+--------------------------------------------
1508 (0x05e4) | 5824 (0x16c0) | For MIDI class devices
--------------+---------------+--------------------------------------------
Note that Windows caches the textual product- and vendor-description for
mice, keyboards and joysticks. Name-bsed discrimination is therefore not
recommended for these device classes.
=======================================
IDs FOR DISCRIMINATION BY SERIAL NUMBER
=======================================
If you use one of the IDs listed below, your device and host-side software
must conform to these rules:
(1) The USB device MUST provide a textual representation of the serial
number, unless ONLY the operating system's default class driver is used.
The serial number string MUST be available at least in USB language 0x0409
(English/US).
(2) The serial number MUST start with either an Internet domain name (e.g.
"mycompany.com") registered and owned by you, or an e-mail address under your
control (e.g. "[email protected]"), both terminated with a colon (":") character.
You MAY append any string you like for further discrimination of your devices.
(3) You are responsible for retaining ownership of the domain or e-mail
address for as long as any of your products are in use.
(5) Application side device look-up MUST be based on the serial number string
in addition to VID/PID matching. The matching must start at the first
character of the serial number string and include the colon character
terminating your domain or e-mail address. It MAY stop anywhere after that.
(6) For devices which implement a particular USB device class (e.g. HID), the
operating system's default class driver MUST be used. If an operating system
driver for Vendor Class devices is needed, this driver must be libusb or
libusb-win32 (see http://libusb.org/ and
http://libusb-win32.sourceforge.net/).
(7) If ONLY the operating system's default class driver is used, e.g. for
mice, keyboards, joysticks, CDC or MIDI devices and no discrimination by an
application is needed, the serial number may be omitted.
Table if IDs for discrimination by serial number string:
PID dec (hex) | VID dec (hex) | Description of use
===============+===============+===========================================
10200 (0x27d8) | 5824 (0x16c0) | For Vendor Class devices with libusb
---------------+---------------+-------------------------------------------
10201 (0x27d9) | 5824 (0x16c0) | For generic HID class devices (which are
| | NOT mice, keyboards or joysticks)
---------------+---------------+-------------------------------------------
10202 (0x27da) | 5824 (0x16c0) | For USB Mice
---------------+---------------+-------------------------------------------
10203 (0x27db) | 5824 (0x16c0) | For USB Keyboards
---------------+---------------+-------------------------------------------
10204 (0x27dc) | 5824 (0x16c0) | For USB Joysticks
---------------+---------------+-------------------------------------------
10205 (0x27dd) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
---------------+---------------+-------------------------------------------
10206 (0x27de) | 5824 (0x16c0) | For MIDI class devices
---------------+---------------+-------------------------------------------
=================
ORIGIN OF USB-IDs
=================
OBJECTIVE DEVELOPMENT Software GmbH has obtained all VID/PID pairs listed
here from Wouter van Ooijen (see www.voti.nl) for exclusive disposition.
Wouter van Ooijen has obtained the VID from the USB Implementers Forum, Inc.
(see www.usb.org). The VID is registered for the company name "Van Ooijen
Technische Informatica".
==========
DISCLAIMER
==========
OBJECTIVE DEVELOPMENT Software GmbH disclaims all liability for any
problems which are caused by the shared use of these VID/PID pairs.
| {
"pile_set_name": "Github"
} |
/* -----------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android
© Copyright 1995 - 2018 Fraunhofer-Gesellschaft zur Förderung der angewandten
Forschung e.V. All rights reserved.
1. INTRODUCTION
The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
scheme for digital audio. This FDK AAC Codec software is intended to be used on
a wide variety of Android devices.
AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
general perceptual audio codecs. AAC-ELD is considered the best-performing
full-bandwidth communications codec by independent studies and is widely
deployed. AAC has been standardized by ISO and IEC as part of the MPEG
specifications.
Patent licenses for necessary patent claims for the FDK AAC Codec (including
those of Fraunhofer) may be obtained through Via Licensing
(www.vialicensing.com) or through the respective patent owners individually for
the purpose of encoding or decoding bit streams in products that are compliant
with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
Android devices already license these patent claims through Via Licensing or
directly from the patent owners, and therefore FDK AAC Codec software may
already be covered under those patent licenses when it is used for those
licensed purposes only.
Commercially-licensed AAC software libraries, including floating-point versions
with enhanced sound quality, are also available from Fraunhofer. Users are
encouraged to check the Fraunhofer website for additional applications
information and documentation.
2. COPYRIGHT LICENSE
Redistribution and use in source and binary forms, with or without modification,
are permitted without payment of copyright license fees provided that you
satisfy the following conditions:
You must retain the complete text of this software license in redistributions of
the FDK AAC Codec or your modifications thereto in source code form.
You must retain the complete text of this software license in the documentation
and/or other materials provided with redistributions of the FDK AAC Codec or
your modifications thereto in binary form. You must make available free of
charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.
The name of Fraunhofer may not be used to endorse or promote products derived
from this library without prior written permission.
You may not charge copyright license fees for anyone to use, copy or distribute
the FDK AAC Codec software or your modifications thereto.
Your modified versions of the FDK AAC Codec must carry prominent notices stating
that you changed the software and the date of any change. For modified versions
of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
AAC Codec Library for Android."
3. NO PATENT LICENSE
NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
Fraunhofer provides no warranty of patent non-infringement with respect to this
software.
You may use this FDK AAC Codec software or modifications thereto only for
purposes that are authorized by appropriate patent licenses.
4. DISCLAIMER
This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
including but not limited to the implied warranties of merchantability and
fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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), arising in any way out of the use of
this software, even if advised of the possibility of such damage.
5. CONTACT INFORMATION
Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany
www.iis.fraunhofer.de/amm
[email protected]
----------------------------------------------------------------------------- */
/************************* MPEG-D DRC decoder library **************************
Author(s): Bernhard Neugebauer
Description: MPEG-D DRC Decoder
*******************************************************************************/
#include "drcDec_reader.h"
#include "drcDec_gainDecoder.h"
#include "FDK_drcDecLib.h"
#include "drcDec_selectionProcess.h"
#include "drcDec_tools.h"
/* Decoder library info */
#define DRCDEC_LIB_VL0 2
#define DRCDEC_LIB_VL1 1
#define DRCDEC_LIB_VL2 0
#define DRCDEC_LIB_TITLE "MPEG-D DRC Decoder Lib"
#ifdef __ANDROID__
#define DRCDEC_LIB_BUILD_DATE ""
#define DRCDEC_LIB_BUILD_TIME ""
#else
#define DRCDEC_LIB_BUILD_DATE __DATE__
#define DRCDEC_LIB_BUILD_TIME __TIME__
#endif
typedef enum {
DRC_DEC_NOT_INITIALIZED = 0,
DRC_DEC_INITIALIZED,
DRC_DEC_NEW_GAIN_PAYLOAD,
DRC_DEC_INTERPOLATION_PREPARED
} DRC_DEC_STATUS;
struct s_drc_decoder {
DRC_DEC_CODEC_MODE codecMode;
DRC_DEC_FUNCTIONAL_RANGE functionalRange;
DRC_DEC_STATUS status;
/* handles of submodules */
HANDLE_DRC_GAIN_DECODER hGainDec;
HANDLE_DRC_SELECTION_PROCESS hSelectionProc;
int selProcInputDiff;
/* data structs */
UNI_DRC_CONFIG uniDrcConfig;
LOUDNESS_INFO_SET loudnessInfoSet;
UNI_DRC_GAIN uniDrcGain;
SEL_PROC_OUTPUT selProcOutput;
} DRC_DECODER;
static int isResetNeeded(HANDLE_DRC_DECODER hDrcDec,
const SEL_PROC_OUTPUT oldSelProcOutput) {
int i, resetNeeded = 0;
if (hDrcDec->selProcOutput.numSelectedDrcSets !=
oldSelProcOutput.numSelectedDrcSets) {
resetNeeded = 1;
} else {
for (i = 0; i < hDrcDec->selProcOutput.numSelectedDrcSets; i++) {
if (hDrcDec->selProcOutput.selectedDrcSetIds[i] !=
oldSelProcOutput.selectedDrcSetIds[i])
resetNeeded = 1;
if (hDrcDec->selProcOutput.selectedDownmixIds[i] !=
oldSelProcOutput.selectedDownmixIds[i])
resetNeeded = 1;
}
}
if (hDrcDec->selProcOutput.boost != oldSelProcOutput.boost) resetNeeded = 1;
if (hDrcDec->selProcOutput.compress != oldSelProcOutput.compress)
resetNeeded = 1;
/* Note: Changes in downmix matrix are not caught, as they don't affect the
* DRC gain decoder */
return resetNeeded;
}
static DRC_DEC_ERROR startSelectionProcess(HANDLE_DRC_DECODER hDrcDec) {
DRC_ERROR dErr = DE_OK;
DRCDEC_SELECTION_PROCESS_RETURN sErr = DRCDEC_SELECTION_PROCESS_NO_ERROR;
int uniDrcConfigHasChanged = 0;
SEL_PROC_OUTPUT oldSelProcOutput = hDrcDec->selProcOutput;
if (!hDrcDec->status) return DRC_DEC_NOT_READY;
if (hDrcDec->functionalRange & DRC_DEC_SELECTION) {
uniDrcConfigHasChanged = hDrcDec->uniDrcConfig.diff;
if (hDrcDec->uniDrcConfig.diff || hDrcDec->loudnessInfoSet.diff ||
hDrcDec->selProcInputDiff) {
/* in case of an error, signal that selection process was not successful
*/
hDrcDec->selProcOutput.numSelectedDrcSets = 0;
sErr = drcDec_SelectionProcess_Process(
hDrcDec->hSelectionProc, &(hDrcDec->uniDrcConfig),
&(hDrcDec->loudnessInfoSet), &(hDrcDec->selProcOutput));
if (sErr) return DRC_DEC_OK;
hDrcDec->selProcInputDiff = 0;
hDrcDec->uniDrcConfig.diff = 0;
hDrcDec->loudnessInfoSet.diff = 0;
}
}
if (hDrcDec->functionalRange & DRC_DEC_GAIN) {
if (isResetNeeded(hDrcDec, oldSelProcOutput) || uniDrcConfigHasChanged) {
dErr =
drcDec_GainDecoder_Config(hDrcDec->hGainDec, &(hDrcDec->uniDrcConfig),
hDrcDec->selProcOutput.numSelectedDrcSets,
hDrcDec->selProcOutput.selectedDrcSetIds,
hDrcDec->selProcOutput.selectedDownmixIds);
if (dErr) return DRC_DEC_OK;
}
}
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_Open(HANDLE_DRC_DECODER* phDrcDec,
const DRC_DEC_FUNCTIONAL_RANGE functionalRange) {
DRC_ERROR dErr = DE_OK;
DRCDEC_SELECTION_PROCESS_RETURN sErr = DRCDEC_SELECTION_PROCESS_NO_ERROR;
HANDLE_DRC_DECODER hDrcDec;
*phDrcDec = (HANDLE_DRC_DECODER)FDKcalloc(1, sizeof(DRC_DECODER));
if (!*phDrcDec) return DRC_DEC_OUT_OF_MEMORY;
hDrcDec = *phDrcDec;
hDrcDec->functionalRange = functionalRange;
hDrcDec->status = DRC_DEC_NOT_INITIALIZED;
hDrcDec->codecMode = DRC_DEC_CODEC_MODE_UNDEFINED;
if (hDrcDec->functionalRange & DRC_DEC_SELECTION) {
sErr = drcDec_SelectionProcess_Create(&(hDrcDec->hSelectionProc));
if (sErr) return DRC_DEC_OUT_OF_MEMORY;
sErr = drcDec_SelectionProcess_Init(hDrcDec->hSelectionProc);
if (sErr) return DRC_DEC_NOT_OK;
hDrcDec->selProcInputDiff = 1;
}
if (hDrcDec->functionalRange & DRC_DEC_GAIN) {
dErr = drcDec_GainDecoder_Open(&(hDrcDec->hGainDec));
if (dErr) return DRC_DEC_OUT_OF_MEMORY;
}
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_SetCodecMode(HANDLE_DRC_DECODER hDrcDec,
const DRC_DEC_CODEC_MODE codecMode) {
DRC_ERROR dErr = DE_OK;
DRCDEC_SELECTION_PROCESS_RETURN sErr = DRCDEC_SELECTION_PROCESS_NO_ERROR;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (hDrcDec->codecMode ==
DRC_DEC_CODEC_MODE_UNDEFINED) { /* Set codec mode, if it is set for the
first time */
hDrcDec->codecMode = codecMode;
if (hDrcDec->functionalRange & DRC_DEC_SELECTION) {
sErr = drcDec_SelectionProcess_SetCodecMode(
hDrcDec->hSelectionProc, (SEL_PROC_CODEC_MODE)codecMode);
if (sErr) return DRC_DEC_NOT_OK;
hDrcDec->selProcInputDiff = 1;
}
if (hDrcDec->functionalRange & DRC_DEC_GAIN) {
DELAY_MODE delayMode;
int timeDomainSupported;
SUBBAND_DOMAIN_MODE subbandDomainSupported;
switch (hDrcDec->codecMode) {
case DRC_DEC_MPEG_4_AAC:
case DRC_DEC_MPEG_D_USAC:
case DRC_DEC_MPEG_H_3DA:
default:
delayMode = DM_REGULAR_DELAY;
}
switch (hDrcDec->codecMode) {
case DRC_DEC_MPEG_4_AAC:
case DRC_DEC_MPEG_D_USAC:
timeDomainSupported = 1;
subbandDomainSupported = SDM_OFF;
break;
case DRC_DEC_MPEG_H_3DA:
timeDomainSupported = 1;
subbandDomainSupported = SDM_STFT256;
break;
case DRC_DEC_TEST_TIME_DOMAIN:
timeDomainSupported = 1;
subbandDomainSupported = SDM_OFF;
break;
case DRC_DEC_TEST_QMF_DOMAIN:
timeDomainSupported = 0;
subbandDomainSupported = SDM_QMF64;
break;
case DRC_DEC_TEST_STFT_DOMAIN:
timeDomainSupported = 0;
subbandDomainSupported = SDM_STFT256;
break;
default:
timeDomainSupported = 0;
subbandDomainSupported = SDM_OFF;
}
dErr = drcDec_GainDecoder_SetCodecDependentParameters(
hDrcDec->hGainDec, delayMode, timeDomainSupported,
subbandDomainSupported);
if (dErr) return DRC_DEC_NOT_OK;
}
}
/* Don't allow changing codecMode if it has already been set. */
if (hDrcDec->codecMode != codecMode) return DRC_DEC_NOT_OK;
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_Init(HANDLE_DRC_DECODER hDrcDec, const int frameSize,
const int sampleRate, const int baseChannelCount) {
DRC_ERROR dErr = DE_OK;
DRCDEC_SELECTION_PROCESS_RETURN sErr = DRCDEC_SELECTION_PROCESS_NO_ERROR;
if (hDrcDec == NULL || frameSize == 0 || sampleRate == 0 ||
baseChannelCount == 0)
return DRC_DEC_OK; /* return without doing anything */
if (hDrcDec->functionalRange & DRC_DEC_SELECTION) {
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_BASE_CHANNEL_COUNT,
(FIXP_DBL)baseChannelCount, &(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_NOT_OK;
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_SAMPLE_RATE, (FIXP_DBL)sampleRate,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_NOT_OK;
}
if (hDrcDec->functionalRange & DRC_DEC_GAIN) {
dErr = drcDec_GainDecoder_Init(hDrcDec->hGainDec, frameSize, sampleRate);
if (dErr) return DRC_DEC_NOT_OK;
}
hDrcDec->status = DRC_DEC_INITIALIZED;
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_Close(HANDLE_DRC_DECODER* phDrcDec) {
HANDLE_DRC_DECODER hDrcDec;
if (phDrcDec == NULL) {
return DRC_DEC_OK;
}
hDrcDec = *phDrcDec;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (hDrcDec->functionalRange & DRC_DEC_GAIN) {
drcDec_GainDecoder_Close(&(hDrcDec->hGainDec));
}
if (hDrcDec->functionalRange & DRC_DEC_SELECTION) {
drcDec_SelectionProcess_Delete(&(hDrcDec->hSelectionProc));
}
FDKfree(*phDrcDec);
*phDrcDec = NULL;
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_SetParam(HANDLE_DRC_DECODER hDrcDec,
const DRC_DEC_USERPARAM requestType,
const FIXP_DBL requestValue) {
DRCDEC_SELECTION_PROCESS_RETURN sErr = DRCDEC_SELECTION_PROCESS_NO_ERROR;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (hDrcDec->functionalRange == DRC_DEC_GAIN)
return DRC_DEC_NOT_OK; /* not supported for DRC_DEC_GAIN. All parameters are
handed over to selection process lib. */
switch (requestType) {
case DRC_DEC_BOOST:
sErr = drcDec_SelectionProcess_SetParam(hDrcDec->hSelectionProc,
SEL_PROC_BOOST, requestValue,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
case DRC_DEC_COMPRESS:
sErr = drcDec_SelectionProcess_SetParam(hDrcDec->hSelectionProc,
SEL_PROC_COMPRESS, requestValue,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
case DRC_DEC_LOUDNESS_NORMALIZATION_ON:
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_LOUDNESS_NORMALIZATION_ON,
requestValue, &(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
case DRC_DEC_TARGET_LOUDNESS:
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_TARGET_LOUDNESS, requestValue,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
case DRC_DEC_EFFECT_TYPE:
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_EFFECT_TYPE, requestValue,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
case DRC_DEC_DOWNMIX_ID:
sErr = drcDec_SelectionProcess_SetParam(hDrcDec->hSelectionProc,
SEL_PROC_DOWNMIX_ID, requestValue,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
case DRC_DEC_TARGET_CHANNEL_COUNT_REQUESTED:
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_TARGET_CHANNEL_COUNT, requestValue,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
case DRC_DEC_BASE_CHANNEL_COUNT:
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_BASE_CHANNEL_COUNT, requestValue,
&(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_NOT_OK;
break;
case DRC_DEC_LOUDNESS_MEASUREMENT_METHOD:
sErr = drcDec_SelectionProcess_SetParam(
hDrcDec->hSelectionProc, SEL_PROC_LOUDNESS_MEASUREMENT_METHOD,
requestValue, &(hDrcDec->selProcInputDiff));
if (sErr) return DRC_DEC_PARAM_OUT_OF_RANGE;
break;
default:
return DRC_DEC_INVALID_PARAM;
}
/* All parameters need a new start of the selection process */
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
LONG FDK_drcDec_GetParam(HANDLE_DRC_DECODER hDrcDec,
const DRC_DEC_USERPARAM requestType) {
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
switch (requestType) {
case DRC_DEC_BOOST:
return (LONG)hDrcDec->selProcOutput.boost;
case DRC_DEC_COMPRESS:
return (LONG)hDrcDec->selProcOutput.compress;
case DRC_DEC_IS_MULTIBAND_DRC_1:
return (LONG)bitstreamContainsMultibandDrc(&hDrcDec->uniDrcConfig, 0);
case DRC_DEC_IS_MULTIBAND_DRC_2:
return (LONG)bitstreamContainsMultibandDrc(&hDrcDec->uniDrcConfig, 0x7F);
case DRC_DEC_IS_ACTIVE: {
/* MPEG-D DRC is considered active (and overrides MPEG-4 DRC), if
* uniDrc payload is present (loudnessInfoSet and/or uniDrcConfig)
* at least one of DRC and Loudness Control is switched on */
int drcOn = drcDec_SelectionProcess_GetParam(
hDrcDec->hSelectionProc, SEL_PROC_DYNAMIC_RANGE_CONTROL_ON);
int lnOn = drcDec_SelectionProcess_GetParam(
hDrcDec->hSelectionProc, SEL_PROC_LOUDNESS_NORMALIZATION_ON);
int uniDrcPayloadPresent =
(hDrcDec->loudnessInfoSet.loudnessInfoCount > 0);
uniDrcPayloadPresent |=
(hDrcDec->loudnessInfoSet.loudnessInfoAlbumCount > 0);
uniDrcPayloadPresent |=
(hDrcDec->uniDrcConfig.drcInstructionsUniDrcCount > 0);
uniDrcPayloadPresent |=
(hDrcDec->uniDrcConfig.downmixInstructionsCount > 0);
return (LONG)(uniDrcPayloadPresent && (drcOn || lnOn));
}
case DRC_DEC_TARGET_CHANNEL_COUNT_SELECTED:
return (LONG)hDrcDec->selProcOutput.targetChannelCount;
default:
return 0;
}
}
DRC_DEC_ERROR
FDK_drcDec_SetInterfaceParameters(HANDLE_DRC_DECODER hDrcDec,
HANDLE_UNI_DRC_INTERFACE hUniDrcInterface) {
return DRC_DEC_UNSUPPORTED_FUNCTION;
}
DRC_DEC_ERROR
FDK_drcDec_SetSelectionProcessMpeghParameters_simple(
HANDLE_DRC_DECODER hDrcDec, const int groupPresetIdRequested,
const int numGroupIdsRequested, const int* groupIdsRequested) {
return DRC_DEC_UNSUPPORTED_FUNCTION;
}
DRC_DEC_ERROR
FDK_drcDec_SetDownmixInstructions(HANDLE_DRC_DECODER hDrcDec,
const int numDownmixId, const int* downmixId,
const int* targetLayout,
const int* targetChannelCount) {
return DRC_DEC_UNSUPPORTED_FUNCTION;
}
void FDK_drcDec_SetSelectionProcessOutput(
HANDLE_DRC_DECODER hDrcDec, HANDLE_SEL_PROC_OUTPUT hSelProcOutput) {}
HANDLE_SEL_PROC_OUTPUT
FDK_drcDec_GetSelectionProcessOutput(HANDLE_DRC_DECODER hDrcDec) {
if (hDrcDec == NULL) return NULL;
return &(hDrcDec->selProcOutput);
}
LONG /* FIXP_DBL, e = 7 */
FDK_drcDec_GetGroupLoudness(HANDLE_SEL_PROC_OUTPUT hSelProcOutput,
const int groupID, int* groupLoudnessAvailable) {
return (LONG)0;
}
void FDK_drcDec_SetChannelGains(HANDLE_DRC_DECODER hDrcDec,
const int numChannels, const int frameSize,
FIXP_DBL* channelGainDb, FIXP_DBL* audioBuffer,
const int audioBufferChannelOffset) {
int err;
if (hDrcDec == NULL) return;
err = drcDec_GainDecoder_SetLoudnessNormalizationGainDb(
hDrcDec->hGainDec, hDrcDec->selProcOutput.loudnessNormalizationGainDb);
if (err) return;
drcDec_GainDecoder_SetChannelGains(hDrcDec->hGainDec, numChannels, frameSize,
channelGainDb, audioBufferChannelOffset,
audioBuffer);
}
DRC_DEC_ERROR
FDK_drcDec_ReadUniDrcConfig(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (hDrcDec->codecMode == DRC_DEC_MPEG_D_USAC) {
dErr = drcDec_readUniDrcConfig(hBitstream, &(hDrcDec->uniDrcConfig));
} else
return DRC_DEC_NOT_OK;
if (dErr) {
/* clear config, if parsing error occured */
FDKmemclear(&hDrcDec->uniDrcConfig, sizeof(hDrcDec->uniDrcConfig));
hDrcDec->uniDrcConfig.diff = 1;
}
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ReadDownmixInstructions_Box(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
return DRC_DEC_NOT_OK;
if (dErr) {
/* clear config, if parsing error occurred */
FDKmemclear(&hDrcDec->uniDrcConfig.downmixInstructions,
sizeof(hDrcDec->uniDrcConfig.downmixInstructions));
hDrcDec->uniDrcConfig.downmixInstructionsCount = 0;
hDrcDec->uniDrcConfig.downmixInstructionsCountV0 = 0;
hDrcDec->uniDrcConfig.downmixInstructionsCountV1 = 0;
hDrcDec->uniDrcConfig.diff = 1;
}
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ReadUniDrcInstructions_Box(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
return DRC_DEC_NOT_OK;
if (dErr) {
/* clear config, if parsing error occurred */
FDKmemclear(&hDrcDec->uniDrcConfig.drcInstructionsUniDrc,
sizeof(hDrcDec->uniDrcConfig.drcInstructionsUniDrc));
hDrcDec->uniDrcConfig.drcInstructionsUniDrcCount = 0;
hDrcDec->uniDrcConfig.drcInstructionsUniDrcCountV0 = 0;
hDrcDec->uniDrcConfig.drcInstructionsUniDrcCountV1 = 0;
hDrcDec->uniDrcConfig.diff = 1;
}
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ReadUniDrcCoefficients_Box(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
return DRC_DEC_NOT_OK;
if (dErr) {
/* clear config, if parsing error occurred */
FDKmemclear(&hDrcDec->uniDrcConfig.drcCoefficientsUniDrc,
sizeof(hDrcDec->uniDrcConfig.drcCoefficientsUniDrc));
hDrcDec->uniDrcConfig.drcCoefficientsUniDrcCount = 0;
hDrcDec->uniDrcConfig.drcCoefficientsUniDrcCountV0 = 0;
hDrcDec->uniDrcConfig.drcCoefficientsUniDrcCountV1 = 0;
hDrcDec->uniDrcConfig.diff = 1;
}
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ReadLoudnessInfoSet(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (hDrcDec->codecMode == DRC_DEC_MPEG_D_USAC) {
dErr = drcDec_readLoudnessInfoSet(hBitstream, &(hDrcDec->loudnessInfoSet));
} else
return DRC_DEC_NOT_OK;
if (dErr) {
/* clear config, if parsing error occurred */
FDKmemclear(&hDrcDec->loudnessInfoSet, sizeof(hDrcDec->loudnessInfoSet));
hDrcDec->loudnessInfoSet.diff = 1;
}
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ReadLoudnessBox(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
return DRC_DEC_NOT_OK;
if (dErr) {
/* clear config, if parsing error occurred */
FDKmemclear(&hDrcDec->loudnessInfoSet, sizeof(hDrcDec->loudnessInfoSet));
hDrcDec->loudnessInfoSet.diff = 1;
}
startSelectionProcess(hDrcDec);
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ReadUniDrcGain(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (!hDrcDec->status) {
return DRC_DEC_OK;
}
dErr = drcDec_readUniDrcGain(
hBitstream, &(hDrcDec->uniDrcConfig),
drcDec_GainDecoder_GetFrameSize(hDrcDec->hGainDec),
drcDec_GainDecoder_GetDeltaTminDefault(hDrcDec->hGainDec),
&(hDrcDec->uniDrcGain));
if (dErr) return DRC_DEC_NOT_OK;
hDrcDec->status = DRC_DEC_NEW_GAIN_PAYLOAD;
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ReadUniDrc(HANDLE_DRC_DECODER hDrcDec,
HANDLE_FDK_BITSTREAM hBitstream) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (!hDrcDec->status) return DRC_DEC_NOT_READY;
dErr = drcDec_readUniDrc(
hBitstream, &(hDrcDec->uniDrcConfig), &(hDrcDec->loudnessInfoSet),
drcDec_GainDecoder_GetFrameSize(hDrcDec->hGainDec),
drcDec_GainDecoder_GetDeltaTminDefault(hDrcDec->hGainDec),
&(hDrcDec->uniDrcGain));
if (dErr) return DRC_DEC_NOT_OK;
startSelectionProcess(hDrcDec);
hDrcDec->status = DRC_DEC_NEW_GAIN_PAYLOAD;
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_Preprocess(HANDLE_DRC_DECODER hDrcDec) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (!hDrcDec->status) return DRC_DEC_NOT_READY;
if (!(hDrcDec->functionalRange & DRC_DEC_GAIN)) return DRC_DEC_NOT_OK;
if (hDrcDec->status != DRC_DEC_NEW_GAIN_PAYLOAD) {
/* no new gain payload was read, e.g. during concalment or flushing.
Generate DRC gains based on the stored DRC gains of last frames */
drcDec_GainDecoder_Conceal(hDrcDec->hGainDec, &(hDrcDec->uniDrcConfig),
&(hDrcDec->uniDrcGain));
}
dErr = drcDec_GainDecoder_Preprocess(
hDrcDec->hGainDec, &(hDrcDec->uniDrcGain),
hDrcDec->selProcOutput.loudnessNormalizationGainDb,
hDrcDec->selProcOutput.boost, hDrcDec->selProcOutput.compress);
if (dErr) return DRC_DEC_NOT_OK;
hDrcDec->status = DRC_DEC_INTERPOLATION_PREPARED;
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ProcessTime(HANDLE_DRC_DECODER hDrcDec, const int delaySamples,
const DRC_DEC_LOCATION drcLocation,
const int channelOffset, const int drcChannelOffset,
const int numChannelsProcessed, FIXP_DBL* realBuffer,
const int timeDataChannelOffset) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (!(hDrcDec->functionalRange & DRC_DEC_GAIN)) return DRC_DEC_NOT_OK;
if (hDrcDec->status != DRC_DEC_INTERPOLATION_PREPARED)
return DRC_DEC_NOT_READY;
dErr = drcDec_GainDecoder_ProcessTimeDomain(
hDrcDec->hGainDec, delaySamples, (GAIN_DEC_LOCATION)drcLocation,
channelOffset, drcChannelOffset, numChannelsProcessed,
timeDataChannelOffset, realBuffer);
if (dErr) return DRC_DEC_NOT_OK;
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ProcessFreq(HANDLE_DRC_DECODER hDrcDec, const int delaySamples,
const DRC_DEC_LOCATION drcLocation,
const int channelOffset, const int drcChannelOffset,
const int numChannelsProcessed,
const int processSingleTimeslot, FIXP_DBL** realBuffer,
FIXP_DBL** imagBuffer) {
DRC_ERROR dErr = DE_OK;
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (!(hDrcDec->functionalRange & DRC_DEC_GAIN)) return DRC_DEC_NOT_OK;
if (hDrcDec->status != DRC_DEC_INTERPOLATION_PREPARED)
return DRC_DEC_NOT_READY;
dErr = drcDec_GainDecoder_ProcessSubbandDomain(
hDrcDec->hGainDec, delaySamples, (GAIN_DEC_LOCATION)drcLocation,
channelOffset, drcChannelOffset, numChannelsProcessed,
processSingleTimeslot, realBuffer, imagBuffer);
if (dErr) return DRC_DEC_NOT_OK;
return DRC_DEC_OK;
}
DRC_DEC_ERROR
FDK_drcDec_ApplyDownmix(HANDLE_DRC_DECODER hDrcDec, int* reverseInChannelMap,
int* reverseOutChannelMap, FIXP_DBL* realBuffer,
int* pNChannels) {
SEL_PROC_OUTPUT* pSelProcOutput = &(hDrcDec->selProcOutput);
int baseChCnt = pSelProcOutput->baseChannelCount;
int targetChCnt = pSelProcOutput->targetChannelCount;
int frameSize, n, ic, oc;
FIXP_DBL tmp_out[8];
FIXP_DBL* audioChannels[8];
if (hDrcDec == NULL) return DRC_DEC_NOT_OPENED;
if (!(hDrcDec->functionalRange & DRC_DEC_GAIN)) return DRC_DEC_NOT_OK;
/* only downmix is performed here, no upmix.
Downmix is only performed if downmix coefficients are provided.
All other cases of downmix and upmix are treated by pcmDmx library. */
if (pSelProcOutput->downmixMatrixPresent == 0)
return DRC_DEC_OK; /* no downmix */
if (targetChCnt >= baseChCnt) return DRC_DEC_OK; /* downmix only */
/* sanity checks */
if (realBuffer == NULL) return DRC_DEC_NOT_OK;
if (reverseInChannelMap == NULL) return DRC_DEC_NOT_OK;
if (reverseOutChannelMap == NULL) return DRC_DEC_NOT_OK;
if (baseChCnt > 8) return DRC_DEC_NOT_OK;
if (baseChCnt != *pNChannels) return DRC_DEC_NOT_OK;
if (targetChCnt > 8) return DRC_DEC_NOT_OK;
frameSize = drcDec_GainDecoder_GetFrameSize(hDrcDec->hGainDec);
for (ic = 0; ic < baseChCnt; ic++) {
audioChannels[ic] = &(realBuffer[ic * frameSize]);
}
/* in-place downmix */
for (n = 0; n < frameSize; n++) {
for (oc = 0; oc < targetChCnt; oc++) {
tmp_out[oc] = (FIXP_DBL)0;
for (ic = 0; ic < baseChCnt; ic++) {
tmp_out[oc] +=
fMultDiv2(audioChannels[ic][n],
pSelProcOutput->downmixMatrix[reverseInChannelMap[ic]]
[reverseOutChannelMap[oc]])
<< 3;
}
}
for (oc = 0; oc < targetChCnt; oc++) {
if (oc >= baseChCnt) break;
audioChannels[oc][n] = tmp_out[oc];
}
}
for (oc = targetChCnt; oc < baseChCnt; oc++) {
FDKmemset(audioChannels[oc], 0, frameSize * sizeof(FIXP_DBL));
}
*pNChannels = targetChCnt;
return DRC_DEC_OK;
}
/* Get library info for this module. */
DRC_DEC_ERROR
FDK_drcDec_GetLibInfo(LIB_INFO* info) {
int i;
if (info == NULL) {
return DRC_DEC_INVALID_PARAM;
}
/* Search for next free tab */
for (i = 0; i < FDK_MODULE_LAST; i++) {
if (info[i].module_id == FDK_NONE) break;
}
if (i == FDK_MODULE_LAST) {
return DRC_DEC_NOT_OK;
}
/* Add the library info */
info[i].module_id = FDK_UNIDRCDEC;
info[i].version = LIB_VERSION(DRCDEC_LIB_VL0, DRCDEC_LIB_VL1, DRCDEC_LIB_VL2);
LIB_VERSION_STRING(info + i);
info[i].build_date = DRCDEC_LIB_BUILD_DATE;
info[i].build_time = DRCDEC_LIB_BUILD_TIME;
info[i].title = DRCDEC_LIB_TITLE;
return DRC_DEC_OK;
}
| {
"pile_set_name": "Github"
} |
import { GRID_GROUP_CHECK } from '../integrated-grouping/constants';
import { GetRowIdFn, Row, RowId, GetCellValueFn, Column } from '../../types';
import { PureComputed } from '@devexpress/dx-core';
const warnIfRowIdUndefined: PureComputed<[GetRowIdFn]> = getRowId => (row) => {
const result = getRowId(row);
if (!row[GRID_GROUP_CHECK] && result === undefined) {
// tslint:disable-next-line: no-console
console.warn('The row id is undefined. Check the getRowId function. The row is', row);
}
return result;
};
export const rowIdGetter: PureComputed<[GetRowIdFn, Row[]]> = (getRowId, rows) => {
if (!getRowId) {
const map = new Map(rows.map((row, rowIndex) => [row, rowIndex]) as [any, number]);
return (row: Row) => map.get(row) as RowId;
}
return warnIfRowIdUndefined(getRowId);
};
const defaultGetCellValue: GetCellValueFn = (row, columnName) => row[columnName];
export const cellValueGetter: PureComputed<[GetCellValueFn, Column[]]> = (
getCellValue = defaultGetCellValue, columns,
) => {
let useFastAccessor = true;
const map = columns.reduce((acc, column) => {
if (column.getCellValue) {
useFastAccessor = false;
acc[column.name] = column.getCellValue;
}
return acc;
}, {});
if (useFastAccessor) {
return getCellValue;
}
return (row, columnName) => (map[columnName]
? map[columnName](row, columnName)
: getCellValue(row, columnName));
};
| {
"pile_set_name": "Github"
} |
// 表格数据为空时的处理逻辑
import utils from '../../src/utils/utils.js'
export default {
data(){
return {
isTableEmpty: false,
// 表格数据为空时表头的高度(若有滚动条会包含滚动条的宽度)
//tableEmptyContentHeight: 50,
// 表格数据为空时的总高度
tableEmptyHeight: 0
}
},
methods: {
// table 数据为空的处理
tableEmpty(){
var tableData = this.internalTableData,
tableEmptyHeight = 0;
if (Array.isArray(tableData) && tableData.length > 0) {
this.isTableEmpty = false;
return false;
}
this.isTableEmpty = true;
tableEmptyHeight = this.getTotalColumnsHeight() + this.errorContentHeight;
this.tableEmptyHeight = tableEmptyHeight;
this.$nextTick(x => {
this.tableEmptyScroll();
})
},
tableEmptyScrollEvent(e){
var headerEle = this.$el.querySelector('.v-table-rightview .v-table-header'),
tableEmptyEle = this.$el.querySelector('.v-table-empty .v-table-empty-scroll');
if (tableEmptyEle) {
headerEle.scrollLeft = tableEmptyEle.scrollLeft;
}
},
// 无数据时的滚动条控制
tableEmptyScroll(){
var tableEmptyEle = this.$el.querySelector('.v-table-empty .v-table-empty-scroll');
// 无数据时的滚动条控制
utils.bind(tableEmptyEle, 'scroll', this.tableEmptyScrollEvent);
},
},
beforeDestroy(){
var tableEmptyEle = this.$el.querySelector('.v-table-empty .v-table-empty-scroll');
// 无数据时的滚动条控制
utils.unbind(tableEmptyEle, 'scroll', this.tableEmptyScrollEvent);
}
} | {
"pile_set_name": "Github"
} |
"""Test MySQL FOR UPDATE behavior.
See #4246
"""
import contextlib
from sqlalchemy import Column
from sqlalchemy import exc
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import testing
from sqlalchemy import update
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.testing import fixtures
class MySQLForUpdateLockingTest(fixtures.DeclarativeMappedTest):
__backend__ = True
__only_on__ = "mysql"
__requires__ = ("mysql_for_update",)
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
x = Column(Integer)
y = Column(Integer)
bs = relationship("B")
__table_args__ = {"mysql_engine": "InnoDB"}
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
a_id = Column(ForeignKey("a.id"))
x = Column(Integer)
y = Column(Integer)
__table_args__ = {"mysql_engine": "InnoDB"}
@classmethod
def insert_data(cls, connection):
A = cls.classes.A
B = cls.classes.B
# all the x/y are < 10
s = Session(connection)
s.add_all(
[
A(x=5, y=5, bs=[B(x=4, y=4), B(x=2, y=8), B(x=7, y=1)]),
A(x=7, y=5, bs=[B(x=4, y=4), B(x=5, y=8)]),
]
)
s.commit()
@contextlib.contextmanager
def run_test(self):
connection = testing.db.connect()
connection.execute("set innodb_lock_wait_timeout=1")
main_trans = connection.begin()
try:
yield Session(bind=connection)
finally:
main_trans.rollback()
connection.close()
def _assert_a_is_locked(self, should_be_locked):
A = self.classes.A
with testing.db.begin() as alt_trans:
alt_trans.execute("set innodb_lock_wait_timeout=1")
# set x/y > 10
try:
alt_trans.execute(update(A).values(x=15, y=19))
except (exc.InternalError, exc.OperationalError) as err:
assert "Lock wait timeout exceeded" in str(err)
assert should_be_locked
else:
assert not should_be_locked
def _assert_b_is_locked(self, should_be_locked):
B = self.classes.B
with testing.db.begin() as alt_trans:
alt_trans.execute("set innodb_lock_wait_timeout=1")
# set x/y > 10
try:
alt_trans.execute(update(B).values(x=15, y=19))
except (exc.InternalError, exc.OperationalError) as err:
assert "Lock wait timeout exceeded" in str(err)
assert should_be_locked
else:
assert not should_be_locked
def test_basic_lock(self):
A = self.classes.A
with self.run_test() as s:
s.query(A).with_for_update().all()
# test our fixture
self._assert_a_is_locked(True)
def test_basic_not_lock(self):
A = self.classes.A
with self.run_test() as s:
s.query(A).all()
# test our fixture
self._assert_a_is_locked(False)
def test_joined_lock_subquery(self):
A = self.classes.A
with self.run_test() as s:
s.query(A).options(joinedload(A.bs)).with_for_update().first()
# test for issue #4246, should be locked
self._assert_a_is_locked(True)
self._assert_b_is_locked(True)
def test_joined_lock_subquery_inner_for_update(self):
A = self.classes.A
B = self.classes.B
with self.run_test() as s:
q = s.query(A).with_for_update().subquery()
s.query(q).join(B).all()
# FOR UPDATE is inside the subquery, should be locked
self._assert_a_is_locked(True)
# FOR UPDATE is inside the subquery, B is not locked
self._assert_b_is_locked(False)
def test_joined_lock_subquery_inner_for_update_outer(self):
A = self.classes.A
B = self.classes.B
with self.run_test() as s:
q = s.query(A).with_for_update().subquery()
s.query(q).join(B).with_for_update().all()
# FOR UPDATE is inside the subquery, should be locked
self._assert_a_is_locked(True)
# FOR UPDATE is also outside the subquery, B is locked
self._assert_b_is_locked(True)
def test_joined_lock_subquery_order_for_update_outer(self):
A = self.classes.A
B = self.classes.B
with self.run_test() as s:
q = s.query(A).order_by(A.id).subquery()
s.query(q).join(B).with_for_update().all()
# FOR UPDATE is inside the subquery, should not be locked
self._assert_a_is_locked(False)
self._assert_b_is_locked(True)
def test_joined_lock_no_subquery(self):
A = self.classes.A
with self.run_test() as s:
s.query(A).options(joinedload(A.bs)).with_for_update().all()
# no subquery, should be locked
self._assert_a_is_locked(True)
self._assert_b_is_locked(True)
| {
"pile_set_name": "Github"
} |
application: twitmock-1012
version: 1
runtime: go
api_version: go1
handlers:
- url: /form/.*
script: _go_app
secure: always
- url: /.*
script: _go_app
# order matters | {
"pile_set_name": "Github"
} |
/*
* AC-3 encoder options
* Copyright (c) 2011 Justin Ruggles <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/opt.h"
#include "internal.h"
#include "ac3.h"
static const AVOption ac3_options[] = {
/* Metadata Options */
{"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, AC3ENC_PARAM},
#if AC3ENC_TYPE != AC3ENC_TYPE_EAC3
/* AC-3 downmix levels */
{"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
{"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
#endif
/* audio production information */
{"mixing_level", "Mixing Level", OFFSET(mixing_level), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, 111, AC3ENC_PARAM},
{"room_type", "Room Type", OFFSET(room_type), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_SMALL_ROOM, AC3ENC_PARAM, "room_type"},
{"notindicated", "Not Indicated (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
{"large", "Large Room", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_LARGE_ROOM }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
{"small", "Small Room", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_SMALL_ROOM }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
/* other metadata options */
{"copyright", "Copyright Bit", OFFSET(copyright), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, 1, AC3ENC_PARAM},
{"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), AV_OPT_TYPE_INT, {.i64 = -31 }, -31, -1, AC3ENC_PARAM},
{"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_MODE_ON, AC3ENC_PARAM, "dsur_mode"},
{"notindicated", "Not Indicated (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
{"on", "Dolby Surround Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_ON }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
{"off", "Not Dolby Surround Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_OFF }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
{"original", "Original Bit Stream", OFFSET(original), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, 1, AC3ENC_PARAM},
/* extended bitstream information */
{"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_DOWNMIX_DPLII, AC3ENC_PARAM, "dmix_mode"},
{"notindicated", "Not Indicated (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
{"ltrt", "Lt/Rt Downmix Preferred", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DOWNMIX_LTRT }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
{"loro", "Lo/Ro Downmix Preferred", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DOWNMIX_LORO }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
{"dplii", "Dolby Pro Logic II Downmix Preferred", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DOWNMIX_DPLII }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
{"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
{"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
{"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
{"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
{"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_DSUREX_DPLIIZ, AC3ENC_PARAM, "dsurex_mode"},
{"notindicated", "Not Indicated (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
{"on", "Dolby Surround EX Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_ON }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
{"off", "Not Dolby Surround EX Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_OFF }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
{"dpliiz", "Dolby Pro Logic IIz-encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DSUREX_DPLIIZ }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
{"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_MODE_ON, AC3ENC_PARAM, "dheadphone_mode"},
{"notindicated", "Not Indicated (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
{"on", "Dolby Headphone Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_ON }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
{"off", "Not Dolby Headphone Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_OFF }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
{"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_ADCONV_HDCD, AC3ENC_PARAM, "ad_conv_type"},
{"standard", "Standard (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_ADCONV_STANDARD }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
{"hdcd", "HDCD", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_ADCONV_HDCD }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
/* Other Encoding Options */
{"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), AV_OPT_TYPE_BOOL, {.i64 = 1 }, 0, 1, AC3ENC_PARAM},
{"channel_coupling", "Channel Coupling", OFFSET(channel_coupling), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_AUTO }, AC3ENC_OPT_AUTO, AC3ENC_OPT_ON, AC3ENC_PARAM, "channel_coupling"},
{"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_AUTO }, INT_MIN, INT_MAX, AC3ENC_PARAM, "channel_coupling"},
{"cpl_start_band", "Coupling Start Band", OFFSET(cpl_start), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_AUTO }, AC3ENC_OPT_AUTO, 15, AC3ENC_PARAM, "cpl_start_band"},
{"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_AUTO }, INT_MIN, INT_MAX, AC3ENC_PARAM, "cpl_start_band"},
{NULL}
};
static const AVCodecDefault ac3_defaults[] = {
{ "b", "0" },
{ NULL }
};
| {
"pile_set_name": "Github"
} |
{
"opening_times": {
"regular_hours": [
{
"weekday": 1,
"period_begin": "08:00",
"period_end": "20:00"
},
{
"weekday": 2,
"period_begin": "08:00",
"period_end": "20:00"
},
{
"weekday": 3,
"period_begin": "08:00",
"period_end": "20:00"
},
{
"weekday": 4,
"period_begin": "08:00",
"period_end": "20:00"
},
{
"weekday": 5,
"period_begin": "08:00",
"period_end": "20:00"
}
],
"twentyfourseven": false,
"exceptional_openings": [
{
"period_begin": "2014-06-21T09:00:00Z",
"period_end": "2014-06-21T12:00:00Z"
}
],
"exceptional_closings": [
{
"period_begin": "2014-06-24T00:00:00Z",
"period_end": "2014-06-25T00:00:00Z"
}
]
}
} | {
"pile_set_name": "Github"
} |
Mono.Directory.LDAP/BindSimpleTest.cs
Mono.Directory.LDAP/QueryRootDSETest.cs
| {
"pile_set_name": "Github"
} |
package factory.pattern;
/**
* Created by luisburgos on 15/07/15.
*/
public class ConcreteFactoryOne extends Factory{
@Override
public Product createProduct(String productType) {
return new ConcreteProductOne();
}
}
| {
"pile_set_name": "Github"
} |
#begin document (wb/sel/40/sel_4038); part 000
wb/sel/40/sel_4038 -1 0 [WORD] XX (TOP* - - - - * -
wb/sel/40/sel_4038 -1 1 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 2 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 3 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 4 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 5 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 6 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 7 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 8 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 9 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 10 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 11 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 12 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 13 [WORD] VERB * demoralize - 2 - * -
wb/sel/40/sel_4038 -1 14 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 15 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 16 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 17 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 18 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 19 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 20 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 21 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 22 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 23 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 24 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 25 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 26 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 27 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 28 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 29 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 30 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 31 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 32 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 33 [WORD] XX * - - - - * -
wb/sel/40/sel_4038 -1 34 [WORD] XX *) - - - - * -
#end document
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015 herd contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.finra.dm.service.activiti.task;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.springframework.stereotype.Component;
/**
* Old Activiti Java delegate.
*
* @deprecated use the class defined in the org.finra.herd.service.activiti.task package.
*/
@Component
@SuppressFBWarnings(value = "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS",
justification = "This is a deprecated class that extends the class of the same name in a different Java package. It will be removed when all users " +
"migrate to the new Java package.")
public class GetBusinessObjectDefinition extends org.finra.herd.service.activiti.task.GetBusinessObjectDefinition
{
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.java.swing.plaf.gtk;
import javax.swing.plaf.synth.Region;
/**
* A typesafe enumeration of the distinct rendering portions specific
* to GTK.
*
* @author Scott Violet
*/
class GTKRegion extends Region {
public static final Region HANDLE_BOX = new GTKRegion("HandleBox", null,
true);
protected GTKRegion(String name, String ui, boolean subregion) {
super(name, ui, subregion);
}
}
| {
"pile_set_name": "Github"
} |
def stats_text_en(text):
"""Count the English words in the text."""
text1 = text.replace(',','').replace('.','').replace('--','').replace('*','').replace('!','') # Remove the non-English characters in the text.
text2 = text1.split() # Convert the string type to the list type.
dict = {x: text2.count(x) for x in text2} # Count the times of each word in the list.
dict1= sorted(dict.items(), key= lambda d:d[1], reverse = True) # Sort the words in the descending order according to the times of words.
print(dict1) # Return the result.
text = 'Python is so powerful and useful!'
print(stats_text_en(text))
def stats_text_cn(text):
"""Count the Chinese characters in the text."""
text1 = text.replace(',','').replace('.','').replace('--','').replace('*','').replace('!','') # Remove the non-Chinese characters in the text.
text2 = list(text1) # Convert the string type to the list type.
dict = {x: text2.count(x) for x in text2} # Count the times of each character in the list.
dict1= sorted(dict.items(), key= lambda d:d[1], reverse = True) # Sort the character in the descending order according to the times of characters.
print(dict1) # Return the result.
text = '自学是门手艺!自学能力非常重要!'
print(stats_text_cn(text)) | {
"pile_set_name": "Github"
} |
package com.forezp.util;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.List;
/**
* Created by fangzhipeng on 2017/6/6.
*/
public class UserUtils {
private static final String AUTHORIZATION = "authorization";
/**
* 获取当前请求的token
* @return
*/
public static String getCurrentToken() {
return HttpUtils.getHeaders(HttpUtils.getHttpServletRequest()).get(AUTHORIZATION);
}
/**
* 获取当前请求的用户Id
* @return
*/
public static String getCurrentPrinciple() {
return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
/**
* 判读当前token用户是否为接口所需的参数username
*
* @param username
* @return
*/
public static boolean isMyself(String username) {
return username.equals(getCurrentPrinciple());
}
/**
* 获取当前请求Authentication
*
* @return
*/
public static Authentication getCurrentAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 获取当前请求的权限信息
* @return
*/
public static List<SimpleGrantedAuthority> getCurrentAuthorities() {
return (List<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
}
/**
* @param role
* @return
*/
public static boolean hasRole(String role) {
if (!role.startsWith("ROLE_")) {
role = "ROLE_" + role;
}
boolean hasRole = false;
List<SimpleGrantedAuthority> list = getCurrentAuthorities();
for (SimpleGrantedAuthority s : list) {
if (role.equals(s.getAuthority())) {
hasRole = true;
break;
}
}
return hasRole;
}
}
| {
"pile_set_name": "Github"
} |
/*
obs-websocket
Copyright (C) 2016-2019 Stéphane Lepin <[email protected]>
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, see <https://www.gnu.org/licenses/>
*/
#include "ConnectionProperties.h"
ConnectionProperties::ConnectionProperties()
: _authenticated(false)
{
}
bool ConnectionProperties::isAuthenticated()
{
return _authenticated.load();
}
void ConnectionProperties::setAuthenticated(bool authenticated)
{
_authenticated.store(authenticated);
} | {
"pile_set_name": "Github"
} |
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);
| {
"pile_set_name": "Github"
} |
#pragma once
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
| {
"pile_set_name": "Github"
} |
# Tests for PERFORMANCE_SCHEMA
--source include/not_embedded.inc
--source include/have_perfschema.inc
--source ../include/start_server_common.inc
# Expect classes
show global variables like "performance_schema_max_socket_classes";
select count(*) > 0 from performance_schema.setup_instruments
where name like "wait/io/socket/%";
# Expect no class lost
show global status like "performance_schema_socket_classes_lost";
# Expect no instances
show global variables like "performance_schema_max_socket_instances";
select count(*) from performance_schema.socket_instances;
# Expect instances lost
--disable_warnings
select variable_value > 0 from information_schema.global_status
where variable_name like 'PERFORMANCE_SCHEMA_SOCKET_INSTANCES_LOST';
--enable_warnings
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package com.icerockdev.library.universal
import com.icerockdev.library.SharedFactory
import com.icerockdev.library.sample.CryptoProfileScreen
import com.icerockdev.library.sample.CryptoProfileViewModel
import com.icerockdev.library.sample.McommerceProfileScreen
import com.icerockdev.library.sample.McommerceProfileViewModel
import com.icerockdev.library.sample.PostsScreen
import com.icerockdev.library.sample.PostsViewModel
import com.icerockdev.library.sample.SocialProfileScreen
import com.icerockdev.library.sample.SocialProfileViewModel
import com.icerockdev.library.sample.StateScreen
import com.icerockdev.library.sample.StateViewModel
import com.icerockdev.library.sample.UsersScreen
import com.icerockdev.library.sample.UsersViewModel
import dev.icerock.moko.widgets.collection.CollectionWidget
import dev.icerock.moko.widgets.core.widget.constraint
import dev.icerock.moko.widgets.core.Theme
import dev.icerock.moko.widgets.core.Widget
import dev.icerock.moko.widgets.core.screen.Args
import dev.icerock.moko.widgets.core.screen.WidgetScreen
import dev.icerock.moko.widgets.core.style.view.SizeSpec
import dev.icerock.moko.widgets.core.style.view.WidgetSize
import dev.icerock.moko.widgets.core.widget.tabs
class WidgetsScreen(
private val sharedFactory: SharedFactory,
private val theme: Theme,
private val postsCollectionCategory: CollectionWidget.Category
) : WidgetScreen<Args.Empty>() {
override fun createContentWidget(): Widget<WidgetSize.Const<SizeSpec.AsParent, SizeSpec.AsParent>> {
return with(theme) {
constraint(size = WidgetSize.AsParent) {
val tabs = +tabs(
size = WidgetSize.Const(
width = SizeSpec.MatchConstraint,
height = SizeSpec.MatchConstraint
)
) {
tab(
title = const("P#2"),
body = SocialProfileScreen(
theme = theme, //AppTheme.socialWidgetScope,
viewModel = SocialProfileViewModel()
).createWidget()
)
tab(
title = const("P#4"),
body = CryptoProfileScreen(
theme = theme, //AppTheme.cryptoWidgetScope,
viewModel = CryptoProfileViewModel()
).createWidget()
)
tab(
title = const("P#1"),
body = SocialProfileScreen(
theme = theme,
viewModel = SocialProfileViewModel()
).createWidget()
)
tab(
title = const("P#3"),
body = McommerceProfileScreen(
theme = theme, //AppTheme.mcommerceWidgetScope,
viewModel = McommerceProfileViewModel()
).createWidget()
)
tab(
title = const("D"),
body = StateScreen(
theme = theme,
viewModel = StateViewModel()
).createWidget()
)
tab(
title = const("P"),
body = PostsScreen(
theme = theme,
viewModel = PostsViewModel()
).createWidget()
)
tab(
title = const("U"),
body = UsersScreen(
theme = theme,
viewModel = UsersViewModel(sharedFactory.usersUnitsFactory)
).createWidget()
)
}
constraints {
tabs topToTop root.safeArea
tabs bottomToBottom root.safeArea
tabs leftRightToLeftRight root
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
#ifndef SimDataFormats_HFShowerPhoton_H
#define SimDataFormats_HFShowerPhoton_H
///////////////////////////////////////////////////////////////////////////////
// File: HFShowerPhoton.h
// Photons which will generate single photo electron as in HFShowerLibrary
///////////////////////////////////////////////////////////////////////////////
#include "DataFormats/Math/interface/Point3D.h"
#include <iostream>
#include <cmath>
#include <vector>
class HFShowerPhoton {
public:
/// point in the space
typedef math::XYZPointF Point;
HFShowerPhoton(float x = 0, float y = 0, float z = 0, float lambda = 0, float t = 0);
HFShowerPhoton(const Point& p, float time, float lambda);
HFShowerPhoton(const HFShowerPhoton&);
virtual ~HFShowerPhoton();
const Point& position() const { return position_; }
float x() const { return position_.X(); }
float y() const { return position_.Y(); }
float z() const { return position_.Z(); }
float lambda() const { return lambda_; }
float t() const { return time_; }
private:
Point position_;
float lambda_;
float time_;
};
typedef std::vector<HFShowerPhoton> HFShowerPhotonCollection;
std::ostream& operator<<(std::ostream&, const HFShowerPhoton&);
#endif
| {
"pile_set_name": "Github"
} |
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#pragma once
#include "Kernel.h"
#include "PorousFlowDictator.h"
/**
* PorousFlowEffectiveStressCoupling computes
* -coefficient*effective_porepressure*grad_component(test)
* where component is the spatial component (not
* a fluid component!)
*/
class PorousFlowEffectiveStressCoupling : public Kernel
{
public:
static InputParameters validParams();
PorousFlowEffectiveStressCoupling(const InputParameters & parameters);
protected:
virtual Real computeQpResidual() override;
virtual Real computeQpJacobian() override;
virtual Real computeQpOffDiagJacobian(unsigned int jvar) override;
/// The PorousFlow dictator that holds global info about the simulation
const PorousFlowDictator & _dictator;
/// Biot coefficient
const Real _coefficient;
/// The spatial component
const unsigned int _component;
/// Effective porepressure
const MaterialProperty<Real> & _pf;
/// d(effective porepressure)/(d porflow variable)
const MaterialProperty<std::vector<Real>> & _dpf_dvar;
/// Whether an RZ coordinate system is being used
const bool _rz;
};
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: 159_14_SSE_Linear_Fog1
m_Shader: {fileID: 4800000, guid: c8bce8bda0c443b40836bb85c1c93e4b, type: 3}
m_ShaderKeywords: _ALPHAPREMULTIPLY_ON _BLENDOP_HARDLIGHT _DEFAULTVALUE_RED
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _Bump:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 2800000, guid: b02db206ebb3e16489d9182daaf89358, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Cube:
m_Texture: {fileID: 8900000, guid: 04bfe9229de6de8429dbd8c69b781954, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Detail:
m_Texture: {fileID: 2800000, guid: a08960dd6e8274e7f8fca616e09c48ed, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 2800000, guid: 9a8f12fee98936349858716a27ce464e, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Layer:
m_Texture: {fileID: 10300, guid: 0000000000000000f000000000000000, type: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 51a41cc951fa0674eb018dac8bcb3f43, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex1:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex2:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex3:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex4:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex5:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex6:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _Amount: 0.0001
- _BlendOp: 12
- _Brightness: 0.1
- _BumpScale: 1
- _Contrast: 2
- _Cutoff: 0.5
- _DefaultValue: 5
- _DetailNormalMapScale: 1
- _DstBlend: 10
- _GlossMapScale: 1
- _Glossiness: 0
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 3
- _OcclusionStrength: 1
- _Opacity: 1
- _Parallax: 0.02
- _Radius: 5
- _RadiusWidth: 1
- _RimPower: 3
- _SmoothnessTextureChannel: 0
- _Snow: 0.8
- _SnowDepth: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 0
m_Colors:
- _Center: {r: -3.9021528, g: 0, b: 0, a: 0}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _ColorTint: {r: 1, g: 0.6, b: 0.6, a: 1}
- _EmissionColor: {r: 1, g: 1, b: 0, a: 1}
- _FogColor: {r: 0.3, g: 0.4, b: 0.7, a: 1}
- _RadiusColor: {r: 1, g: 0, b: 0, a: 1}
- _RimColor: {r: 0.26, g: 0.19, b: 0.16, a: 0}
- _SnowColor: {r: 1, g: 1, b: 1, a: 1}
- _SnowDir: {r: 0, g: 1, b: 0, a: 1}
- _SnowDirection: {r: 0, g: 1, b: 0, a: 0}
- _SpecColor: {r: 0.2, g: 0.2, b: 0.2, a: 1}
| {
"pile_set_name": "Github"
} |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "AttenuatedComponentVisualizer.h"
class COMPONENTVISUALIZERS_API FAudioComponentVisualizer : public TAttenuatedComponentVisualizer<UAudioComponent>
{
private:
virtual bool IsVisualizerEnabled(const FEngineShowFlags& ShowFlags) const override
{
return ShowFlags.AudioRadius;
}
};
| {
"pile_set_name": "Github"
} |
#ifndef CERT_TRANS_MERKLETREE_SERIAL_HASHER_H_
#define CERT_TRANS_MERKLETREE_SERIAL_HASHER_H_
#include <openssl/sha.h>
#include <stddef.h>
#include <memory>
#include <string>
class SerialHasher {
public:
SerialHasher() = default;
virtual ~SerialHasher() = default;
SerialHasher(const SerialHasher&) = delete;
SerialHasher& operator=(const SerialHasher&) = delete;
virtual size_t DigestSize() const = 0;
// Reset the context. Must be called before the first Update() call.
// Optionally it can be called after each Final() call; however
// doing so is a no-op since Final() will leave the hasher in a
// reset state.
virtual void Reset() = 0;
// Update the hash context with (binary) data.
virtual void Update(const std::string& data) = 0;
// Finalize the hash context and return the binary digest blob.
virtual std::string Final() = 0;
// A virtual constructor, creates a new instance of the same type.
virtual std::unique_ptr<SerialHasher> Create() const = 0;
};
class Sha256Hasher : public SerialHasher {
public:
Sha256Hasher();
Sha256Hasher(const Sha256Hasher&) = delete;
Sha256Hasher& operator=(const Sha256Hasher&) = delete;
size_t DigestSize() const {
return kDigestSize;
}
void Reset();
void Update(const std::string& data);
std::string Final();
std::unique_ptr<SerialHasher> Create() const;
// Create a new hasher and call Reset(), Update(), and Final().
static std::string Sha256Digest(const std::string& data);
private:
SHA256_CTX ctx_;
bool initialized_;
static const size_t kDigestSize;
};
#endif // CERT_TRANS_MERKLETREE_SERIAL_HASHER_H_
| {
"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.
*/
package org.apache.syncope.client.console.panels;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.syncope.client.console.SyncopeConsoleSession;
import org.apache.syncope.client.console.layout.AnyLayout;
import org.apache.syncope.client.console.layout.AnyLayoutUtils;
import org.apache.syncope.client.console.layout.IdMUserFormLayoutInfo;
import org.apache.syncope.client.console.layout.LinkedAccountForm;
import org.apache.syncope.client.console.layout.LinkedAccountFormLayoutInfo;
import org.apache.syncope.client.console.pages.BasePage;
import org.apache.syncope.client.console.rest.AnyTypeRestClient;
import org.apache.syncope.client.console.rest.UserRestClient;
import org.apache.syncope.client.console.status.LinkedAccountStatusPanel;
import org.apache.syncope.client.console.status.ReconTaskPanel;
import org.apache.syncope.client.console.wicket.markup.html.bootstrap.dialog.BaseModal;
import org.apache.syncope.client.console.wicket.markup.html.form.ActionLink;
import org.apache.syncope.client.console.wicket.markup.html.form.ActionLinksTogglePanel;
import org.apache.syncope.client.console.wizards.WizardMgtPanel;
import org.apache.syncope.client.console.wizards.any.LinkedAccountWizardBuilder;
import org.apache.syncope.client.ui.commons.Constants;
import org.apache.syncope.client.ui.commons.panels.ModalPanel;
import org.apache.syncope.client.ui.commons.wizards.AjaxWizard;
import org.apache.syncope.common.lib.SyncopeClientException;
import org.apache.syncope.common.lib.request.LinkedAccountUR;
import org.apache.syncope.common.lib.request.UserUR;
import org.apache.syncope.common.lib.to.EntityTO;
import org.apache.syncope.common.lib.to.LinkedAccountTO;
import org.apache.syncope.common.lib.to.PullTaskTO;
import org.apache.syncope.common.lib.to.PushTaskTO;
import org.apache.syncope.common.lib.to.UserTO;
import org.apache.syncope.common.lib.types.IdRepoEntitlement;
import org.apache.syncope.common.lib.types.PatchOperation;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.PageReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.StringResourceModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LinkedAccountModalPanel extends Panel implements ModalPanel {
private static final long serialVersionUID = -4603032036433309900L;
private static final Logger LOG = LoggerFactory.getLogger(LinkedAccountModalPanel.class);
private LinkedAccountForm wizard;
private final WizardMgtPanel<LinkedAccountTO> list;
private final AjaxLink<LinkedAccountTO> addAjaxLink;
protected ActionLinksTogglePanel<LinkedAccountTO> actionTogglePanel;
private UserRestClient userRestClient = new UserRestClient();
private AnyTypeRestClient anyTypeRestClient = new AnyTypeRestClient();
private final List<LinkedAccountTO> linkedAccountTOs;
@SuppressWarnings("unchecked")
public LinkedAccountModalPanel(
final BaseModal<?> baseModal,
final IModel<UserTO> model,
final PageReference pageRef,
final boolean recounciliationOnly) {
super(BaseModal.getContentId(), model);
final MultilevelPanel mlp = new MultilevelPanel("mlpContainer");
mlp.setOutputMarkupId(true);
setOutputMarkupId(true);
actionTogglePanel = new ActionLinksTogglePanel<>("toggle", pageRef);
add(actionTogglePanel);
AnyLayout anyLayout = AnyLayoutUtils.fetch(
anyTypeRestClient.listAnyTypes().stream().map(EntityTO::getKey).collect(Collectors.toList()));
LinkedAccountFormLayoutInfo linkedAccountFormLayoutInfo =
anyLayout.getUser() instanceof IdMUserFormLayoutInfo
? IdMUserFormLayoutInfo.class.cast(anyLayout.getUser()).getLinkedAccountFormLayoutInfo()
: new LinkedAccountFormLayoutInfo();
try {
wizard = linkedAccountFormLayoutInfo.getFormClass().
getConstructor(model.getClass(), LinkedAccountFormLayoutInfo.class, PageReference.class).
newInstance(model, linkedAccountFormLayoutInfo, pageRef);
} catch (Exception e) {
LOG.error("Error instantiating form layout", e);
wizard = new LinkedAccountWizardBuilder(model, linkedAccountFormLayoutInfo, pageRef);
}
ListViewPanel.Builder<LinkedAccountTO> builder = new ListViewPanel.Builder<LinkedAccountTO>(
LinkedAccountTO.class, pageRef) {
private static final long serialVersionUID = -5322423525438435153L;
@Override
protected LinkedAccountTO getActualItem(final LinkedAccountTO item, final List<LinkedAccountTO> list) {
return item == null
? null
: list.stream().filter(
in -> ((item.getKey() == null && in.getKey() == null)
|| (in.getKey() != null && in.getKey().equals(item.getKey())))).
findAny().orElse(null);
}
@Override
protected void customActionCallback(final AjaxRequestTarget target) {
// change modal footer visibility
send(LinkedAccountModalPanel.this, Broadcast.BUBBLE, new BaseModal.ChangeFooterVisibilityEvent(target));
}
@Override
protected void customActionOnCancelCallback(final AjaxRequestTarget target) {
// change modal footer visibility
send(LinkedAccountModalPanel.this, Broadcast.BUBBLE, new BaseModal.ChangeFooterVisibilityEvent(target));
}
@Override
@SuppressWarnings("unchecked")
protected void customActionOnFinishCallback(final AjaxRequestTarget target) {
checkAddButton(model.getObject().getRealm());
linkedAccountTOs.clear();
linkedAccountTOs.addAll(model.getObject().getLinkedAccounts());
sortLinkedAccounts();
ListViewPanel.class.cast(list).refreshList(linkedAccountTOs);
// change modal footer visibility
send(LinkedAccountModalPanel.this, Broadcast.BUBBLE, new BaseModal.ChangeFooterVisibilityEvent(target));
}
@Override
protected Component getValueComponent(final String key, final LinkedAccountTO bean) {
if ("suspended".equalsIgnoreCase(key)) {
Label label = new Label("field", StringUtils.EMPTY);
if (bean.isSuspended()) {
label.add(new AttributeModifier("class", "fa fa-check"));
label.add(new AttributeModifier("style", "display: table-cell; text-align: center;"));
}
return label;
}
return super.getValueComponent(key, bean);
}
@Override
protected ActionLinksTogglePanel<LinkedAccountTO> getTogglePanel() {
return actionTogglePanel;
}
};
linkedAccountTOs = new ArrayList<>(model.getObject().getLinkedAccounts());
sortLinkedAccounts();
builder.setItems(linkedAccountTOs);
builder.includes("connObjectKeyValue", "resource", "suspended");
builder.setReuseItem(false);
builder.withChecks(ListViewPanel.CheckAvailability.NONE);
builder.addAction(new ActionLink<LinkedAccountTO>() {
private static final long serialVersionUID = 2555747430358755813L;
@Override
public void onClick(final AjaxRequestTarget target, final LinkedAccountTO linkedAccountTO) {
mlp.next(linkedAccountTO.getResource(), new LinkedAccountStatusPanel(
linkedAccountTO.getResource(),
model.getObject().getType(),
linkedAccountTO.getConnObjectKeyValue()),
target);
target.add(mlp);
((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
send(LinkedAccountModalPanel.this, Broadcast.BREADTH,
new ActionLinksTogglePanel.ActionLinkToggleCloseEventPayload(target));
}
}, ActionLink.ActionType.VIEW, IdRepoEntitlement.USER_READ);
if (!recounciliationOnly) {
builder.addAction(new ActionLink<LinkedAccountTO>() {
private static final long serialVersionUID = 2555747430358755813L;
@Override
public void onClick(final AjaxRequestTarget target, final LinkedAccountTO linkedAccountTO) {
try {
send(LinkedAccountModalPanel.this, Broadcast.DEPTH,
new AjaxWizard.NewItemActionEvent<>(linkedAccountTO, 1, target).
setResourceModel(new StringResourceModel("inner.edit.linkedAccount",
LinkedAccountModalPanel.this, Model.of(linkedAccountTO))));
} catch (SyncopeClientException e) {
LOG.error("While attempting to create new linked account", e);
SyncopeConsoleSession.get().onException(e);
((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
}
send(LinkedAccountModalPanel.this, Broadcast.BREADTH,
new ActionLinksTogglePanel.ActionLinkToggleCloseEventPayload(target));
}
}, ActionLink.ActionType.EDIT, IdRepoEntitlement.USER_UPDATE);
builder.addAction(new ActionLink<LinkedAccountTO>() {
private static final long serialVersionUID = 2555747430358755813L;
@Override
public void onClick(final AjaxRequestTarget target, final LinkedAccountTO linkedAccountTO) {
try {
linkedAccountTO.setSuspended(!linkedAccountTO.isSuspended());
LinkedAccountUR linkedAccountUR = new LinkedAccountUR.Builder().
operation(PatchOperation.ADD_REPLACE).
linkedAccountTO(linkedAccountTO).build();
UserUR req = new UserUR();
req.setKey(model.getObject().getKey());
req.getLinkedAccounts().add(linkedAccountUR);
model.setObject(userRestClient.update(model.getObject().getETagValue(), req).getEntity());
SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED));
} catch (SyncopeClientException e) {
LOG.error("While toggling status of linked account", e);
SyncopeConsoleSession.get().onException(e);
((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
}
checkAddButton(model.getObject().getRealm());
((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
send(LinkedAccountModalPanel.this, Broadcast.DEPTH, new ListViewPanel.ListViewReload<>(target));
}
}, ActionLink.ActionType.ENABLE, IdRepoEntitlement.USER_UPDATE);
}
builder.addAction(new ActionLink<LinkedAccountTO>() {
private static final long serialVersionUID = 2555747430358755813L;
@Override
public void onClick(final AjaxRequestTarget target, final LinkedAccountTO linkedAccountTO) {
mlp.next("PUSH " + linkedAccountTO.getResource(),
new ReconTaskPanel(
linkedAccountTO.getResource(),
new PushTaskTO(),
model.getObject().getType(),
null,
linkedAccountTO.getConnObjectKeyValue(),
true,
mlp,
pageRef),
target);
target.add(mlp);
((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
send(LinkedAccountModalPanel.this, Broadcast.BREADTH,
new ActionLinksTogglePanel.ActionLinkToggleCloseEventPayload(target));
}
}, ActionLink.ActionType.RECONCILIATION_PUSH,
String.format("%s,%s", IdRepoEntitlement.USER_READ, IdRepoEntitlement.TASK_EXECUTE));
builder.addAction(new ActionLink<LinkedAccountTO>() {
private static final long serialVersionUID = 2555747430358755813L;
@Override
public void onClick(final AjaxRequestTarget target, final LinkedAccountTO linkedAccountTO) {
mlp.next("PULL " + linkedAccountTO.getResource(),
new ReconTaskPanel(
linkedAccountTO.getResource(),
new PullTaskTO(),
model.getObject().getType(),
null,
linkedAccountTO.getConnObjectKeyValue(),
true,
mlp,
pageRef),
target);
target.add(mlp);
((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
send(LinkedAccountModalPanel.this, Broadcast.BREADTH,
new ActionLinksTogglePanel.ActionLinkToggleCloseEventPayload(target));
}
}, ActionLink.ActionType.RECONCILIATION_PULL,
String.format("%s,%s", IdRepoEntitlement.USER_READ, IdRepoEntitlement.TASK_EXECUTE));
if (!recounciliationOnly) {
builder.addAction(new ActionLink<LinkedAccountTO>() {
private static final long serialVersionUID = 2555747430358755813L;
@Override
public void onClick(final AjaxRequestTarget target, final LinkedAccountTO linkedAccountTO) {
try {
LinkedAccountUR linkedAccountUR = new LinkedAccountUR.Builder().
operation(PatchOperation.DELETE).
linkedAccountTO(linkedAccountTO).build();
UserUR req = new UserUR();
req.setKey(model.getObject().getKey());
req.getLinkedAccounts().add(linkedAccountUR);
model.setObject(userRestClient.update(model.getObject().getETagValue(), req).getEntity());
linkedAccountTOs.remove(linkedAccountTO);
SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED));
} catch (Exception e) {
LOG.error("While removing linked account {}", linkedAccountTO.getKey(), e);
SyncopeConsoleSession.get().onException(e);
}
checkAddButton(model.getObject().getRealm());
((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
send(LinkedAccountModalPanel.this, Broadcast.DEPTH, new ListViewPanel.ListViewReload<>(target));
}
}, ActionLink.ActionType.DELETE, IdRepoEntitlement.USER_UPDATE, true);
}
builder.addNewItemPanelBuilder(wizard);
list = builder.build(MultilevelPanel.FIRST_LEVEL_ID);
list.setOutputMarkupId(true);
list.setReadOnly(!SyncopeConsoleSession.get().
owns(IdRepoEntitlement.USER_UPDATE, model.getObject().getRealm()));
addAjaxLink = new AjaxLink<LinkedAccountTO>("add") {
private static final long serialVersionUID = -7978723352517770644L;
@Override
public void onClick(final AjaxRequestTarget target) {
send(LinkedAccountModalPanel.this, Broadcast.BREADTH,
new ActionLinksTogglePanel.ActionLinkToggleCloseEventPayload(target));
// this opens the wizard (set above) in CREATE mode
send(list, Broadcast.DEPTH, new AjaxWizard.NewItemActionEvent<>(new LinkedAccountTO(), target).
setResourceModel(
new StringResourceModel("inner.create.linkedAccount", LinkedAccountModalPanel.this)));
}
};
list.addOrReplaceInnerObject(addAjaxLink.setEnabled(!recounciliationOnly).setVisible(!recounciliationOnly));
add(mlp.setFirstLevel(list));
}
private void sortLinkedAccounts() {
linkedAccountTOs.sort(Comparator.comparing(LinkedAccountTO::getConnObjectKeyValue));
}
private void checkAddButton(final String realm) {
addAjaxLink.setVisible(SyncopeConsoleSession.get().owns(IdRepoEntitlement.USER_UPDATE, realm));
}
}
| {
"pile_set_name": "Github"
} |
/* crypto/ripemd/rmd160.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 <stdlib.h>
#include <openssl/ripemd.h>
#define BUFSIZE 1024*16
void do_fp(FILE *f);
void pt(unsigned char *md);
#if !defined(_OSD_POSIX) && !defined(__DJGPP__)
int read(int, void *, unsigned int);
#endif
int main(int argc, char **argv)
{
int i,err=0;
FILE *IN;
if (argc == 1)
{
do_fp(stdin);
}
else
{
for (i=1; i<argc; i++)
{
IN=fopen(argv[i],"r");
if (IN == NULL)
{
perror(argv[i]);
err++;
continue;
}
printf("RIPEMD160(%s)= ",argv[i]);
do_fp(IN);
fclose(IN);
}
}
exit(err);
}
void do_fp(FILE *f)
{
RIPEMD160_CTX c;
unsigned char md[RIPEMD160_DIGEST_LENGTH];
int fd;
int i;
static unsigned char buf[BUFSIZE];
fd=fileno(f);
RIPEMD160_Init(&c);
for (;;)
{
i=read(fd,buf,BUFSIZE);
if (i <= 0) break;
RIPEMD160_Update(&c,buf,(unsigned long)i);
}
RIPEMD160_Final(&(md[0]),&c);
pt(md);
}
void pt(unsigned char *md)
{
int i;
for (i=0; i<RIPEMD160_DIGEST_LENGTH; i++)
printf("%02x",md[i]);
printf("\n");
}
| {
"pile_set_name": "Github"
} |
// Module included in the following assemblies:
//
// * applications/odc-monitoring-project-and-application-metrics-using-developer-perspective.adoc
[id="odc-monitoring-your-project-metrics_{context}"]
= Monitoring your project metrics
After you create applications in your project and deploy them, you can use the *Developer* perspective in the web console to see the metrics for your project.
.Procedure
. On the left navigation panel of the *Developer* perspective, click *Monitoring* to see the *Dashboard*, *Metrics*, *Alerts*, and *Events* for your project.
* Use the *Dashboard* tab to see graphs depicting the CPU, memory, and bandwidth consumption and network related information, such as the rate of transmitted and received packets and the rate of dropped packets.
+
.Monitoring dashboard
image::odc_project_dashboard.png[]
+
Use the following options to see further details:
** Select a workload from the *All Workloads* list to see the filtered metrics for the selected workload.
** Select an option from the *Time Range* list to determine the time frame for the data being captured.
** Select an option from the *Refresh Interval* list to determine the time period after which the data is refreshed.
** Hover your cursor over the graphs to see specific details for your Pod.
** Click on any of the graphs displayed to see the details for that particular metric in the *Metrics* page.
* Use the *Metrics* tab to query for the required project metric.
+
.Monitoring metrics
image::odc_project_metrics.png[]
+
.. In the *Select Query* list, select an option to filter the required details for your project. The filtered metrics for all the application Pods in your project are displayed in the graph. The Pods in your project are also listed below.
.. From the list of Pods, clear the colored square boxes to remove the metrics for specific Pods to further filter your query result.
.. Click *Show PromQL* to see the Prometheus query. You can further modify this query with the help of prompts to customize the query and filter the metrics you want to see for that namespace.
.. Use the drop-down list to set a time range for the data being displayed. You can click *Reset Zoom* to reset it to the default time range.
.. Optionally, in the *Select Query* list, select *Custom Query* to create a custom Prometheus query and filter relevant metrics.
* Use the *Alerts* tab to see the rules that trigger alerts for the applications in your project, identify the alerts firing in the project, and silence them if required.
+
.Monitoring alerts
image::odc_project_alerts.png[]
+
** Use the *Filter* list to filter the alerts by their *Alert State* and *Severity*.
** Click on an alert to go to the details page for that alert. In the *Alerts Details* page, you can click the *View Metrics* button to see the metrics for the alert.
** Use the *Notifications* toggle adjoining an alert rule to silence all the alerts for that rule, and then select the duration for which the alerts will be silenced from the *Silence for* list.
You must have the permissions to edit alerts to see the *Notifications* toggle.
** Use the *Options* menu {kebab} adjoining an alert rule to see the details of the alerting rule.
* Use the *Events* tab to see the events for your project.
+
.Monitoring events
image::odc_project_events.png[]
+
You can filter the displayed events using the following options:
** In the *Resources* list, select a resource to see events for that resource.
** In the *All Types* list, select a type of event to see events relevant to that type.
** Search for specific events using the *Filter events by names or messages* field.
| {
"pile_set_name": "Github"
} |
# coding: utf-8
try:
import urllib.request
except ImportError:
raise ImportError('You should use Python 3.x')
import os.path
import gzip
import pickle
import os
import numpy as np
url_base = 'http://yann.lecun.com/exdb/mnist/'
key_file = {
'train_img':'train-images-idx3-ubyte.gz',
'train_label':'train-labels-idx1-ubyte.gz',
'test_img':'t10k-images-idx3-ubyte.gz',
'test_label':'t10k-labels-idx1-ubyte.gz'
}
dataset_dir = os.path.dirname(os.path.abspath(__file__))
save_file = dataset_dir + "/mnist.pkl"
train_num = 60000
test_num = 10000
img_dim = (1, 28, 28)
img_size = 784
def _download(file_name):
file_path = dataset_dir + "/" + file_name
if os.path.exists(file_path):
return
print("Downloading " + file_name + " ... ")
urllib.request.urlretrieve(url_base + file_name, file_path)
print("Done")
def download_mnist():
for v in key_file.values():
_download(v)
def _load_label(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
labels = np.frombuffer(f.read(), np.uint8, offset=8)
print("Done")
return labels
def _load_img(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=16)
data = data.reshape(-1, img_size)
print("Done")
return data
def _convert_numpy():
dataset = {}
dataset['train_img'] = _load_img(key_file['train_img'])
dataset['train_label'] = _load_label(key_file['train_label'])
dataset['test_img'] = _load_img(key_file['test_img'])
dataset['test_label'] = _load_label(key_file['test_label'])
return dataset
def init_mnist():
'''
Note:已将数据集下载至本地,第一次加载会将数据集保存成pickle
'''
# download_mnist()
dataset = _convert_numpy()
print("Creating pickle file ...")
with open(save_file, 'wb') as f:
pickle.dump(dataset, f, -1)
print("Done!")
def _change_one_hot_label(X):
T = np.zeros((X.size, 10))
for idx, row in enumerate(T):
row[X[idx]] = 1
return T
def load_mnist(normalize=True, flatten=True, one_hot_label=False):
"""读入MNIST数据集
Parameters
----------
normalize : 将图像的像素值正规化为0.0~1.0
one_hot_label :
one_hot_label为True的情况下,标签作为one-hot数组返回
one-hot数组是指[0,0,1,0,0,0,0,0,0,0]这样的数组
flatten : 是否将图像展开为一维数组
Returns
-------
(训练图像, 训练标签), (测试图像, 测试标签)
"""
if not os.path.exists(save_file):
init_mnist()
with open(save_file, 'rb') as f:
dataset = pickle.load(f)
if normalize:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].astype(np.float32)
dataset[key] /= 255.0
if one_hot_label:
dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
if not flatten:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].reshape(-1, 1, 28, 28)
return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label'])
if __name__ == '__main__':
init_mnist()
| {
"pile_set_name": "Github"
} |
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file config_framework.h
* @author drose
* @date 2000-09-06
*/
#ifndef CONFIG_FRAMEWORK_H
#define CONFIG_FRAMEWORK_H
#include "pandabase.h"
#include "notifyCategoryProxy.h"
#include "windowProperties.h"
#include "configVariableDouble.h"
#include "configVariableBool.h"
#include "configVariableString.h"
NotifyCategoryDecl(framework, EXPCL_FRAMEWORK, EXPTP_FRAMEWORK);
// Configure variables for framework package.
extern ConfigVariableDouble aspect_ratio;
extern ConfigVariableBool show_frame_rate_meter;
extern ConfigVariableBool show_scene_graph_analyzer_meter;
extern ConfigVariableBool print_pipe_types;
extern ConfigVariableString window_type;
extern ConfigVariableString record_session;
extern ConfigVariableString playback_session;
#endif
| {
"pile_set_name": "Github"
} |
/* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* 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 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.
*/
package org.voltdb_testprocs.regressionsuites.sqlfeatureprocs;
import org.voltdb.SQLStmt;
import org.voltdb.VoltProcedure;
import org.voltdb.VoltTable;
public class TruncateTable extends VoltProcedure {
public final SQLStmt truncateRTable = new SQLStmt("DELETE FROM RTABLE;");
public final SQLStmt checkRTable = new SQLStmt("SELECT COUNT(*) FROM RTABLE;");
public final SQLStmt truncatePTable = new SQLStmt("DELETE FROM PTABLE;");
public final SQLStmt checkPTable = new SQLStmt("SELECT COUNT(*) FROM PTABLE;");
public final SQLStmt insertRTable = new SQLStmt("INSERT INTO RTABLE VALUES(6, 30, 1.1, 'Jedi', 'Winchester');");
public long run() {
voltQueueSQL(truncateRTable);
voltQueueSQL(checkRTable);
voltQueueSQL(truncatePTable);
voltQueueSQL(checkPTable);
VoltTable[] results = voltExecuteSQL();
if (results.length != 4 ||
results[1].asScalarLong() != 0 ||
results[3].asScalarLong() != 0) {
throw new VoltAbortException(
"A table truncation behaved unexpectedly PRIOR to the intentional violation.");
}
// Force a rollback after a constraint violation
voltQueueSQL(insertRTable);
voltQueueSQL(insertRTable);
voltExecuteSQL();
return 0;
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript" src="../internal.js"></script>
<style type="text/css">
.wrapper{width: 600px;padding: 10px;height: 352px;overflow: hidden;position: relative;border-bottom: 1px solid #d7d7d7}
.localPath input{float: left;width: 350px;line-height: 20px;height: 20px;}
#clipboard{float:left;width: 70px;height: 30px; }
.description{ color: #0066cc; margin-top: 2px; width: 450px; height: 45px;float: left;line-height: 22px}
#upload{width: 100px;height: 30px;float: right; margin:10px 2px 0 0;cursor: pointer;}
#msg{ width: 140px; height: 30px; line-height:25px;float: left;color: red}
</style>
</head>
<body>
<div class="wrapper">
<div class="localPath">
<input id="localPath" type="text" readonly />
<div id="clipboard"></div>
<div id="msg"></div>
</div>
<div id="flashContainer"></div>
<div>
<div id="upload" style="display: none" ><img id="uploadBtn"></div>
<div class="description">
<span style="color: red"><var id="lang_resave"></var>: </span><var id="lang_step"></var>
</div>
</div>
</div>
<script type="text/javascript" src="tangram.js"></script>
<script type="text/javascript" src="wordimage.js"></script>
<script type="text/javascript">
editor.setOpt({
wordImageFieldName:"upfile",
compressSide:0,
maxImageSideLength:900
});
//全局变量
var imageUrls = [], //用于保存从服务器返回的图片信息数组
selectedImageCount = 0, //当前已选择的但未上传的图片数量
optImageUrl = editor.getActionUrl(editor.getOpt('imageActionName')),
optImageFieldName = editor.getOpt('imageFieldName'),
optImageCompressBorder = editor.getOpt('imageCompressEnable') ? editor.getOpt('imageCompressBorder'):null,
maxSize = editor.getOpt('imageMaxSize') / 1024,
extension = editor.getOpt('imageAllowFiles').join(';').replace(/\./g, '*.');
/* 添加额外的GET参数 */
var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
urlWidthParams = optImageUrl + (optImageUrl.indexOf('?') == -1 ? '?':'&') + params;
utils.domReady(function(){
//创建Flash相关的参数集合
var flashOptions = {
container:"flashContainer", //flash容器id
url:urlWidthParams, // 上传处理页面的url地址
ext:editor.queryCommandValue('serverParam') || {}, //可向服务器提交的自定义参数列表
fileType:'{"description":"'+lang.fileType+'", "extension":"' + extension + '"}', //上传文件格式限制
flashUrl:'imageUploader.swf', //上传用的flash组件地址
width:600, //flash的宽度
height:272, //flash的高度
gridWidth:120, // 每一个预览图片所占的宽度
gridHeight:120, // 每一个预览图片所占的高度
picWidth:100, // 单张预览图片的宽度
picHeight:100, // 单张预览图片的高度
uploadDataFieldName: optImageFieldName, // POST请求中图片数据的key
picDescFieldName:'pictitle', // POST请求中图片描述的key
maxSize: maxSize, // 文件的最大体积,单位M
compressSize:1, // 上传前如果图片体积超过该值,会先压缩,单位M
maxNum:32, // 单次最大可上传多少个文件
compressSide: 0, //等比压缩的基准,0为按照最长边,1为按照宽度,2为按照高度
compressLength: optImageCompressBorder //能接受的最大边长,超过该值Flash会自动等比压缩
};
//回调函数集合,支持传递函数名的字符串、函数句柄以及函数本身三种类型
var callbacks={
selectFileCallback: function(selectFiles){ // 选择文件的回调
selectedImageCount += selectFiles.length;
if(selectedImageCount) baidu.g("upload").style.display = "";
dialog.buttons[0].setDisabled(true); //初始化时置灰确定按钮
},
deleteFileCallback: function(delFiles){ // 删除文件的回调
selectedImageCount -= delFiles.length;
if (!selectedImageCount) {
baidu.g("upload").style.display = "none";
dialog.buttons[0].setDisabled(false); //没有选择图片时重新点亮按钮
}
},
uploadCompleteCallback: function(data){ // 单个文件上传完成的回调
try{var info = eval("(" + data.info + ")");
info && imageUrls.push(info);
selectedImageCount--;
}catch(e){}
},
uploadErrorCallback: function (data){ // 单个文件上传失败的回调,
console && console.log(data);
},
allCompleteCallback: function(){ // 全部上传完成时的回调
dialog.buttons[0].setDisabled(false); //上传完毕后点亮按钮
}
//exceedFileCallback: 'exceedFileCallback', // 文件超出限制的最大体积时的回调
//startUploadCallback: startUploadCallback // 开始上传某个文件时的回调
};
wordImage.init(flashOptions,callbacks);
});
</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <string>
// UNSUPPORTED: c++03, c++11, c++14
// XFAIL: libcpp-no-deduction-guides
// template<class InputIterator>
// basic_string(InputIterator begin, InputIterator end,
// const Allocator& a = Allocator());
// template<class charT,
// class traits,
// class Allocator = allocator<charT>
// >
// basic_string(basic_string_view<charT, traits>, const Allocator& = Allocator())
// -> basic_string<charT, traits, Allocator>;
//
// The deduction guide shall not participate in overload resolution if Allocator
// is a type that does not qualify as an allocator.
#include <string>
#include <string_view>
#include <iterator>
#include <cassert>
#include <cstddef>
int main(int, char**)
{
{
std::string_view sv = "12345678901234";
std::basic_string s1{sv, 23}; // expected-error {{no viable constructor or deduction guide for deduction of template arguments of 'basic_string'}}
}
return 0;
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.