repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
MicroHealthLLC/MH_ShowPreper
|
src/components/styler/borderEditor/index.js
|
import React from 'react'
import 'spectrum-colorpicker'
import 'spectrum-colorpicker/spectrum.css'
import DropdownList from 'react-widgets/lib/DropdownList'
import './index.less'
export default class extends React.Component {
componentDidMount() {
super.componentDidMount && super.componentDidMount()
$('#sp-border-colorpicker').spectrum({
color: this.props.currentStyle.borderColor,
showAlpha: true,
showInput: true,
allowEmpty: true,
preferredFormat: 'rgb',
change: tinycolor => {
this.props.updateStyle({
borderColor: tinycolor && tinycolor.toRgbString()
})
}
})
}
componentWillUnmount(){
super.componentWillUnmount && super.componentWillUnmount()
$('#sp-border-colorpicker').spectrum('destroy')
}
componentDidUpdate() {
super.componentDidUpdate && super.componentDidUpdate()
$('#sp-border-colorpicker').spectrum(
'set',
this.props.currentStyle.borderColor
)
}
parseBorder() {
let border = {
width: { components: [] },
style: this.props.currentStyle.borderStyle,
radius: { components: [] }
}
try {
let widthComponentsRaw =
this.props.currentStyle.borderWidth.trim() === ''
? null
: this.props.currentStyle.borderWidth.split(' ')
border.width.components = widthComponentsRaw.map((e, i) => {
let lengthMatch = e.trim().match(/(\d+)(\D+)/)
if (lengthMatch) {
return {
length: parseInt(lengthMatch[1]),
uom: lengthMatch[2]
}
} else {
return e
}
})
} catch (ex) {}
try {
let radiusComponentsRaw =
this.props.currentStyle.borderRadius.trim() === ''
? null
: this.props.currentStyle.borderRadius.split(' ')
border.radius.components = radiusComponentsRaw.map((e, i) => {
let lengthMatch = e.trim().match(/(\d+)(\D+)/)
if (lengthMatch) {
return {
length: parseInt(lengthMatch[1]),
uom: lengthMatch[2]
}
} else {
return e
}
})
} catch (ex) {}
return border
}
composeBorder(parsedBorder) {
let borderStyleObject = { borderStyle: parsedBorder.style }
try {
borderStyleObject.borderWidth = parsedBorder.width.components
.reduce((pv, cv, ci) => {
return pv + ' ' + (typeof cv == 'string' ? cv : cv.length + cv.uom)
}, '')
.trim()
} catch (ex) {}
try {
borderStyleObject.borderRadius = parsedBorder.radius.components
.reduce((pv, cv) => {
return pv + ' ' + (typeof cv == 'string' ? cv : cv.length + cv.uom)
}, '')
.trim()
} catch (ex) {}
return borderStyleObject
}
onChangeStyle = newStyle => {
let border = this.parseBorder()
border.style = newStyle
this.props.updateStyle(this.composeBorder(border))
}
onChangeWidthComponentCnt = newCnt => {
let border = this.parseBorder()
let diff = newCnt - border.width.components.length
if (diff > 0) {
let i = 0
while (i < diff) {
border.width.components.push({ length: 0, uom: 'px' })
i++
}
} else {
border.width.components.splice(newCnt, -diff)
}
this.props.updateStyle(this.composeBorder(border))
}
onChangeWidthComponent = (i, prop, newVal) => {
let border = this.parseBorder()
border.width.components[i][prop] =
newVal instanceof Object ? newVal.target.value : newVal
this.props.updateStyle(this.composeBorder(border))
}
onChangeRadiusComponentCnt = newCnt => {
let border = this.parseBorder()
let diff = newCnt - border.radius.components.length
if (diff > 0) {
let i = 0
while (i < diff) {
border.radius.components.push({ length: 0, uom: 'px' })
i++
}
} else {
border.radius.components.splice(newCnt, -diff)
}
this.props.updateStyle(this.composeBorder(border))
}
onChangeRadiusComponent = (i, prop, newVal) => {
let border = this.parseBorder()
border.radius.components[i][prop] =
newVal instanceof Object ? newVal.target.value : newVal
this.props.updateStyle(this.composeBorder(border))
}
render() {
let border = this.parseBorder()
let borderWidthComponents =
border.width.components &&
border.width.components.map((e, i) => {
return (
<div className="col-xs-3" key={i} style={{ display: 'inline' }}>
<input
value={e.length}
size={1}
onChange={this.onChangeWidthComponent.bind(null, i, 'length')}
/>
<DropdownList
data={['px', 'em']}
value={e.uom}
onChange={this.onChangeWidthComponent.bind(null, i, 'uom')}
/>
</div>
)
})
let borderRadiusComponents =
border.radius.components &&
border.radius.components.map((e, i) => {
return (
<div className="col-xs-3" key={i} style={{ display: 'inline' }}>
<input
value={e.length}
size={1}
onChange={this.onChangeRadiusComponent.bind(null, i, 'length')}
/>
<DropdownList
data={['px', 'em', '%']}
value={e.uom}
onChange={this.onChangeRadiusComponent.bind(null, i, 'uom')}
/>
</div>
)
})
return (
<div className="container-fluid sp-border-editor">
<div className="row">
<div className="col-xs-1">Width</div>
<div className="col-xs-11">
<DropdownList
data={[0, 1, 2, 3, 4]}
value={border.width.components && border.width.components.length}
onChange={this.onChangeWidthComponentCnt}
/>{' '}
components
</div>
</div>
<div className="row">
<div className="col-xs-1" />
<div className="col-xs-11 row">
{borderWidthComponents}
</div>
</div>
<div className="row">
<div className="col-xs-1">Style</div>
<div className="col-xs-11">
<DropdownList
data={[
'none',
'hidden',
'dotted',
'dashed',
'solid',
'double',
'groove',
'ridge',
'inset',
'outset'
]}
value={border.style}
onChange={this.onChangeStyle}
className="sp-style-dropdown"
/>
</div>
</div>
<div className="row">
<div className="col-xs-1">Color</div>
<div className="col-xs-11">
<input id="sp-border-colorpicker" />
</div>
</div>
<div className="row">
<div className="col-xs-1">Radius</div>
<div className="col-xs-11">
<DropdownList
data={[0, 1, 2, 3, 4]}
value={
border.radius.components && border.radius.components.length
}
onChange={this.onChangeRadiusComponentCnt}
/>{' '}
components
</div>
</div>
<div className="row">
<div className="col-xs-1" />
<div className="col-xs-11 row">
{borderRadiusComponents}
</div>
</div>
</div>
)
}
}
|
raphaelmue/financer
|
backend/org.financer.util/src/main/java/module-info.java
|
<reponame>raphaelmue/financer
module org.financer.util {
exports org.financer.util.collections;
exports org.financer.util.validation;
exports org.financer.util.mapping;
exports org.financer.util.security;
requires commons.beanutils;
requires java.validation;
requires modelmapper;
}
|
devshop2019/mixlyTest
|
arduino/portable/sketchbook/libraries/RF24/utility/ATXMegaD3/gpio_helper.c
|
<filename>arduino/portable/sketchbook/libraries/RF24/utility/ATXMegaD3/gpio_helper.c
/*
* gpio_helper.c
*
* Created: 22/1/2016 15:28:48
* Author: akatran
*/
#include "gpio_helper.h"
/**
* Get the port corresponding in portnum. Default is PORTC.
*/
PORT_t* GPIO_getPort(int pinnum, uint8_t* pin_bm)
//PORT_t * GPIO_getPort(int portnum)
{
PORT_t* port = &PORTC;
if ((pinnum >= XMEGA_PORTA_PIN0) && (pinnum <= XMEGA_PORTA_PIN7)) {
port = &PORTA;
*pin_bm = (1 << pinnum);
} else if ((pinnum >= XMEGA_PORTB_PIN0) && (pinnum <= XMEGA_PORTB_PIN7)) {
port = &PORTB;
*pin_bm = (1 << (pinnum - 8));
} else if ((pinnum >= XMEGA_PORTC_PIN0) && (pinnum <= XMEGA_PORTC_PIN7)) {
port = &PORTC;
*pin_bm = (1 << (pinnum - 16));
} else if ((pinnum >= XMEGA_PORTD_PIN0) && (pinnum <= XMEGA_PORTD_PIN7)) {
port = &PORTD;
*pin_bm = (1 << (pinnum - 24));
} else if ((pinnum >= XMEGA_PORTE_PIN0) && (pinnum <= XMEGA_PORTE_PIN7)) {
port = &PORTE;
*pin_bm = (1 << (pinnum - 32));
} else if ((pinnum >= XMEGA_PORTF_PIN0) && (pinnum <= XMEGA_PORTF_PIN7)) {
port = &PORTF;
*pin_bm = (1 << (pinnum - 40));
}
return port;
}
|
xaque208/znet
|
modules/telemetry/telemetry.pb.go
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.17.3
// source: modules/telemetry/telemetry.proto
package telemetry
import (
proto "github.com/golang/protobuf/proto"
inventory "github.com/xaque208/znet/modules/inventory"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
var File_modules_telemetry_telemetry_proto protoreflect.FileDescriptor
var file_modules_telemetry_telemetry_proto_rawDesc = []byte{
0x0a, 0x21, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x73, 0x2f, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65,
0x74, 0x72, 0x79, 0x2f, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x12, 0x09, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x1a, 0x21,
0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x73, 0x2f, 0x69, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72,
0x79, 0x2f, 0x69, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x32, 0x81, 0x01, 0x0a, 0x09, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x12,
0x39, 0x0a, 0x0f, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x49, 0x4f, 0x54, 0x44, 0x65, 0x76, 0x69,
0x63, 0x65, 0x12, 0x14, 0x2e, 0x69, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x49,
0x4f, 0x54, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x1a, 0x10, 0x2e, 0x69, 0x6e, 0x76, 0x65, 0x6e,
0x74, 0x6f, 0x72, 0x79, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x39, 0x0a, 0x0f, 0x52, 0x65,
0x70, 0x6f, 0x72, 0x74, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x49, 0x44, 0x12, 0x14, 0x2e,
0x69, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72,
0x6b, 0x49, 0x44, 0x1a, 0x10, 0x2e, 0x69, 0x6e, 0x76, 0x65, 0x6e, 0x74, 0x6f, 0x72, 0x79, 0x2e,
0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x2c, 0x5a, 0x2a, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x71, 0x75, 0x65, 0x32, 0x30, 0x38, 0x2f, 0x7a, 0x6e, 0x65,
0x74, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x73, 0x2f, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65,
0x74, 0x72, 0x79, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var file_modules_telemetry_telemetry_proto_goTypes = []interface{}{
(*inventory.IOTDevice)(nil), // 0: inventory.IOTDevice
(*inventory.NetworkID)(nil), // 1: inventory.NetworkID
(*inventory.Empty)(nil), // 2: inventory.Empty
}
var file_modules_telemetry_telemetry_proto_depIdxs = []int32{
0, // 0: telemetry.Telemetry.ReportIOTDevice:input_type -> inventory.IOTDevice
1, // 1: telemetry.Telemetry.ReportNetworkID:input_type -> inventory.NetworkID
2, // 2: telemetry.Telemetry.ReportIOTDevice:output_type -> inventory.Empty
2, // 3: telemetry.Telemetry.ReportNetworkID:output_type -> inventory.Empty
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_modules_telemetry_telemetry_proto_init() }
func file_modules_telemetry_telemetry_proto_init() {
if File_modules_telemetry_telemetry_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_modules_telemetry_telemetry_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_modules_telemetry_telemetry_proto_goTypes,
DependencyIndexes: file_modules_telemetry_telemetry_proto_depIdxs,
}.Build()
File_modules_telemetry_telemetry_proto = out.File
file_modules_telemetry_telemetry_proto_rawDesc = nil
file_modules_telemetry_telemetry_proto_goTypes = nil
file_modules_telemetry_telemetry_proto_depIdxs = nil
}
|
HAPwebsite/Brackets-Extensions
|
brackets-beautify/nls/root/strings.js
|
define({
BEAUTIFY: 'Beautify',
BEAUTIFY_ON_SAVE: 'Beautify on Save',
BEAUTIFY_ON_SAVE_DESC: 'true to Beautify file on Save',
PREF_BEAUTIFIERS_NAME: 'External Beautifiers',
PREF_BEAUTIFIERS_DESC: 'External Beautifiers, see https://github.com/brackets-beautify/brackets-beautify#external-formatters',
PREF_LANGUAGES_NAME: 'Beautifier-Language-Mapping',
PREF_LANGUAGES_DESC: 'Beautifier-Language-Mapping, see https://github.com/brackets-beautify/brackets-beautify#configure-languages',
PREF_DIALOG_NAME: 'Hide dialog for unsupported languages',
PREF_DIALOG_DESC: 'true to hide the dialog warning about unsupported languages',
UNSUPPORTED_TITLE: 'Unsupported Language',
UNSUPPORTED_MESSAGE: 'This language is not supported.<br />Supported languages are JavaScript, JSON, HTML, XML, SVG, HTML in PHP, Embedded JavaScript, Handlebars, CSS, SCSS, and LESS.',
CONFIGURE_LINKS: 'See the README for <a href="https://github.com/brackets-beautify/brackets-beautify#configure-languages">configuring languages</a> and <a href="https://github.com/brackets-beautify/brackets-beautify#external-formatters">adding new formatters</a>.',
UNSUPPORTED_CHECKBOX: 'Don\'t show this dialog in the future'
});
|
FUNKVESSEL/ps_cpp_recipes
|
recipes/thirdparty/psapi/pica_sp/SPStrngs.h
|
<filename>recipes/thirdparty/psapi/pica_sp/SPStrngs.h
/***********************************************************************/
/* */
/* SPStrngs.h */
/* */
/* Copyright 1995-2006 Adobe Systems Incorporated. */
/* All Rights Reserved. */
/* */
/* Patents Pending */
/* */
/* NOTICE: All information contained herein is the property of Adobe */
/* Systems Incorporated. Many of the intellectual and technical */
/* concepts contained herein are proprietary to Adobe, are protected */
/* as trade secrets, and are made available only to Adobe licensees */
/* for their internal use. Any reproduction or dissemination of this */
/* software is strictly forbidden unless prior written permission is */
/* obtained from Adobe. */
/* */
/***********************************************************************/
#ifndef __SPStrings__
#define __SPStrings__
/*******************************************************************************
**
** Imports
**
**/
#include "SPTypes.h"
#ifdef __cplusplus
extern "C" {
#endif
/*******************************************************************************
**
** Constants
**
**/
/** PICA strings suite name */
#define kSPStringsSuite "SP Strings Suite"
/** PICA strings suite version */
#define kSPStringsSuiteVersion 2
/** Globally available PICA strings resources.
@see \c #SPRuntimeSuite::GetRuntimeStringPool(). */
#define kSPRuntimeStringPool ((SPStringPoolRef)NULL)
/*******************************************************************************
**
** Types
**
**/
/* If you override the default string pool handler by defining host proc routines,
* how the string pool memory allocation and searching is done is up to you. As an example,
* the structure below is similar to what Sweet Pea uses for its default string pool
* routines. The pool is a sorted list of strings of number count, kept in memory referenced
* by the heap field.
*
* typedef struct SPStringPool {
*
* SPPoolHeapRef heap;
* int32 count;
*
* } SPStringPool;
*/
/** Opaque reference to a string pool. Access with the \c #SPStringsSuite. */
typedef struct SPStringPool *SPStringPoolRef;
/*******************************************************************************
**
** Suite
**
**/
/** @ingroup Suites
This suite allows you to work with the PICA string pool.
PICA manages a string pool, which provides an efficient central
storage space for C strings. When a string is placed in the pool, PICA
checks whether it already exists in the pool, and if so, returns a
pointer to the existing string. If not, it copies the string into the pool,
and returns a pointer to the copy.
This mechanisms atomizes the strings. Because each string exists in
only one place, strings can be compared by address, rather than character
by character, and string searches are made much more efficient.
\li Acquire this suite using \c #SPBasicSuite::AcquireSuite() with the constants
\c #kSPStringsSuite and \c #kSPStringsSuiteVersion.
*/
typedef struct SPStringsSuite {
/** Creates a new string pool and allocates an initial block of memory for
its strings. You can also access PICA's global string pool,
using \c #SPRuntimeSuite::GetRuntimeStringPool().
@param stringPool [out] A buffer in which to return the new string pool reference.
*/
SPAPI SPErr (*AllocateStringPool)( SPStringPoolRef *stringPool );
/** Frees the memory used for a string pool created with \c #AllocateStringPool().
Do not free the global string pool (\c #kSPRuntimeStringPool).
@param stringPool The string pool reference.
*/
SPAPI SPErr (*FreeStringPool)( SPStringPoolRef stringPool );
/** Adds a string to a string pool, or, if the string has already been added
to the pool, retrieves a reference to the pooled string.
@param stringPool The string pool reference.
@param string The string.
@param wString [out] A buffer in which to return the address of
the atomized string in the pool.
*/
SPAPI SPErr (*MakeWString)( SPStringPoolRef stringPool, const char *string, const char **wString );
} SPStringsSuite;
SPAPI SPErr SPAllocateStringPool( SPStringPoolRef *stringPool );
SPAPI SPErr SPFreeStringPool( SPStringPoolRef stringPool );
SPAPI SPErr SPMakeWString( SPStringPoolRef stringPool, const char *string, const char **wString );
#ifdef __cplusplus
}
#endif
#endif
|
ChanTerelLy/partnerweb3
|
call_center/migrations/0004_auto_20191221_0324.py
|
# Generated by Django 2.2.1 on 2019-12-21 00:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('call_center', '0003_subscribers_called'),
]
operations = [
migrations.AddField(
model_name='subscribers',
name='call_time',
field=models.TextField(default=''),
preserve_default=False,
),
migrations.AddField(
model_name='subscribers',
name='status_result',
field=models.TextField(default=''),
preserve_default=False,
),
]
|
King0987654/windows2000
|
private/windows/shell/snapins/devmgr/snapin/machine.cpp
|
<reponame>King0987654/windows2000
/*++
Copyright (C) 1997-1999 Microsoft Corporation
Module Name:
machine.cpp
Abstract:
This module implements CDevInfoList, CMachine and CMachineList
Author:
<NAME> (williamh) created
Revision History:
--*/
#include "devmgr.h"
extern "C" {
#include <initguid.h>
#include <dbt.h>
#include <devguid.h>
#include <wdmguid.h>
}
//
//private setupapi export
//
DWORD
pSetupGuidFromString(
PWCHAR GuidString,
LPGUID Guid
);
CONST TCHAR* DEVMGR_NOTIFY_CLASS_NAME = TEXT("DevMgrNotifyClass");
CONST TCHAR* DEVMGR_REFRESH_MSG = TEXT("DevMgrRefreshOn");
CONST TCHAR* YES = TEXT("Yes");
CONST TCHAR* NO = TEXT("No");
//
// This guid is used for file signing/verification.
//
GUID DriverVerifyGuid = DRIVER_ACTION_VERIFY;
//the constant is the size we use to allocate GUID list from within
//stack when we have to build a GUID list. The aim of this is
//that buiding a guid list take time and in many case, a minimum
// buffer should retrive all of them. We do not want to get
// the size first, allocate buffer and get it again.
// 64 looks to be fair enough value because there are not
// many classes out there today(and maybe, in the future).
const int GUID_LIST_INIT_SIZE = 64;
#if DBG
#define DUMP_DEVICETREE 0x00000001
#define DUMP_CLASSDEVICES 0x00000002
#define DUMP_COOKIE 0x00000004
#define DUMP_DEVNODETREE 0x00000008
#define DUMP_SCOPEITEM_TREE 0x00000040
DWORD g_Dump = 0;
#endif
// CDevInfoList implementation
BOOL
CDevInfoList::DiGetExtensionPropSheetPage(
PSP_DEVINFO_DATA DevData,
LPFNADDPROPSHEETPAGE pfnAddPropSheetPage,
DWORD PageType,
LPARAM lParam
)
{
SP_PROPSHEETPAGE_REQUEST PropPageRequest;
LPFNADDPROPSHEETPAGES AddPropPages;
PropPageRequest.cbSize = sizeof(PropPageRequest);
PropPageRequest.PageRequested = PageType;
PropPageRequest.DeviceInfoSet = m_hDevInfo;
PropPageRequest.DeviceInfoData = DevData;
if (SPPSR_SELECT_DEVICE_RESOURCES == PageType)
{
HINSTANCE hModule = ::GetModuleHandle(TEXT("setupapi.dll"));
if (hModule)
{
AddPropPages = (LPFNADDPROPSHEETPAGES)GetProcAddress(hModule, "ExtensionPropSheetPageProc");
if (AddPropPages)
{
if (AddPropPages(&PropPageRequest, pfnAddPropSheetPage, lParam))
return TRUE;
}
}
}
return FALSE;
}
BOOL
CDevInfoList::InstallDevInst(
HWND hwndParent,
LPCTSTR DeviceId,
BOOL UpdateDriver,
DWORD* pReboot
)
{
BOOL Result = FALSE;
HINSTANCE hLib = LoadLibrary(TEXT("newdev.dll"));
LPFNINSTALLDEVINST InstallDevInst;
if (hLib)
{
InstallDevInst = (LPFNINSTALLDEVINST)GetProcAddress(hLib, "InstallDevInst");
if (InstallDevInst)
Result = (*InstallDevInst)(hwndParent, DeviceId, UpdateDriver,
pReboot);
}
if (hLib)
FreeLibrary(hLib);
return Result;
}
DWORD
CDevInfoList::DiGetFlags(
PSP_DEVINFO_DATA DevData
)
{
SP_DEVINSTALL_PARAMS dip;
dip.cbSize = sizeof(dip);
if (DiGetDeviceInstallParams(DevData, &dip))
{
return dip.Flags;
}
return 0;
}
DWORD
CDevInfoList::DiGetExFlags(
PSP_DEVINFO_DATA DevData
)
{
SP_DEVINSTALL_PARAMS dip;
dip.cbSize = sizeof(dip);
if (DiGetDeviceInstallParams(DevData, &dip))
{
return dip.FlagsEx;
}
return 0;
}
BOOL
CDevInfoList::DiTurnOnDiFlags(
PSP_DEVINFO_DATA DevData,
DWORD FlagsMask
)
{
SP_DEVINSTALL_PARAMS dip;
dip.cbSize = sizeof(dip);
if (DiGetDeviceInstallParams(DevData, &dip))
{
dip.Flags |= FlagsMask;
return DiSetDeviceInstallParams(DevData, &dip);
}
return FALSE;
}
BOOL
CDevInfoList::DiTurnOffDiFlags(
PSP_DEVINFO_DATA DevData,
DWORD FlagsMask
)
{
SP_DEVINSTALL_PARAMS dip;
dip.cbSize = sizeof(dip);
if (DiGetDeviceInstallParams(DevData, &dip))
{
dip.Flags &= ~FlagsMask;
return DiSetDeviceInstallParams(DevData, &dip);
}
return FALSE;
}
BOOL
CDevInfoList::DiTurnOnDiExFlags(
PSP_DEVINFO_DATA DevData,
DWORD FlagsMask
)
{
SP_DEVINSTALL_PARAMS dip;
dip.cbSize = sizeof(dip);
if (DiGetDeviceInstallParams(DevData, &dip))
{
dip.FlagsEx |= FlagsMask;
return DiSetDeviceInstallParams(DevData, &dip);
}
return FALSE;
}
BOOL
CDevInfoList::DiTurnOffDiExFlags(
PSP_DEVINFO_DATA DevData,
DWORD FlagsMask
)
{
SP_DEVINSTALL_PARAMS dip;
dip.cbSize = sizeof(dip);
if (DiGetDeviceInstallParams(DevData, &dip))
{
dip.FlagsEx &= ~FlagsMask;
return DiSetDeviceInstallParams(DevData, &dip);
}
return FALSE;
}
void
CDevInfoList::DiDestroyDeviceInfoList()
{
if (INVALID_HANDLE_VALUE != m_hDevInfo)
{
SetupDiDestroyDeviceInfoList(m_hDevInfo);
m_hDevInfo = INVALID_HANDLE_VALUE;
}
}
BOOL
CDevInfoList::DiGetDeviceDescription(
PSP_DEVINFO_DATA DevData,
TCHAR* pBuffer,
DWORD Size,
DWORD* pRequiredSize
)
{
//
if (Size && !pBuffer)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
DWORD ActualSize;
BOOL Result;
ActualSize = 0;
Result = DiGetDeviceRegistryProperty(DevData, SPDRP_FRIENDLYNAME, NULL,
(PBYTE)pBuffer, Size * sizeof(TCHAR),
&ActualSize);
if (!Result && ERROR_INSUFFICIENT_BUFFER != GetLastError())
{
// no friendly name available, use device's description
ActualSize = 0;
Result = DiGetDeviceRegistryProperty(DevData, SPDRP_DEVICEDESC, NULL,
(PBYTE)pBuffer,
Size * sizeof(TCHAR),
&ActualSize);
}
if (pRequiredSize)
*pRequiredSize = ActualSize / sizeof(TCHAR);
return Result;
}
BOOL
CDevInfoList::DiGetDeviceDescriptionString(
PSP_DEVINFO_DATA DevData,
String& str
)
{
// first probe the size
DWORD RequiredSize = 0;
TCHAR Desc[LINE_LEN];
if (DiGetDeviceDescription(DevData, Desc, ARRAYLEN(Desc), &RequiredSize))
{
str = Desc;
return TRUE;
}
return FALSE;
}
BOOL
CDevInfoList::DiGetDeviceMFGString(
PSP_DEVINFO_DATA DevData,
TCHAR* pBuffer,
DWORD Size,
DWORD* pRequiredSize
)
{
if (Size && !pBuffer)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
DWORD ActualSize = 0;
BOOL Result;
Result = DiGetDeviceRegistryProperty(DevData, SPDRP_MFG, NULL,
(PBYTE)pBuffer,
Size * sizeof(TCHAR),
&ActualSize);
if (pRequiredSize)
*pRequiredSize = ActualSize / sizeof(TCHAR);
return Result;
}
BOOL
CDevInfoList::DiGetDeviceMFGString(
PSP_DEVINFO_DATA DevData,
String& str
)
{
DWORD RequiredSize = 0;
TCHAR MFG[LINE_LEN];
if (DiGetDeviceMFGString(DevData, MFG, ARRAYLEN(MFG), &RequiredSize))
{
str = MFG;
return TRUE;
}
return FALSE;
}
BOOL
CDevInfoList::DiGetDeviceIDString(
PSP_DEVINFO_DATA DevData,
TCHAR* pBuffer,
DWORD Size,
DWORD* pRequiredSize
)
{
if (Size && !pBuffer)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
DWORD ActualSize = 0;
BOOL Result;
Result = DiGetDeviceRegistryProperty(DevData, SPDRP_HARDWAREID, NULL,
(PBYTE) pBuffer,
Size * sizeof(TCHAR), &ActualSize);
if (pRequiredSize)
*pRequiredSize = ActualSize / sizeof(TCHAR);
return Result;
}
BOOL
CDevInfoList::DiGetDeviceIDString(
PSP_DEVINFO_DATA DevData,
String& str
)
{
BOOL Result;
DWORD RequiredSize = 0;
TCHAR DeviceId[MAX_DEVICE_ID_LEN];
if (DiGetDeviceIDString(DevData, DeviceId, ARRAYLEN(DeviceId), &RequiredSize))
{
str = DeviceId;
return TRUE;
}
return FALSE;
}
/////////////////////////////////////////////////////////////////////
//// CMachine implementation
////
//
// For every single instance of DevMgr.dll, we maintain a CMachine list
// from which different instances of IComponentData(and IComponent) will
// attach to. The objects created(CDevice, Class, HDEVINFO and etc) are
// shared by all the attached IComponentData and IComponent(the implementation
// use CFolder as the controlling identify).
// Everything changed to the CMachine or one of its object will inform
// all the attached CFolders which would pass the information down to their
// sub-objects(CResultView).
// Imaging that you have two Device Manager window in the same console
// and you do a refresh on one the window. The other window must also
// do a refresh after the first one is done. Since both windows shares
// the same machine(and will get the same notification when machine states
// changed), we can keep the two windows in sync.
CMachine::CMachine(
LPCTSTR pMachineName
)
{
InitializeCriticalSection(&m_CriticalSection);
//
// determine if the process has SE_LOAD_DRIVER_NAME privileges
//
g_HasLoadDriverNamePrivilege = DoesUserHavePrivilege((PCTSTR)SE_LOAD_DRIVER_NAME);
m_RefreshDisableCounter = 0;
m_RefreshPending = FALSE;
m_pComputer = NULL;
m_hMachine = NULL;
m_Initialized = FALSE;
TCHAR LocalName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD dwSize = sizeof(LocalName) / sizeof(TCHAR);
if (!GetComputerName(LocalName, &dwSize)) {
LocalName[0] = _T('\0');
}
m_strMachineFullName.Empty();
m_strMachineDisplayName.Empty();
// skip over any leading '\' chars
if (pMachineName && _T('\0') != *pMachineName)
{
int len = lstrlen(pMachineName);
ASSERT(len >= 3 && _T('\\') == pMachineName[0] && _T('\\') == pMachineName[1]);
m_strMachineDisplayName = &pMachineName[2];
m_strMachineFullName = pMachineName;
m_IsLocal = (0 == m_strMachineDisplayName.CompareNoCase(LocalName));
}
else
{
// local machine
m_strMachineDisplayName = LocalName;
m_strMachineFullName = TEXT("\\\\") + m_strMachineDisplayName;
m_IsLocal = TRUE;
}
m_hwndNotify = NULL;
m_msgRefresh = 0;
m_ShowNonPresentDevices = FALSE;
TCHAR Buffer[MAX_PATH];
DWORD BufferLen;
//
// If the environment variable DEVMGR_SHOW_NONPRESENT_DEVICES does exist and it
// is not 0 then we will show Phantom devices.
//
if (((BufferLen = ::GetEnvironmentVariable(TEXT("DEVMGR_SHOW_NONPRESENT_DEVICES"),
Buffer,
sizeof(Buffer)/sizeof(TCHAR))) != 0) &&
((BufferLen > 1) ||
(lstrcmp(Buffer, TEXT("0"))))) {
m_ShowNonPresentDevices = TRUE;
}
}
BOOL
CMachine::Initialize(
HWND hwndParent,
LPCTSTR DeviceId
)
{
DEBUGBREAK_ON(DEBUG_OPTIONS_BREAKON_INITMACHINE);
m_hwndParent = hwndParent;
if (m_Initialized)
return TRUE;
if (DeviceId && _T('\0') == *DeviceId)
DeviceId = NULL;
#ifdef DEVL
//
// Initialize logging for this machine
//
CSafeRegistry regDevMgr;
DWORD Type;
DWORD Size;
Size = sizeof(m_LoggingMask);
String strLogging;
if (regDevMgr.Open(HKEY_LOCAL_MACHINE, REG_PATH_DEVICE_MANAGER))
{
if (regDevMgr.GetValue(REG_VAL_DEVMGR_LOGGING_MASK, &Type, (BYTE*)&m_LoggingMask, &Size) &&
REG_DWORD == Type && sizeof(Size) == Size && m_LoggingMask)
{
// create a file under the temporary subdirectory. The file
// name is the machine name itself with extension "dmlog"
//
TCHAR LogFile[MAX_PATH * 2];
GetTempPath(ARRAYLEN(LogFile), LogFile);
lstrcat(LogFile, TEXT("\\"));
lstrcat(LogFile, GetMachineDisplayName());
lstrcat(LogFile, TEXT(".dmlog"));
m_LogFile.Create(LogFile);
}
}
#endif
HCURSOR hCursorOld;
hCursorOld = SetCursor(LoadCursor(NULL, IDC_WAIT));
BOOL Result = FALSE;
if (CreateClassesAndDevices(DeviceId))
{
#if DBG
if (g_Dump & DUMP_CLASSDEVICES)
DumpClassDevices();
if (g_Dump & DUMP_DEVICETREE)
DumpDeviceTree();
if (g_Dump & DUMP_DEVNODETREE)
DumpDevNodeTree();
#endif
m_Initialized = TRUE;
Result = TRUE;
}
// Is it really necessary to create this window when we are
// creating a single device?
// create a data window to monitor WM_DEVICECHANGE message
if (hCursorOld)
SetCursor(hCursorOld);
// we are ready for device change notification, create the notify window
//
return CreateNotifyWindow();
}
BOOL
CMachine::ScheduleRefresh()
{
Lock();
// Only queue the the request if there is no requests outstanding
// and we have a valid window handle/message to the notify window.
if (!m_RefreshPending && m_hwndNotify && m_msgRefresh)
{
// broadcast the message so that every instance runs on
// the computer get the notification
::PostMessage(HWND_BROADCAST, m_msgRefresh, 0, 0);
}
Unlock();
return TRUE;
}
//
// This function creates a data window to receive WM_DEVICECHANGE notification
// so that we can refresh the device tree. It also registers a private
// message so that anybody can post a refresh request.
//
BOOL
CMachine::CreateNotifyWindow()
{
WNDCLASS wndClass;
//lets see if the class has been registered.
if (!GetClassInfo(g_hInstance, DEVMGR_NOTIFY_CLASS_NAME, &wndClass))
{
// register the class
memset(&wndClass, 0, sizeof(wndClass));
wndClass.lpfnWndProc = dmNotifyWndProc;
wndClass.hInstance = g_hInstance;
wndClass.lpszClassName = DEVMGR_NOTIFY_CLASS_NAME;
if (!RegisterClass(&wndClass))
return FALSE;
}
// register a private message for refresh. The name must contain
// the target machine name so that every machine has its own message.
String strMsg = DEVMGR_REFRESH_MSG;
strMsg += m_strMachineDisplayName;
m_msgRefresh = RegisterWindowMessage(strMsg);
if (m_msgRefresh)
{
// Create a data window.
m_hwndNotify = CreateWindowEx(WS_EX_TOOLWINDOW, DEVMGR_NOTIFY_CLASS_NAME,
TEXT(""),
WS_DLGFRAME|WS_BORDER|WS_DISABLED,
CW_USEDEFAULT, CW_USEDEFAULT,
0, 0, NULL, NULL, g_hInstance, (void*)this);
return (NULL != m_hwndNotify);
}
return FALSE;
}
//
// This is the WM_DEVICECHANGE window procedure running in the main thread
// context. It listens to two messages:
// (1). WM_DEVICECHANGE broadcasted by Configuration Manager on device
// addition/removing.
// (2). Private refresh message broadcasted by different instance
// of Device Manager targeting on the same machine.
// On WM_CREATE, we participate the WM_DEVICECHANGE notification chain
// while on WM_DESTROY, we detach oursleves from the chain.
// There are occasions that we have to detach and re-attach to the
// chain duing the window life time, for example, during device uninstallation
// or during re-enumeration. The EnableFresh function is the place
// that does the attach/detach.
//
//
LRESULT
dmNotifyWndProc(
HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
CMachine* pThis;
pThis = (CMachine*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
// special case for private refresh message
if (pThis && uMsg == pThis->m_msgRefresh)
{
pThis->LOGMISCINFO(TEXT("Private refresh message\n"));
pThis->Refresh();
return FALSE;
}
switch (uMsg)
{
case WM_CREATE:
{
pThis = (CMachine*)((CREATESTRUCT*)lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pThis);
break;
}
case WM_DEVICECHANGE:
{
if (DBT_DEVNODES_CHANGED == wParam)
{
pThis->LOGMISCINFO(TEXT("WM_DEVICECHANGE\n"));
// While we are in WM_DEVICECHANGE context,
// no CM apis can be called because it would
// deadlock. Here, we schedule a timer so that
// we can handle the message later on.
SetTimer(hWnd, DM_NOTIFY_TIMERID, 1000, NULL);
}
break;
}
case WM_TIMER:
{
if (DM_NOTIFY_TIMERID == wParam)
{
KillTimer(hWnd, DM_NOTIFY_TIMERID);
ASSERT(pThis);
pThis->ScheduleRefresh();
}
break;
}
default:
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
//
// This function attaches the given CFolder to the class.
// An attached CFolder will get notified when there are state
// changes in the class(Refresh, property changes, for example).
//
BOOL
CMachine::AttachFolder(
CFolder* pFolder
)
{
ASSERT(pFolder);
if (!IsFolderAttached(pFolder))
{
pFolder->MachinePropertyChanged(this);
m_listFolders.AddTail(pFolder);
}
return TRUE;
}
BOOL
CMachine::IsFolderAttached(
CFolder* pFolder
)
{
if (!m_listFolders.IsEmpty())
{
POSITION pos = m_listFolders.GetHeadPosition();
while (NULL != pos)
{
if (pFolder == m_listFolders.GetNext(pos))
return TRUE;
}
}
return FALSE;
}
void
CMachine::DetachFolder(
CFolder* pFolder
)
{
int nFolders = m_listFolders.GetCount();
for (int i = 0; i < nFolders; i++)
{
CFolder* pFolderToTest;
POSITION pos = m_listFolders.FindIndex(i);
pFolderToTest = m_listFolders.GetAt(pos);
if (pFolderToTest == pFolder)
{
m_listFolders.RemoveAt(pos);
break;
}
}
}
BOOL
CMachine::AttachPropertySheet(
HWND hwndPropertySheet
)
{
ASSERT(hwndPropertySheet);
m_listPropertySheets.AddTail(hwndPropertySheet);
return TRUE;
}
void
CMachine::DetachPropertySheet(
HWND hwndPropertySheet
)
{
int nPropertySheets = m_listPropertySheets.GetCount();
for (int i = 0; i < nPropertySheets; i++)
{
HWND hwndPropertySheetToTest;
POSITION pos = m_listPropertySheets.FindIndex(i);
hwndPropertySheetToTest = m_listPropertySheets.GetAt(pos);
if (hwndPropertySheetToTest == hwndPropertySheet)
{
m_listPropertySheets.RemoveAt(pos);
break;
}
}
}
CMachine::~CMachine()
{
//
// Turn off refresh. We need to do this in case there are any property
// sheets that are still active.
//
EnableRefresh(FALSE);
//
// We need to wait for all of the property sheets to be destroyed.
//
// We will check to see if there are any property pages still around, and
// if there is we will wait for 1 second and then check again. After 5
// seconds we will give up and just destroy the CMachine anyway.
//
int iSecondsCount = 0;
while (!m_listPropertySheets.IsEmpty() &&
(iSecondsCount++ < 10)) {
//
// Enumerate through all of the property sheets left and if IsWindow fails
// then pull them from the list, otherwise call DestroyWindow on them.
//
int nPropertySheets = m_listPropertySheets.GetCount();
for (int i = 0; i < nPropertySheets; i++)
{
HWND hwndPropertySheetToTest;
POSITION pos = m_listPropertySheets.FindIndex(i);
hwndPropertySheetToTest = m_listPropertySheets.GetAt(pos);
if (IsWindow(hwndPropertySheetToTest))
{
//
// There is still a valid window for this property sheet so
// call DestroyWindow on it.
//
::DestroyWindow(hwndPropertySheetToTest);
}
else
{
//
// There is no window for this property sheet so just remove
// it from the list
//
m_listPropertySheets.RemoveAt(pos);
}
}
//
// Sleep for .5 seconds and then try again. This will give the property pages time to
// finish up their work.
//
Sleep(500);
}
// if we have created a device change data window for this machine,
// destroy it.
if (m_hwndNotify && IsWindow(m_hwndNotify))
{
::DestroyWindow(m_hwndNotify);
m_hwndNotify = NULL;
}
DestroyClassesAndDevices();
if (!m_listFolders.IsEmpty())
{
m_listFolders.RemoveAll();
}
DeleteCriticalSection(&m_CriticalSection);
}
//
// This function destroys all the CClass and CDevice we ever created.
// No notification is sent for the attached folder
//
//
void
CMachine::DestroyClassesAndDevices()
{
LOGMISCINFO(TEXT("!!!!Destroy class and devices!!!!\n"));
if (m_pComputer)
{
delete m_pComputer;
m_pComputer = NULL;
}
if (!m_listDevice.IsEmpty())
{
POSITION pos = m_listDevice.GetHeadPosition();
while (NULL != pos)
{
CDevice* pDevice = m_listDevice.GetNext(pos);
delete pDevice;
}
m_listDevice.RemoveAll();
}
if (!m_listClass.IsEmpty())
{
POSITION pos = m_listClass.GetHeadPosition();
while (NULL != pos)
{
CClass* pClass = m_listClass.GetNext(pos);
delete pClass;
}
m_listClass.RemoveAll();
}
if (m_ImageListData.cbSize)
{
DiDestroyClassImageList(&m_ImageListData);
}
CDevInfoList::DiDestroyDeviceInfoList();
m_hMachine = NULL;
}
BOOL
CMachine::BuildClassesFromGuidList(
LPGUID GuidList,
DWORD Guids
)
{
DWORD Index;
CClass* pClass;
// build a list of CClass for each GUID.
for (Index = 0; Index < Guids; Index++)
{
SafePtr<CClass> ClassPtr;
pClass = new CClass(this, &GuidList[Index]);
ClassPtr.Attach(pClass);
m_listClass.AddTail(ClassPtr);
ClassPtr.Detach();
}
return TRUE;
}
//
// Create CClass and CDevice for this machine.
// If DeviceId is valid, this function will create the machine
// with ONLY ONE device(and its CClass)
//
// PERFBUG Optimize this function!!!!!!!
// This function is slow because SetupDiGetClassDevs can take a long
// time (over 1 sec of a 300Mhz machine).
// The other slow part is the call to DoNotCreateDevice which needs to
// go through the service manager for all legacy devnodes to see
// if they are Win32 services (which we don't display). This takes
// around 10ms to get this information from the service manager on
// a 300Mhz machine and their are almost 100 of these legacy devices.
// This means another second of time.
//
//
BOOL
CMachine::CreateClassesAndDevices(
LPCTSTR DeviceId
)
{
SC_HANDLE SCMHandle = NULL;
//preventing memory leak
ASSERT(NULL == m_pComputer);
ASSERT(INVALID_HANDLE_VALUE == m_hDevInfo);
ASSERT(NULL == m_hMachine);
// if the object is being created for a single device,
// create a empty device info list. We will add the
// device to the info list later.
if (DeviceId)
{
m_hDevInfo = DiCreateDeviceInfoList(NULL, m_hwndParent);
}
else
{
// we have to pull out the entire devices/classes set
// so create a device info list that contains all of them.
m_hDevInfo = DiGetClassDevs(NULL, NULL, m_hwndParent, DIGCF_ALLCLASSES | DIGCF_PROFILE);
}
// NULL != INVALID_HANDLE_VALUE. We checked both just be safe.
if(INVALID_HANDLE_VALUE == m_hDevInfo || NULL == m_hDevInfo)
{
LogLastError(TEXT("DiCreateDeviceInfoList"));
return FALSE;
}
SP_DEVINFO_LIST_DETAIL_DATA DevInfoDetailData;
DevInfoDetailData.cbSize = sizeof(DevInfoDetailData);
// use the HMACHINE returned from Setupapi so that
// every call we make to Cfgmgr32.dll will use the
// same HMACHINE. Two call of CM_Connect_Machine will
// return different hMachines even though they refer to
// the same machine name(and thus, different set of DEVNODE!).
// The catch is that we will be able to call Setuapi and cfgmgr32
// API without worrying about which hMachine to use.
//
if (DiGetDeviceInfoListDetail(&DevInfoDetailData))
{
m_hMachine = DevInfoDetailData.RemoteMachineHandle;
}
else
{
// unable to get the devinfo detail information.
// bugbug--- what should we do here?????
LogLastError(TEXT("DiGetDeviceInfoListDetail"));
m_hMachine = NULL;
// continue on
}
// get class image list data;
m_ImageListData.cbSize = sizeof(m_ImageListData);
if (DiGetClassImageList(&m_ImageListData))
{
// add extra icons
HICON hIcon;
if ((hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_DEVMGR))) != NULL)
{
m_ComputerIndex = ImageList_AddIcon(m_ImageListData.ImageList, hIcon);
DestroyIcon(hIcon);
}
if ((hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_RESOURCES))) != NULL)
{
m_ResourceIndex = ImageList_AddIcon(m_ImageListData.ImageList, hIcon);
DestroyIcon(hIcon);
}
}
else
{
LogLastError(TEXT("DiGetClassImageList"));
}
// if the object is created for a particular device,
// do not create the entire device list because it is
// a waste of time.
if (DeviceId)
{
SP_DEVINFO_DATA DevData;
GUID ClassGuid;
DevData.cbSize = sizeof(DevData);
if (DiOpenDeviceInfo(DeviceId, m_hwndParent, 0, &DevData) &&
CmGetClassGuid(DevData.DevInst, ClassGuid))
{
// create a CClass for the device(without CClass, no
// device can not be created).
CClass* pClass;
SafePtr<CClass> ClassPtr;
pClass = new CClass(this, &ClassGuid);
ClassPtr.Attach(pClass);
m_listClass.AddTail(ClassPtr); // may cause memory exception
// the class object has been inserted to the list
// it is safe now to detach the object from the smart pointer
// The class object will be deleted by the list
ClassPtr.Detach();
// create the device
SafePtr<CDevice> DevicePtr;
CDevice* pDevice;
pDevice = new CDevice(this, pClass, &DevData);
// guard the object
DevicePtr.Attach(pDevice);
m_listDevice.AddTail(DevicePtr);
// object added..
DevicePtr.Detach();
// AddDevice may cause memory exception. However, it is fine
// here because the object has been inserted to the device list.
// The class object should NOT delete the device object we pass
// to it: NEVER DELETE AN OBJECT IF IT IS PASSED IN AS A POINTER
// BECAUSE YOU DO NOT OWN IT!
pClass->AddDevice(pDevice);
}
// we should have one class and one device object. no more no less.
// we are done here.
return (1 == m_listClass.GetCount() && 1 == m_listDevice.GetCount());
}
// build class guid list
DWORD ClassGuids, GuidsRequired;
GuidsRequired = 0;
// we make a guess here to save us some time.
GUID LocalGuid[GUID_LIST_INIT_SIZE];
ClassGuids = GUID_LIST_INIT_SIZE;
if (DiBuildClassInfoList(0, LocalGuid, ClassGuids, &GuidsRequired))
{
BuildClassesFromGuidList(LocalGuid, GuidsRequired);
}
else if (ERROR_INSUFFICIENT_BUFFER == GetLastError() && GuidsRequired)
{
// the stack based buffer is too small, allocate buffer from
// the heap.
BufferPtr<GUID> ClassGuidList(GuidsRequired);
if (DiBuildClassInfoList(0, ClassGuidList, GuidsRequired, &ClassGuids))
{
BuildClassesFromGuidList(ClassGuidList, ClassGuids);
}
}
//
// If we have any classes at all, create devices objects
//
if (!m_listClass.IsEmpty())
{
DWORD Index = 0;
SP_DEVINFO_DATA DevData;
//
// We need a handle to the service manager in the DoNotCreateDevice
// function. We will open it once and pass it to this function rather
// than opening and closing it for every device.
//
SCMHandle = OpenSCManager(NULL, NULL, GENERIC_READ);
//
// Create every device in the devinfo list and
// associate each device to its class.
//
DevData.cbSize = sizeof(DevData);
while (DiEnumDeviceInfo(Index, &DevData))
{
POSITION pos = m_listClass.GetHeadPosition();
CClass* pClass;
// find the class for this device
while (NULL != pos)
{
pClass = m_listClass.GetNext(pos);
//
// Match the ClassGuid for this device.
// Note that if the device does not have a class guid (GUID_NULL)
// then we will put it in class GUID_DEVCLASS_UNKNOWN)
//
if ((IsEqualGUID(DevData.ClassGuid, *pClass)) ||
(IsEqualGUID(GUID_DEVCLASS_UNKNOWN, *pClass) &&
IsEqualGUID(DevData.ClassGuid, GUID_NULL)))
{
//
// Is this one of the special DevInst that we should
// not create a CDevice for?
//
if (DoNotCreateDevice(SCMHandle, *pClass, DevData.DevInst)) {
break;
}
// create the device
SafePtr<CDevice> DevicePtr;
CDevice* pDevice;
pDevice = new CDevice(this, pClass, &DevData);
// guard the object
DevicePtr.Attach(pDevice);
m_listDevice.AddTail(DevicePtr);
// object added..
DevicePtr.Detach();
// put the device under the class
pClass->AddDevice(pDevice);
break;
}
// no class than, no device
}
//
// next device
//
Index++;
}
CloseServiceHandle(SCMHandle);
//
// Create a device tree under computer
// the tree order comes from DEVNODE structure;
//
DEVNODE dnRoot = CmGetRootDevNode();
m_pComputer = new CComputer(this, dnRoot);
DEVNODE dnStart = CmGetChild(dnRoot);
CreateDeviceTree(m_pComputer, NULL, dnStart);
}
else
{
m_LogFile.Logf(TEXT("No classes available, total class guid from setupdi = %l\n"),
GuidsRequired);
}
// log objects attached to this machine
LOGMACHINE();
return TRUE;
}
//
// This function builds a device tree based on the Devnode tree retreived
// from configuration manager. Note that ALL CDevice are created before
// this function is called. This function establishs each CDevice relationship.
//
void
CMachine::CreateDeviceTree(
CDevice* pParent,
CDevice* pSibling,
DEVNODE dn
)
{
CDevice* pDevice;
DEVNODE dnChild, dnSibling;
while (dn)
{
pDevice = DevNodeToDevice(dn);
if (pDevice)
{
// no sibling ->this is the first child
if (!pSibling)
{
pParent->SetChild(pDevice);
}
else
{
pSibling->SetSibling(pDevice);
}
pDevice->SetParent(pParent);
pSibling = pDevice;
dnChild = CmGetChild(dn);
if (dnChild)
{
CreateDeviceTree(pDevice, NULL, dnChild);
}
}
else
{
m_LogFile.Logf(TEXT("Devnode %lx not contained in hDevInfo\n"),
dn);
//TRACE((TEXT("Devnode %08X not contained in hDevInfo")));
}
dn = CmGetSibling(dn);
}
}
//
// Find CDevice from the given devnode
//
CDevice*
CMachine::DevNodeToDevice(
DEVNODE dn
)
{
POSITION pos = m_listDevice.GetHeadPosition();
while (NULL != pos)
{
CDevice* pDevice = m_listDevice.GetNext(pos);
if (pDevice->GetDevNode() == dn) {
return pDevice;
}
}
return NULL;
}
//
// Find CDevice from the given device id
//
CDevice*
CMachine::DeviceIDToDevice(
LPCTSTR DeviceID
)
{
if (!DeviceID)
return NULL;
POSITION pos = m_listDevice.GetHeadPosition();
while (NULL != pos)
{
CDevice* pDevice = m_listDevice.GetNext(pos);
if (*pDevice == DeviceID)
return pDevice;
}
return NULL;
}
//
// Find CClass from the given GUID
//
CClass*
CMachine::ClassGuidToClass(
LPGUID ClassGuid
)
{
if (!ClassGuid)
return NULL;
POSITION pos = m_listClass.GetHeadPosition();
while (NULL != pos)
{
CClass* pClass = m_listClass.GetNext(pos);
if (IsEqualGUID(*ClassGuid, *pClass))
return pClass;
}
return NULL;
}
BOOL
CMachine::LoadStringWithMachineName(
int StringId,
LPTSTR Buffer,
DWORD* BufferLen
)
{
if (!BufferLen || *BufferLen && !Buffer)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
TCHAR Format[LINE_LEN];
TCHAR Temp[1024];
LoadResourceString(StringId, Format, ARRAYLEN(Format));
if (IsLocal())
{
TCHAR LocalComputer[LINE_LEN];
LoadResourceString(IDS_LOCAL_MACHINE, LocalComputer, ARRAYLEN(LocalComputer));
wsprintf(Temp, Format, LocalComputer);
}
else
{
wsprintf(Temp, Format, (LPCTSTR)m_strMachineFullName);
}
DWORD Len = lstrlen(Temp);
if (*BufferLen > Len)
{
lstrcpyn(Buffer, Temp, Len + 1);
*BufferLen = Len;
return TRUE;
}
else
{
SetLastError(ERROR_BUFFER_OVERFLOW);
*BufferLen = Len;
return FALSE;
}
}
//
// This function goes through all its CClass and CDevice to
// determine how many property sheets are currently active.
//
UINT
CMachine::GetActivePropSheetCount()
{
UINT Count = 0;
// start with class and then for each device under the class
if (!m_listClass.IsEmpty())
{
POSITION posClass;
posClass = m_listClass.GetHeadPosition();
CClass* pClass;
while (NULL != posClass)
{
pClass = m_listClass.GetNext(posClass);
if (pClass->m_psd.GetWindowHandle())
Count++;
// loop through all its devices
CDevice* pDevice;
PVOID Context;
if (pClass->GetFirstDevice(&pDevice, Context))
{
do
{
if (pDevice->m_psd.GetWindowHandle())
Count++;
} while (pClass->GetNextDevice(&pDevice, Context));
}
}
}
return Count;
}
//
// This function reenumerates the devnode tree from the root, rebuilds the
// device tree and notifies every attached folder about the new device tree.
//
BOOL
CMachine::Reenumerate()
{
BOOL Result = FALSE;
if (m_pComputer)
{
// Temporarily disable refresh while we are doing reenumeration
// so that we will not keep refreshing the device tree.
EnableRefresh(FALSE);
CDialog WaitDialog(IDD_SCAN_PNP_HARDWARES);
WaitDialog.DoModaless(m_hwndParent, (LPARAM)&WaitDialog);
LOGMISCINFO(TEXT("Reenumerating...\n"));
CmReenumerate(m_pComputer->GetDevNode(), CM_REENUMERATE_SYNCHRONOUS);
DestroyWindow(WaitDialog);
// reenumeration is done, schedule a refresh and enable refresh now.
ScheduleRefresh();
EnableRefresh(TRUE);
}
return TRUE;
}
//
// This function enable/disable refresh. A disble counter is kept to
// support multiple disabling/enabling. Only when the disable counter
// is zero, a refresh is possible.
// If a refresh is pending while we are enabling, we schedule a new
// request so that we will not lose any requests.
//
BOOL
CMachine::EnableRefresh(
BOOL fEnable
)
{
BOOL Result = TRUE;
Lock();
if (fEnable)
{
if (m_RefreshDisableCounter < 0)
{
m_RefreshDisableCounter++;
}
}
else
{
m_RefreshDisableCounter--;
}
// If we are enabling refresh and there is one request pending,
// schedule it again. This makes sure that we will not lose
// any requests.
// We schedule a new refresh request instead of calling Refresh
// directly because we can be called by different threads while
// we want the refresh to be done in the main thread. The data window
// we created will receive the message and execute the refresh
// in the main thread context.
if (fEnable && m_RefreshPending)
{
m_RefreshPending = FALSE;
ScheduleRefresh();
}
Unlock();
return Result;
}
//
//
// This function rebuilds the entire list of CClass and CDevice
// All attached CFolder are notified about the new machine.
//
// There are several occasions that we need to recreate the device tree:
// (1). On WM_DEVICECHANGE. (2). Device properties changed.
// (3). Device removal. (4). Device drivers updated and
// (5). Reenumeration requested by users.
// The requests may come from different threads and we must serialize
// the requests. A critical section and a new function(EnableRefresh) are added for
// for this purpose.
// Before doing anything on a device or class, one must call EnableRefesh(FALSE)
// to suspend Device change notification. When it is done with the change,
// one must call ScheduleRefesh function(if a refresh is necessary because of
// the changes) and then EnableRefresh(TRUE) to reenable the refresh.
//
BOOL
CMachine::Refresh()
{
BOOL Result = TRUE;
Lock();
if (0 == m_RefreshDisableCounter)
{
HCURSOR hCursorOld;
hCursorOld = SetCursor(LoadCursor(NULL, IDC_WAIT));
// before we destroy all the classes and devices,
// notify every attached folder so that they can dis-engaged
// from us. After we created a new set of classes and devices,
// the notification will be sent again to each folder
// so that each folder can enagage to the machine again.
POSITION pos;
pos = m_listFolders.GetHeadPosition();
while (NULL != pos)
{
((CFolder*)m_listFolders.GetNext(pos))->MachinePropertyChanged(NULL);
}
// we can destroy all the "old" classes and devices now.
LOGMISCINFO(TEXT("Refreshing...\n"));
DestroyClassesAndDevices();
if (CreateClassesAndDevices())
{
// notify every attach folder to recreate
if (!m_listFolders.IsEmpty())
{
POSITION pos = m_listFolders.GetHeadPosition();
while (NULL != pos)
{
CFolder* pFolder = m_listFolders.GetNext(pos);
Result = SUCCEEDED(pFolder->MachinePropertyChanged(this));
}
}
}
if (hCursorOld)
SetCursor(hCursorOld);
m_RefreshPending = FALSE;
}
else
{
// we need to refresh while the refresh is disabled
// Remember this so that when refresh is enabled, we
// can launch a refresh.
LOGMISCINFO(TEXT("Refresh pending\n"));
m_RefreshPending = TRUE;
}
Unlock();
return Result;
}
BOOL
CMachine::GetFirstDevice(
CDevice** ppDevice,
PVOID& Context
)
{
ASSERT(ppDevice);
if (!m_listDevice.IsEmpty())
{
POSITION pos = m_listDevice.GetHeadPosition();
*ppDevice = m_listDevice.GetNext(pos);
Context = pos;
return TRUE;
}
*ppDevice = NULL;
Context = NULL;
return FALSE;
}
BOOL
CMachine::GetNextDevice(
CDevice** ppDevice,
PVOID& Context
)
{
ASSERT(ppDevice);
POSITION pos = (POSITION)Context;
if (NULL != pos)
{
*ppDevice = m_listDevice.GetNext(pos);
Context = pos;
return TRUE;
}
*ppDevice = NULL;
return FALSE;
}
BOOL
CMachine::GetFirstClass(
CClass** ppClass,
PVOID& Context
)
{
ASSERT(ppClass);
if (!m_listClass.IsEmpty())
{
POSITION pos = m_listClass.GetHeadPosition();
*ppClass = m_listClass.GetNext(pos);
Context = pos;
return TRUE;
}
*ppClass = NULL;
Context = NULL;
return FALSE;
}
BOOL
CMachine::GetNextClass(
CClass** ppClass,
PVOID& Context
)
{
ASSERT(ppClass);
POSITION pos = (POSITION)Context;
if (NULL != pos)
{
*ppClass = m_listClass.GetNext(pos);
Context = pos;
return TRUE;
}
*ppClass = NULL;
return FALSE;
}
BOOL
CMachine::pGetOriginalInfName(
LPTSTR InfName,
String& OriginalInfName
)
{
SP_ORIGINAL_FILE_INFO InfOriginalFileInformation;
PSP_INF_INFORMATION pInfInformation;
DWORD InfInformationSize;
BOOL bRet;
ZeroMemory(&InfOriginalFileInformation, sizeof(InfOriginalFileInformation));
InfInformationSize = 8192; // I'd rather have this too big and succeed first time, than read the INF twice
pInfInformation = (PSP_INF_INFORMATION)LocalAlloc(LPTR, InfInformationSize);
if (pInfInformation != NULL) {
bRet = SetupGetInfInformation(InfName,
INFINFO_INF_NAME_IS_ABSOLUTE,
pInfInformation,
InfInformationSize,
&InfInformationSize
);
DWORD Error = GetLastError();
//
// If buffer was too small then make the buffer larger and try again.
//
if (!bRet && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
PVOID newbuff = LocalReAlloc(pInfInformation, InfInformationSize, LPTR);
if (!newbuff) {
LocalFree(pInfInformation);
pInfInformation = NULL;
} else {
pInfInformation = (PSP_INF_INFORMATION)newbuff;
bRet = SetupGetInfInformation(InfName,
INFINFO_INF_NAME_IS_ABSOLUTE,
pInfInformation,
InfInformationSize,
&InfInformationSize
);
}
}
if (bRet) {
InfOriginalFileInformation.cbSize = sizeof(InfOriginalFileInformation);
if (SetupQueryInfOriginalFileInformation(pInfInformation, 0, NULL, &InfOriginalFileInformation)) {
if (InfOriginalFileInformation.OriginalInfName[0]!=0) {
//
// we have a "real" inf name
//
OriginalInfName = InfOriginalFileInformation.OriginalInfName;
}
}
}
//
// Assume that this INF has not been renamed
//
else {
OriginalInfName = MyGetFileTitle(InfName);
}
if (pInfInformation != NULL) {
LocalFree(pInfInformation);
pInfInformation = NULL;
}
}
return TRUE;
}
BOOL
CMachine::GetDigitalSigner(
LPTSTR FullInfPath,
String& DigitalSigner
)
{
String OriginalInfName;
String Catalog;
LPBYTE Hash;
DWORD HashSize;
CATALOG_INFO CatInfo;
HANDLE hFile;
HCATADMIN hCatAdmin;
HCATINFO hCatInfo;
HCATINFO PrevCat;
DWORD Err;
WINTRUST_DATA WintrustData;
WINTRUST_CATALOG_INFO WintrustCatalogInfo;
WINTRUST_FILE_INFO WintrustFileInfo;
DRIVER_VER_INFO VersionInfo;
OSVERSIONINFO OSVer;
LPTSTR CatalogFullPath;
WCHAR UnicodeKey[MAX_PATH];
//
// Get the INFs original name (this is needed since it is the hash key)
//
pGetOriginalInfName(FullInfPath, OriginalInfName);
//
// If this is an OEM INF then only check the OEM catalog.
// We determine if it is an OEM if by checking to see if the current
// INF name is the same as the original INF name.
//
if (lstrcmpi(MyGetFileTitle(FullInfPath), LPTSTR(OriginalInfName))) {
//
// Get the catalog name by replacing .INF with .CAT in the
// current INF name.
//
Catalog = MyGetFileTitle(FullInfPath);
lstrcpy(&Catalog[Catalog.GetLength() - lstrlen(TEXT(".CAT"))], TEXT(".CAT"));
}
lstrcpyn(UnicodeKey, OriginalInfName, sizeof(UnicodeKey)/sizeof(TCHAR));
//
// Calculate the hash value for the inf.
//
if(CryptCATAdminAcquireContext(&hCatAdmin, &DriverVerifyGuid, 0)) {
hFile = CreateFile(FullInfPath,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL
);
if(hFile == INVALID_HANDLE_VALUE) {
Err = GetLastError();
ASSERT(Err != NO_ERROR);
} else {
//
// Start out with a hash buffer size that should be large enough for
// most requests.
//
HashSize = 100;
do {
Hash = (LPBYTE)LocalAlloc(LPTR, HashSize);
if(!Hash) {
Err = ERROR_NOT_ENOUGH_MEMORY;
break;
}
if(CryptCATAdminCalcHashFromFileHandle(hFile, &HashSize, Hash, 0)) {
Err = NO_ERROR;
} else {
Err = GetLastError();
ASSERT(Err != NO_ERROR);
//
// If this API did screw up and not set last error, go ahead
// and set something.
//
if(Err == NO_ERROR) {
Err = ERROR_INVALID_DATA;
}
LocalFree(Hash);
if(Err != ERROR_INSUFFICIENT_BUFFER) {
//
// The API failed for some reason other than
// buffer-too-small. We gotta bail.
//
Hash = NULL; // reset this so we won't try to free it later
break;
}
}
} while(Err != NO_ERROR);
CloseHandle(hFile);
if(Err == NO_ERROR) {
//
// Now we have the file's hash. Initialize the structures that
// will be used later on in calls to WinVerifyTrust.
//
ZeroMemory(&WintrustData, sizeof(WINTRUST_DATA));
WintrustData.cbStruct = sizeof(WINTRUST_DATA);
WintrustData.dwUIChoice = WTD_UI_NONE;
WintrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
WintrustData.dwUnionChoice = WTD_CHOICE_CATALOG;
WintrustData.dwStateAction = WTD_STATEACTION_AUTO_CACHE;
WintrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
WintrustData.pCatalog = &WintrustCatalogInfo;
ZeroMemory(&WintrustCatalogInfo, sizeof(WINTRUST_CATALOG_INFO));
WintrustCatalogInfo.cbStruct = sizeof(WINTRUST_CATALOG_INFO);
WintrustCatalogInfo.pbCalculatedFileHash = Hash;
WintrustCatalogInfo.cbCalculatedFileHash = HashSize;
WintrustData.pPolicyCallbackData = (LPVOID)&VersionInfo;
ZeroMemory(&VersionInfo, sizeof(DRIVER_VER_INFO));
VersionInfo.cbStruct = sizeof(DRIVER_VER_INFO);
ZeroMemory(&OSVer, sizeof(OSVERSIONINFO));
OSVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (GetVersionEx(&OSVer)) {
VersionInfo.dwPlatform = OSVer.dwPlatformId;
VersionInfo.dwVersion = OSVer.dwMajorVersion;
VersionInfo.sOSVersionLow.dwMajor = OSVer.dwMajorVersion;
VersionInfo.sOSVersionLow.dwMinor = OSVer.dwMinorVersion;
VersionInfo.sOSVersionHigh.dwMajor = OSVer.dwMajorVersion;
VersionInfo.sOSVersionHigh.dwMinor = OSVer.dwMinorVersion;
}
//
// WinVerifyTrust is case-sensitive, so ensure that the key
// being used is all lower-case!
//
CharLower(UnicodeKey);
WintrustCatalogInfo.pcwszMemberTag = UnicodeKey;
//
// Search through installed catalogs looking for those that
// contain data for a file with the hash we just calculated.
//
PrevCat = NULL;
hCatInfo = CryptCATAdminEnumCatalogFromHash(hCatAdmin,
Hash,
HashSize,
0,
&PrevCat
);
//
// Enumerate through all of the catalogs installed on the system
//
while(hCatInfo) {
CatInfo.cbStruct = sizeof(CATALOG_INFO);
if(CryptCATCatalogInfoFromContext(hCatInfo, &CatInfo, 0)) {
CatalogFullPath = CatInfo.wszCatalogFile;
//
// If we have a catalog name we're looking for,
// see if the current catalog matches. If we
// are not validating against a specific catalog, then
// just attempt to validate against each catalog we
// enumerate. Note that the catalog file info we
// get back gives us a fully qualified path.
//
if(Catalog.IsEmpty() || (!lstrcmpi(MyGetFileTitle(CatalogFullPath), (LPTSTR)Catalog)))
{
//
// We found an applicable catalog, now
// validate the file against that catalog.
//
// NOTE: Because we're using cached
// catalog information (i.e., the
// WTD_STATEACTION_AUTO_CACHE flag), we
// don't need to explicitly validate the
// catalog itself first.
//
WintrustCatalogInfo.pcwszCatalogFilePath = CatInfo.wszCatalogFile;
Err = (DWORD)WinVerifyTrust(NULL,
&DriverVerifyGuid,
&WintrustData
);
//
// If WinVerifyTrust suceeded
//
if (Err == NO_ERROR) {
DigitalSigner = VersionInfo.wszSignedBy;
}
//
// Free the pcSignerCertContext member of the DRIVER_VER_INFO struct
// that was allocated in our call to WinVerifyTrust.
//
if (VersionInfo.pcSignerCertContext != NULL) {
CertFreeCertificateContext(VersionInfo.pcSignerCertContext);
VersionInfo.pcSignerCertContext = NULL;
}
//
// If the result of the above validations is
// success, then we're done. If not, and we're
// looking for a relevant catalog file (i.e.,
// the INF didn't specify one), then we move
// on to the next catalog. Otherwise, we've
// failed.
//
if((Err == NO_ERROR) || !Catalog.IsEmpty()) {
CryptCATAdminReleaseCatalogContext(hCatAdmin, hCatInfo, 0);
break;
}
}
}
PrevCat = hCatInfo;
hCatInfo = CryptCATAdminEnumCatalogFromHash(hCatAdmin, Hash, HashSize, 0, &PrevCat);
}
}
if(Hash) {
LocalFree(Hash);
}
}
CryptCATAdminReleaseContext(hCatAdmin,0);
}
return TRUE;
}
BOOL
CMachine::DoNotCreateDevice(
SC_HANDLE SCMHandle,
LPGUID ClassGuid,
DEVINST DevInst
)
/*++
This function returns whether a CDevice should be created for this DevInst
or not. If a CDevice is not created for DevInst then it will never show up
in the device manager UI, even when "Show hidden devices" is turned on.
We don't create a CDevice in the following cases:
- DevInst is HTREE\ROOT\0
- DevInst is a Win32 Service.
--*/
{
SC_HANDLE ServiceHandle;
TCHAR ServiceName[MAX_PATH];
LPQUERY_SERVICE_CONFIG ServiceConfig = NULL;
DWORD ServiceConfigSize;
ULONG Size;
String strDeviceID;
BOOL Return = FALSE;
//
// Check to see if this device is a Win32 service. Only
// legacy devices could be Win32 services.
//
if (IsEqualGUID(*ClassGuid, GUID_DEVCLASS_LEGACYDRIVER)) {
Size = sizeof(ServiceName);
if (CmGetRegistryProperty(DevInst,
CM_DRP_SERVICE,
(PVOID)ServiceName,
&Size
) == CR_SUCCESS) {
//
// Open this particular service
//
if ((ServiceHandle = OpenService(SCMHandle, ServiceName, GENERIC_READ)) != NULL) {
//
// Get the service config
//
if ((!QueryServiceConfig(ServiceHandle, NULL, 0, &ServiceConfigSize)) &&
(ERROR_INSUFFICIENT_BUFFER == GetLastError())) {
if ((ServiceConfig = (LPQUERY_SERVICE_CONFIG)malloc(ServiceConfigSize)) != NULL) {
if (QueryServiceConfig(ServiceHandle, ServiceConfig, ServiceConfigSize, &ServiceConfigSize)) {
if (ServiceConfig->dwServiceType & (SERVICE_WIN32 | SERVICE_FILE_SYSTEM_DRIVER)) {
Return = TRUE;
}
}
free(ServiceConfig);
}
}
CloseServiceHandle(ServiceHandle);
}
}
}
//
// If the DEVMGR_SHOW_NONPRESENT_DEVICES environment variable is not set then
// we do not want to show any Phantom devices.
//
else if (!m_ShowNonPresentDevices) {
CONFIGRET cr;
ULONG Status, Problem;
cr = CM_Get_DevInst_Status(&Status, &Problem, DevInst, 0);
if ((cr == CR_NO_SUCH_VALUE) ||
(cr == CR_NO_SUCH_DEVINST)) {
return TRUE;
}
}
//
// Check to see if this is the HTREE\ROOT\0 device. We don't
// want to create a CDevice for this phantom devnode.
//
// This is an else statement because the HTREE\ROOT\0 device is
// not in the legacy device class.
//
else {
CmGetDeviceIDString(DevInst, strDeviceID);
if (!lstrcmpi((LPTSTR)strDeviceID, TEXT("HTREE\\ROOT\\0"))) {
Return = TRUE;
}
}
return Return;
}
BOOL
CMachine::DiGetClassFriendlyNameString(
LPGUID Guid,
String& strClass
)
{
TCHAR DisplayName[LINE_LEN + 1];
// try friendly name first. If it failed, try the class name
if (SetupDiGetClassDescriptionEx(Guid, DisplayName, sizeof(DisplayName),
NULL, GetRemoteMachineFullName(), NULL) ||
SetupDiClassNameFromGuidEx(Guid, DisplayName, sizeof(DisplayName),
NULL, GetRemoteMachineFullName(), NULL))
{
strClass = DisplayName;
return TRUE;
}
return FALSE;
}
DEVNODE
CMachine::CmGetParent(
DEVNODE dn
)
{
DEVNODE dnParent;
m_LastCR = CM_Get_Parent_Ex(&dnParent, dn, 0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
return dnParent;
return NULL;
}
DEVNODE
CMachine::CmGetChild(
DEVNODE dn
)
{
DEVNODE dnChild;
m_LastCR = CM_Get_Child_Ex(&dnChild, dn, 0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
return dnChild;
return NULL;
}
DEVNODE
CMachine::CmGetSibling(
DEVNODE dn
)
{
DEVNODE dnSibling;
m_LastCR = CM_Get_Sibling_Ex(&dnSibling, dn, 0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
return dnSibling;
return NULL;
}
DEVNODE
CMachine::CmGetRootDevNode()
{
DEVNODE dnRoot;
m_LastCR = CM_Locate_DevNode_Ex(&dnRoot, NULL, 0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
return dnRoot;
return NULL;
}
BOOL
CMachine::CmGetDeviceIDString(
DEVNODE dn,
String& str
)
{
TCHAR DeviceID[MAX_DEVICE_ID_LEN + 1];
m_LastCR = CM_Get_Device_ID_Ex(dn, DeviceID, sizeof(DeviceID), 0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
{
str = DeviceID;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetConfigFlags(
DEVNODE dn,
DWORD* pFlags
)
{
DWORD Size;
Size = sizeof(DWORD);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_CONFIGFLAGS, pFlags, &Size);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmGetCapabilities(
DEVNODE dn,
DWORD* pCapabilities
)
{
DWORD Size;
Size = sizeof(DWORD);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_CAPABILITIES, pCapabilities, &Size);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmGetDescriptionString(
DEVNODE dn,
String& str
)
{
TCHAR Description[LINE_LEN + 1];
ULONG Size = sizeof(Description);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_FRIENDLYNAME, Description, &Size);
if (CR_NO_SUCH_VALUE == m_LastCR)
{
Size = sizeof(Description);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_DEVICEDESC, Description,
&Size);
}
if (CR_SUCCESS == m_LastCR)
{
str = Description;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetMFGString(
DEVNODE dn,
String& str
)
{
TCHAR MFG[LINE_LEN + 1];
ULONG Size = sizeof(MFG);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_MFG, MFG, &Size);
if (CR_SUCCESS == m_LastCR)
{
str = MFG;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetProviderString(
DEVNODE dn,
String& str
)
{
TCHAR Provider[LINE_LEN + 1];
ULONG Size = sizeof(Provider);
m_LastCR = CmGetRegistrySoftwareProperty(dn, TEXT("ProviderName"),
Provider, &Size);
if (CR_SUCCESS == m_LastCR)
{
str = Provider;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetDriverDateString(
DEVNODE dn,
String& str
)
{
TCHAR DriverDate[LINE_LEN + 1];
ULONG Size = sizeof(DriverDate);
m_LastCR = CmGetRegistrySoftwareProperty(dn, TEXT("DriverDate"),
DriverDate, &Size);
if (CR_SUCCESS == m_LastCR)
{
str = DriverDate;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetDriverDateData(
DEVNODE dn,
FILETIME *ft
)
{
ULONG Size = sizeof(*ft);
m_LastCR = CmGetRegistrySoftwareProperty(dn, TEXT("DriverDateData"),
ft, &Size);
return (m_LastCR == CR_SUCCESS);
}
BOOL
CMachine::CmGetDriverVersionString(
DEVNODE dn,
String& str
)
{
TCHAR DriverVersion[LINE_LEN + 1];
ULONG Size = sizeof(DriverVersion);
m_LastCR = CmGetRegistrySoftwareProperty(dn, TEXT("DriverVersion"),
DriverVersion, &Size);
if (CR_SUCCESS == m_LastCR)
{
str = DriverVersion;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetBusGuid(
DEVNODE dn,
LPGUID Guid
)
{
ULONG Size = sizeof(*Guid);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_BUSTYPEGUID, (LPVOID)Guid, &Size);
if (CR_SUCCESS == m_LastCR) {
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetBusGuidString(
DEVNODE dn,
String& str
)
{
GUID BusGuid;
TCHAR BusGuidString[MAX_GUID_STRING_LEN];
ULONG Size;
while (dn)
{
// we have to set the size on each loop
Size = sizeof(BusGuid);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_BUSTYPEGUID, &BusGuid, &Size);
if (CR_SUCCESS == m_LastCR && GuidToString(&BusGuid, BusGuidString,
ARRAYLEN(BusGuidString)))
{
str = BusGuidString;
return TRUE;
}
dn = CmGetParent(dn);
}
return FALSE;
}
BOOL
CMachine::CmGetClassGuid(
DEVNODE dn,
GUID& Guid
)
{
TCHAR szGuidString[MAX_GUID_STRING_LEN + 1];
ULONG Size = sizeof(szGuidString);
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_CLASSGUID, szGuidString, &Size);
if (CR_SUCCESS == m_LastCR && GuidFromString(szGuidString, &Guid))
{
return TRUE;
}
//
// If we can't get the class GUID from the registry then most likely the device
// does not have a class GUID. If this is the case then we will return
// GUID_DEVCLASS_UNKNOWN
//
else
{
memcpy(&Guid, &GUID_DEVCLASS_UNKNOWN, sizeof(GUID));
return TRUE;
}
}
BOOL
CMachine::CmGetHardwareIDs(
DEVNODE dn,
PVOID Buffer,
ULONG* BufferLen
)
{
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_HARDWAREID, Buffer, BufferLen);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmGetCompatibleIDs(
DEVNODE dn,
PVOID Buffer,
ULONG* BufferLen
)
{
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_COMPATIBLEIDS, Buffer, BufferLen);
return CR_SUCCESS == m_LastCR;
}
LPTSTR
FormatString(
LPCTSTR format,
...
)
{
LPTSTR str = NULL;
va_list arglist;
va_start(arglist, format);
if (FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER,
format,
0,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
(LPTSTR)&str,
0,
&arglist
) == 0) {
str = NULL;
}
va_end(arglist);
return str;
}
STDAPI_(CONFIGRET) GetLocationInformation(
DEVNODE dn,
LPTSTR Location,
ULONG LocationLen,
HMACHINE hMachine
)
/*++
Slot x (LocationInformation)
Slot x
LocationInformation
on parent bus
--*/
{
CONFIGRET LastCR;
DEVNODE dnParent;
ULONG ulSize;
DWORD UINumber;
TCHAR Buffer[MAX_PATH];
TCHAR UINumberDescFormat[MAX_PATH];
TCHAR Format[MAX_PATH];
Buffer[0] = TEXT('\0');
//
// Get the LocationInformation for this device
//
ulSize = sizeof(Buffer);
CM_Get_DevNode_Registry_Property_Ex(dn,
CM_DRP_LOCATION_INFORMATION,
NULL,
Buffer,
&ulSize,
0,
hMachine
);
//
// UINumber has precedence over all other location information so check if this
// device has a UINumber.
//
ulSize = sizeof(UINumber);
if (((LastCR = CM_Get_DevNode_Registry_Property_Ex(dn,
CM_DRP_UI_NUMBER,
NULL,
&UINumber,
&ulSize,
0,
hMachine
)) == CR_SUCCESS) &&
(ulSize > 0)) {
UINumberDescFormat[0] = TEXT('\0');
ulSize = sizeof(UINumberDescFormat);
//
// Get the UINumber description format string from the device's parent,
// if there is one, otherwise default to 'Location %1'
if ((CM_Get_Parent_Ex(&dnParent, dn, 0, hMachine) == CR_SUCCESS) &&
(CM_Get_DevNode_Registry_Property_Ex(dnParent,
CM_DRP_UI_NUMBER_DESC_FORMAT,
NULL,
UINumberDescFormat,
&ulSize,
0,
hMachine) == CR_SUCCESS) &&
*UINumberDescFormat) {
} else {
::LoadString(g_hInstance, IDS_UI_NUMBER_DESC_FORMAT, UINumberDescFormat, sizeof(UINumberDescFormat)/sizeof(TCHAR));
}
LPTSTR UINumberBuffer = NULL;
//
// Fill in the UINumber string
//
UINumberBuffer = FormatString(UINumberDescFormat, UINumber);
if (UINumberBuffer) {
lstrcpy((LPTSTR)Location, UINumberBuffer);
LocalFree(UINumberBuffer);
} else {
Location[0] = TEXT('\0');
}
//
// If we also have LocationInformation then tack that on the end of the string
// as well.
//
if (*Buffer) {
lstrcat((LPTSTR)Location, TEXT(" ("));
lstrcat((LPTSTR)Location, Buffer);
lstrcat((LPTSTR)Location, TEXT(")"));
}
}
//
// We don't have a UINumber but we do have LocationInformation
//
else if (*Buffer) {
::LoadString(g_hInstance, IDS_LOCATION, Format, sizeof(Format)/sizeof(TCHAR));
wsprintf((LPTSTR)Location, Format, Buffer);
}
//
// We don't have a UINumber or LocationInformation so we need to get a description
// of the parent of this device.
//
else {
if ((LastCR = CM_Get_Parent_Ex(&dnParent, dn, 0, hMachine)) == CR_SUCCESS) {
//
// Try the registry for FRIENDLYNAME
//
Buffer[0] = TEXT('\0');
ulSize = sizeof(Buffer);
if (((LastCR = CM_Get_DevNode_Registry_Property_Ex(dnParent,
CM_DRP_FRIENDLYNAME,
NULL,
Buffer,
&ulSize,
0,
hMachine
)) != CR_SUCCESS) ||
!*Buffer) {
//
// Try the registry for DEVICEDESC
//
ulSize = sizeof(Buffer);
if (((LastCR = CM_Get_DevNode_Registry_Property_Ex(dnParent,
CM_DRP_DEVICEDESC,
NULL,
Buffer,
&ulSize,
0,
hMachine
)) != CR_SUCCESS) ||
!*Buffer) {
ulSize = sizeof(Buffer);
if (((LastCR = CM_Get_DevNode_Registry_Property_Ex(dnParent,
CM_DRP_CLASS,
NULL,
Buffer,
&ulSize,
0,
hMachine
)) != CR_SUCCESS) ||
!*Buffer) {
//
// no parent, or parent name.
//
Buffer[0] = TEXT('\0');
}
}
}
}
if (*Buffer) {
//
// We have a description of the parent
//
::LoadString(g_hInstance, IDS_LOCATION_NOUINUMBER, Format, sizeof(Format)/sizeof(TCHAR));
wsprintf((LPTSTR)Location, Format, Buffer);
} else {
//
// We don't have any information so we will just say Unknown
//
::LoadString(g_hInstance, IDS_UNKNOWN, Location, LocationLen);
}
}
return CR_SUCCESS;
}
BOOL
CMachine::CmGetStatus(
DEVNODE dn,
DWORD* pProblem,
DWORD* pStatus
)
{
ASSERT(pProblem && pStatus);
m_LastCR = CM_Get_DevNode_Status_Ex(pStatus, pProblem, dn, 0, m_hMachine);
return (CR_SUCCESS == m_LastCR);
}
BOOL
CMachine::CmGetKnownLogConf(
DEVNODE dn,
LOG_CONF* plc,
DWORD* plcType
)
{
ASSERT(plc);
*plc = 0;
if (plcType)
*plcType = LOG_CONF_BITS + 1;
ULONG lcTypeFirst = ALLOC_LOG_CONF;
ULONG lcTypeLast = FORCED_LOG_CONF;
ASSERT(ALLOC_LOG_CONF + 1 == BOOT_LOG_CONF &&
BOOT_LOG_CONF + 1 == FORCED_LOG_CONF);
for (ULONG lcType = lcTypeFirst; lcType <= lcTypeLast; lcType++)
{
m_LastCR = CM_Get_First_Log_Conf_Ex(plc, dn, lcType, m_hMachine);
if (CR_SUCCESS == m_LastCR)
{
if (plcType)
*plcType = lcType;
break;
}
}
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmHasResources(
DEVNODE dn
)
{
for (ULONG lcType = 0; lcType < NUM_LOG_CONF; lcType++)
{
m_LastCR = CM_Get_First_Log_Conf_Ex(NULL, dn, lcType, m_hMachine);
if (CR_SUCCESS == m_LastCR)
break;
}
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmReenumerate(
DEVNODE dn,
ULONG Flags
)
{
m_LastCR = CM_Reenumerate_DevNode(dn, Flags);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmGetHwProfileFlags(
DEVNODE dn,
ULONG Profile,
ULONG* pFlags
)
{
TCHAR DeviceID[MAX_DEVICE_ID_LEN + 1];
m_LastCR = CM_Get_Device_ID_Ex(dn, DeviceID, sizeof(DeviceID),
0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
return CmGetHwProfileFlags(DeviceID, Profile, pFlags);
return FALSE;
}
BOOL
CMachine::CmGetHwProfileFlags(
LPCTSTR DeviceID,
ULONG Profile,
ULONG* pFlags
)
{
m_LastCR = CM_Get_HW_Prof_Flags_Ex((LPTSTR)DeviceID, Profile, pFlags, 0,
m_hMachine);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmSetHwProfileFlags(
DEVNODE dn,
ULONG Profile,
ULONG Flags
)
{
TCHAR DeviceID[MAX_DEVICE_ID_LEN + 1];
m_LastCR = CM_Get_Device_ID_Ex(dn, DeviceID, sizeof(DeviceID),
0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
return CmSetHwProfileFlags(DeviceID, Profile, Flags);
return FALSE;
}
BOOL
CMachine::CmSetHwProfileFlags(
LPCTSTR DeviceID,
ULONG Profile,
ULONG Flags
)
{
m_LastCR = CM_Set_HW_Prof_Flags_Ex((LPTSTR)DeviceID, Profile, Flags, 0,
m_hMachine);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmHasDrivers(
DEVNODE dn
)
{
ULONG Size = 0;
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_DRIVER, NULL, &Size);
if (CR_BUFFER_SMALL != m_LastCR)
{
Size = 0;
m_LastCR = CmGetRegistryProperty(dn, CM_DRP_SERVICE, NULL, &Size);
}
return (CR_BUFFER_SMALL == m_LastCR);
}
BOOL
CMachine::CmGetCurrentHwProfile(
ULONG* phwpf
)
{
HWPROFILEINFO hwpfInfo;
ASSERT(phwpf);
if (CmGetHwProfileInfo(0xFFFFFFFF, &hwpfInfo))
{
*phwpf = hwpfInfo.HWPI_ulHWProfile;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetHwProfileInfo(
int Index,
PHWPROFILEINFO pHwProfileInfo
)
{
m_LastCR = CM_Get_Hardware_Profile_Info_Ex(Index, pHwProfileInfo, 0, m_hMachine);
return (CR_SUCCESS == m_LastCR);
}
ULONG
CMachine::CmGetResDesDataSize(
RES_DES rd
)
{
ULONG Size;
m_LastCR = CM_Get_Res_Des_Data_Size_Ex(&Size, rd, 0, m_hMachine);
if(CR_SUCCESS == m_LastCR)
return Size;
return 0;
}
BOOL
CMachine::CmGetResDesData(
RES_DES rd,
PVOID Buffer,
ULONG BufferSize
)
{
m_LastCR = CM_Get_Res_Des_Data_Ex(rd, Buffer, BufferSize, 0, m_hMachine);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmGetNextResDes(
PRES_DES prdNext,
RES_DES rd,
RESOURCEID ForResource,
PRESOURCEID pTheResource
)
{
m_LastCR = CM_Get_Next_Res_Des_Ex(prdNext, rd, ForResource, pTheResource,
0, m_hMachine);
return (CR_SUCCESS == m_LastCR);
}
void
CMachine::CmFreeResDesHandle(
RES_DES rd
)
{
m_LastCR = CM_Free_Res_Des_Handle(rd);
}
void
CMachine::CmFreeResDes(
PRES_DES prdPrev,
RES_DES rd
)
{
m_LastCR = CM_Free_Res_Des_Ex(prdPrev, rd, 0, m_hMachine);
}
void
CMachine::CmFreeLogConfHandle(
LOG_CONF lc
)
{
m_LastCR = CM_Free_Log_Conf_Handle(lc);
}
int
CMachine::CmGetNumberOfBasicLogConf(
DEVNODE dn
)
{
LOG_CONF lcFirst;
int nLC = 0;
if (CmGetFirstLogConf(dn, &lcFirst, BASIC_LOG_CONF))
{
LOG_CONF lcNext;
BOOL NoMore = FALSE;
do
{
NoMore = !CmGetNextLogConf(&lcNext, lcFirst, BASIC_LOG_CONF);
CmFreeLogConfHandle(lcFirst);
lcFirst = lcNext;
nLC++;
} while (NoMore);
}
return nLC;
}
BOOL
CMachine::CmGetFirstLogConf(
DEVNODE dn,
LOG_CONF* plc,
ULONG Type
)
{
m_LastCR = CM_Get_First_Log_Conf_Ex(plc, dn, Type, m_hMachine);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmGetNextLogConf(
LOG_CONF* plcNext,
LOG_CONF lcRef,
ULONG Type
)
{
m_LastCR = CM_Get_Next_Log_Conf_Ex(plcNext, lcRef, Type, m_hMachine);
return CR_SUCCESS == m_LastCR;
}
ULONG
CMachine::CmGetArbitratorFreeDataSize(
DEVNODE dn,
RESOURCEID ResType
)
{
ULONG Size;
m_LastCR = CM_Query_Arbitrator_Free_Size_Ex(&Size, dn, ResType,
0, m_hMachine);
if (CR_SUCCESS == m_LastCR)
return Size;
return 0;
}
BOOL
CMachine::CmGetArbitratorFreeData(
DEVNODE dn,
PVOID pBuffer,
ULONG BufferSize,
RESOURCEID ResType
)
{
m_LastCR = CM_Query_Arbitrator_Free_Data_Ex(pBuffer, BufferSize, dn,
ResType, 0, m_hMachine
);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmTestRangeAvailable(
RANGE_LIST RangeList,
DWORDLONG dlBase,
DWORDLONG dlEnd
)
{
m_LastCR = CM_Test_Range_Available(dlBase, dlEnd, RangeList, 0);
return (CR_SUCCESS == m_LastCR);
}
void
CMachine::CmDeleteRange(
RANGE_LIST RangeList,
DWORDLONG dlBase,
DWORDLONG dlLen
)
{
DWORDLONG dlEnd = dlBase + dlLen - 1;
m_LastCR = CM_Delete_Range(dlBase, dlEnd, RangeList, 0);
}
BOOL
CMachine::CmGetFirstRange(
RANGE_LIST RangeList,
DWORDLONG* pdlBase,
DWORDLONG* pdlLen,
RANGE_ELEMENT* pre
)
{
m_LastCR = CM_First_Range(RangeList, pdlBase, pdlLen, pre, 0);
if (CR_SUCCESS == m_LastCR)
{
*pdlLen = *pdlLen - *pdlBase + 1;
return TRUE;
}
return FALSE;
}
BOOL
CMachine::CmGetNextRange(
RANGE_ELEMENT* pre,
DWORDLONG* pdlBase,
DWORDLONG* pdlLen
)
{
m_LastCR = CM_Next_Range(pre, pdlBase, pdlLen, 0);
if (CR_SUCCESS == m_LastCR)
{
*pdlLen = *pdlLen - *pdlBase + 1;
return TRUE;
}
return FALSE;
}
void
CMachine::CmFreeRangeList(
RANGE_LIST RangeList
)
{
m_LastCR = CM_Free_Range_List(RangeList, 0);
}
CONFIGRET
CMachine::CmGetRegistryProperty(
DEVNODE dn,
ULONG Property,
PVOID pBuffer,
ULONG* pBufferSize
)
{
return CM_Get_DevNode_Registry_Property_Ex(dn, Property, NULL,
pBuffer, pBufferSize,
0, m_hMachine
);
}
CONFIGRET
CMachine::CmGetRegistrySoftwareProperty(
DEVNODE dn,
LPCTSTR ValueName,
PVOID pBuffer,
ULONG* pBufferSize
)
{
HKEY hKey;
DWORD Type = REG_SZ;
CONFIGRET CR;
if (CR_SUCCESS == (CR = CM_Open_DevNode_Key_Ex(dn, KEY_READ, 0, RegDisposition_OpenExisting,
&hKey, CM_REGISTRY_SOFTWARE, m_hMachine))) {
if (ERROR_SUCCESS != RegQueryValueEx(hKey, ValueName, NULL, &Type, (const PBYTE)pBuffer,
pBufferSize)) {
CR = CR_REGISTRY_ERROR;
}
RegCloseKey(hKey);
}
return CR;
}
BOOL
CMachine::CmGetDeviceIdListSize(
LPCTSTR Filter,
ULONG* Size,
ULONG Flags
)
{
m_LastCR = CM_Get_Device_ID_List_Size_Ex(Size, Filter, Flags, m_hMachine);
return CR_SUCCESS == m_LastCR;
}
BOOL
CMachine::CmGetDeviceIdList(
LPCTSTR Filter,
TCHAR* Buffer,
ULONG BufferSize,
ULONG Flags
)
{
m_LastCR = CM_Get_Device_ID_List_Ex(Filter, Buffer, BufferSize, Flags, m_hMachine);
return CR_SUCCESS == m_LastCR;
}
CMachineList::~CMachineList()
{
if (!m_listMachines.IsEmpty())
{
POSITION pos = m_listMachines.GetHeadPosition();
CMachine* pMachine;
while (NULL != pos)
{
pMachine = m_listMachines.GetNext(pos);
delete pMachine;
}
m_listMachines.RemoveAll();
}
}
//
// This function creates a machine object on the given machine name
// INPUT:
// hwndParent -- Window Handle to be used as the owner window
// of all possible windows this function may create
// MachineName -- the machine name. Must be in full qualified format
// NULL means the local machine
// ppMachine -- buffer to receive the newly create machine.
//
// OUTPUT:
// TRUE if the machine is created successfully. ppMachine
// is filled with the newly created Machine.
// FALSE if the function failed.
// NOTE:
// The caller should NOT free any machine object retruned
// from this function.
//
BOOL
CMachineList::CreateMachine(
HWND hwndParent,
LPCTSTR MachineName,
CMachine** ppMachine
)
{
ASSERT(ppMachine);
*ppMachine = NULL;
CMachine* pMachine = NULL;
if (!MachineName || _T('\0') == MachineName[0])
{
// local machine.
String strMachineName;
strMachineName.GetComputerName();
pMachine = FindMachine(strMachineName);
}
else
{
pMachine = FindMachine(MachineName);
}
if (NULL == pMachine)
{
pMachine = new CMachine(MachineName);
m_listMachines.AddTail(pMachine);
}
*ppMachine = pMachine;
return NULL != pMachine;
}
CMachine*
CMachineList::FindMachine(
LPCTSTR MachineName
)
{
if (!m_listMachines.IsEmpty())
{
POSITION pos = m_listMachines.GetHeadPosition();
while (NULL != pos)
{
CMachine* pMachine;
pMachine = m_listMachines.GetNext(pos);
if (!lstrcmpi(MachineName, pMachine->GetMachineFullName()))
return pMachine;
}
}
return NULL;
}
#if DBG
void
CMachine::DumpClassDevices()
{
POSITION pos = m_listClass.GetHeadPosition();
CClass* pClass;
String strInsert(TEXT("|--"));
String strClass;
String strDevice;
TRACE1(TEXT("%s\n"), (LPCTSTR)m_pComputer->GetDisplayName());
while (NULL != pos)
{
pClass = m_listClass.GetNext(pos);
strClass = strInsert;
strClass += pClass->GetDisplayName();
TRACE2(TEXT("%s, image index = %d\n"), (LPCTSTR)strClass, pClass->GetImageIndex());
CDevice* pDevice;
PVOID Context;
if (pClass->GetFirstDevice(&pDevice, Context))
{
do
{
strDevice = TEXT(" ");
strDevice += strInsert;
strDevice += pDevice->GetDisplayName();
TRACE3(TEXT("%s, DeviceId = %s, DN = %lx\n"), (LPCTSTR)strDevice,
pDevice->GetDeviceID(), pDevice->GetDevNode());
}while (pClass->GetNextDevice(&pDevice, Context));
}
}
}
void
CMachine::DumpDeviceTree()
{
ASSERT(m_pComputer);
DumpDeviceSubtree(FALSE, TEXT("|--"), m_pComputer);
}
void
CMachine::DumpDeviceSubtree(
BOOL HasParent,
LPCTSTR Insert,
CDevice* pDevice
)
{
CDevice* pSibling;
do {
pSibling = pDevice->GetSibling();
if (HasParent)
TRACE1(TEXT("%s"), Insert);
TRACE2(TEXT("DN = %lx, device= %s\n"), pDevice->GetDevNode(), (LPCTSTR)pDevice->GetDisplayName());
CDevice* pChild = pDevice->GetChild();
if (pChild) {
String str;
str = TEXT(" ");
str += Insert;
DumpDeviceSubtree(TRUE, (LPCTSTR)str, pChild);
}
pDevice = pSibling;
}while (NULL != pDevice);
}
void
CMachine::DumpDevNodeTree()
{
DEVNODE dnRoot, dnStart;
dnRoot = CmGetRootDevNode();
if (!dnRoot)
TRACE0(TEXT("Can not get root devnode\n"));
dnStart = CmGetChild(dnRoot);
if (!dnStart)
TRACE0(TEXT("Root Denode does not have children\n"));
TRACE0(TEXT("Dump Devnode tree\n"));
DumpDevNodeSubtree(TEXT("|__"), dnStart);
}
void
CMachine::DumpDevNodeSubtree(
LPCTSTR Insert,
DEVNODE dn
)
{
ASSERT(Insert);
DEVNODE dnChild, dnSibling;
String strInsert;
String strDeviceID;
do
{
dnSibling = CmGetSibling(dn);
CmGetDeviceIDString(dn, strDeviceID);
TRACE1(TEXT("%s"), Insert);
TRACE2(TEXT("(%lx)%s\n"), dn, (LPCTSTR)strDeviceID);
dnChild = CmGetChild(dn);
if (dnChild)
{
strInsert = TEXT(" ");
strInsert += Insert;
DumpDevNodeSubtree((LPCTSTR)strInsert, dnChild);
}
dn = dnSibling;
} while (dn);
}
#endif
#ifdef DEVL
BOOL
CMachine::LogObject()
{
if (m_LoggingMask & LOG_MASK_COMPUTER)
{
m_LogFile.Logf(TEXT(" COMPUTER <%s> INFORMATION\n\n"), GetMachineFullName());
m_LogFile.Logf(TEXT("hMachine = 0x%lx, total classes = %ld, total devices = %ld\n"),
m_hMachine, m_listClass.GetCount(), m_listDevice.GetCount());
}
if (m_LoggingMask & LOG_MASK_CLASS)
{
CClass* pClass;
POSITION pos = m_listClass.GetHeadPosition();
while (NULL != pos)
{
pClass = m_listClass.GetNext(pos);
LogObject(pClass);
}
}
return TRUE;
}
BOOL
CMachine::LogObject(
CClass* pClass
)
{
ASSERT(pClass && (m_LoggingMask & LOG_MASK_CLASS));
m_LogFile.Logf(TEXT("\n\n CLASS <%s> INFORMATION \n\n"), pClass->GetDisplayName());
int Index;
if (!DiGetClassImageIndex(*pClass, &Index))
LogLastError(TEXT("Unable to get class image index"));
else
m_LogFile.Logf(TEXT("Image index = %ld\n"), Index);
m_LogFile.Logf(TEXT("Total devices = %ld\n"), pClass->GetNumberOfDevices(FALSE));
m_LogFile.Logf(TEXT("Total hidden devices = %ld\n"), pClass->GetNumberOfDevices(TRUE));
TCHAR GuidString[MAX_PATH];
GuidToString(*pClass, GuidString, ARRAYLEN(GuidString));
m_LogFile.Logf(TEXT("Guid = %s\n"), GuidString);
if (m_LoggingMask & LOG_MASK_DEVICE)
{
PVOID Context;
CDevice* pDevice;
if (pClass->GetFirstDevice(&pDevice, Context))
{
do
{
LogObject(pDevice);
} while (pClass->GetNextDevice(&pDevice, Context));
}
else
{
m_LogFile.Log(TEXT("This class has no devices\n"));
}
}
return TRUE;
}
BOOL
CMachine::LogObject(
CDevice* pDevice
)
{
DWORD Status, Problem, Flags;
ASSERT(pDevice);
m_LogFile.Logf(TEXT("\n\n DEVICE <%s> INFORMATION \n\n"), pDevice->GetDisplayName());
m_LogFile.Logf(TEXT("Devnode = 0x%lx\n"), pDevice->GetDevNode());
m_LogFile.Logf(TEXT("Devinst id = %s\n"), pDevice->GetDeviceID());
m_LogFile.Logf(TEXT("IsPnpDevice = %s\n"), pDevice->IsPnpDevice() ?
YES : NO);
m_LogFile.Logf(TEXT("IsBiosDevice = %s\n"), pDevice->IsBiosDevice() ?
YES : NO);
m_LogFile.Logf(TEXT("Has Resources = %s\n"), pDevice->HasResources() ?
YES : NO);
m_LogFile.Logf(TEXT("Has Drivers = %s\n"), pDevice->HasDrivers() ?
YES : NO);
m_LogFile.Logf(TEXT("Non-present device = %s\n"), pDevice->IsPhantom() ?
YES : NO);
if (pDevice->GetConfigFlags(&Flags))
m_LogFile.Logf(TEXT("Config flags = 0x%lx\n"), Flags);
else
m_LogFile.Logf(TEXT("Failed to get config flags, CR = 0x%lx\n"),
m_LastCR);
if (pDevice->GetStatus(&Status, &Problem))
m_LogFile.Logf(TEXT("Status = 0x%lx, Problem = 0x%lx\n"),
Status, Problem);
else
m_LogFile.Logf(TEXT("Failed to get Status/problem, CR = 0x%lx\n"),
m_LastCR);
return TRUE;
}
#endif
|
YangHao666666/hawq
|
src/test/feature/Ranger/test_ranger.cpp
|
<reponame>YangHao666666/hawq
/*
* 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.
*/
#include "test_ranger.h"
#include "policy_helper.h"
#include <string>
#include <pwd.h>
#include "lib/command.h"
#include "lib/gpfdist.h"
#include "lib/string_util.h"
using std::vector;
using std::string;
using hawq::test::SQLUtility;
using hawq::test::Command;
TestHawqRanger::TestHawqRanger()
{
initfile = hawq::test::stringFormat("Ranger/sql/init_file");
rangerHost = RANGER_HOST;
}
TEST_F(TestHawqRanger, BasicTest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
hawq::test::GPfdist gpdfist(&util);
gpdfist.init_gpfdist();
string rootPath(util.getTestRootPath());
auto cmd = hawq::test::stringFormat("ls -l %s/Ranger/sql/normal/*.sql 2>/dev/null | grep \"^-\" | wc -l", rootPath.c_str());
int sql_num = std::atoi(Command::getCommandOutput(cmd).c_str());
int writableTableCase = 28;
cmd = hawq::test::stringFormat("cp %s/Ranger/data/copydata.txt /tmp/a.txt", rootPath.c_str());
Command::getCommandStatus(cmd);
// clear environment
for (int i = 1; i <= sql_num; i++) {
// delete user_num
std::string normalusername = hawq::test::stringFormat("usertest%d", i);
std::string superusername = hawq::test::stringFormat("usersuper%d", i);
util.execute(hawq::test::stringFormat("drop role %s;",normalusername.c_str()), false);
util.execute(hawq::test::stringFormat("drop role %s;",superusername.c_str()), false);
// delete policy
std::string cmd = hawq::test::stringFormat("ls -l %s/Ranger/policy/%d/ 2>/dev/null| grep \"^-\" | wc -l ", rootPath.c_str(), i);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -d policy%d-%d", rootPath.c_str(), rangerHost.c_str(), i, j);
Command::getCommandStatus(cmd);
}
}
for (int i = 1; i <= sql_num; i++) {
// create user_num
std::string superusername = hawq::test::stringFormat("usersuper%d", i);;
std::string normalusername = hawq::test::stringFormat("usertest%d", i);;
util.execute(hawq::test::stringFormat("create role %s with login createdb superuser;", superusername.c_str()),true);
if(i == writableTableCase) { //for writable external table
util.execute(hawq::test::stringFormat("create role %s with login createdb CREATEEXTTABLE(type='writable') CREATEROLE;", normalusername.c_str()),true);
}
else {
util.execute(hawq::test::stringFormat("create role %s with login createdb CREATEEXTTABLE CREATEROLE;", normalusername.c_str()),true);
}
cmd = hawq::test::stringFormat("python %s/Ranger/rangeruser.py -h %s -u %s,%s", rootPath.c_str(),
rangerHost.c_str(),normalusername.c_str(), superusername.c_str());
Command::getCommandStatus(cmd);
//run sql by different users
string normal_sqlfile = hawq::test::stringFormat("Ranger/sql/normal/%d.sql", i);
string super_sqlfile = hawq::test::stringFormat("Ranger/sql/super/%d.sql", i);
string admin_sqlfile = hawq::test::stringFormat("Ranger/sql/admin/%d.sql", i);
string normal_ansfile_fail = hawq::test::stringFormat("Ranger/ans/normal%d_fail.ans", i);
string super_ansfile_fail = hawq::test::stringFormat("Ranger/ans/super%d_fail.ans", i);
string admin_ansfile = hawq::test::stringFormat("Ranger/ans/adminfirst%d.ans", i);
cmd = hawq::test::stringFormat("ls -l %s/Ranger/policy/%d/ 2>/dev/null| grep \"^-\" | wc -l", rootPath.c_str(), i);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
cmd = hawq::test::stringFormat("ls -l %s/Ranger/sql/super/%d.sql 2>/dev/null| grep \"^-\" | wc -l", rootPath.c_str(), i);
int supersqlexist = std::atoi(Command::getCommandOutput(cmd).c_str());
if (policy_num > 0){
if (supersqlexist) {
util.execSQLFile(super_sqlfile, super_ansfile_fail, initfile, true, true);
}
else {
util.execSQLFile(normal_sqlfile, normal_ansfile_fail, initfile, true, true);
}
}
util.execSQLFile(admin_sqlfile, admin_ansfile, initfile, true, true);
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -a %s/Ranger/policy/%d/%d.json", rootPath.c_str(), rangerHost.c_str(), rootPath.c_str(), i, j);
Command::getCommandStatus(cmd);
}
}
sleep(60);
for (int i = 1; i <= sql_num; i++) {
//run sql by different users
string normal_sqlfile = hawq::test::stringFormat("Ranger/sql/normal/%d.sql", i);
string super_sqlfile = hawq::test::stringFormat("Ranger/sql/super/%d.sql", i);
string normal_ansfile_success = hawq::test::stringFormat("Ranger/ans/normal%d_success.ans", i);
string super_ansfile_success = hawq::test::stringFormat("Ranger/ans/super%d_success.ans", i);
cmd = hawq::test::stringFormat("ls -l %s/Ranger/policy/%d/ 2>/dev/null| grep \"^-\" | wc -l", rootPath.c_str(), i);
cmd = hawq::test::stringFormat("ls -l %s/Ranger/sql/super/%d.sql 2>/dev/null | grep \"^-\" | wc -l", rootPath.c_str(), i);
int supersqlexist = std::atoi(Command::getCommandOutput(cmd).c_str());
util.execSQLFile(normal_sqlfile, normal_ansfile_success, initfile, true, true);
if (supersqlexist) {
util.execSQLFile(super_sqlfile, super_ansfile_success, initfile, true, true);
}
}
//using gpadmin to clear database environment.
for (int i = 1; i <= sql_num; i++) {
string admin_sqlfile = hawq::test::stringFormat("Ranger/sql/admin/%d.sql", i);
string admin_ansfile = hawq::test::stringFormat("Ranger/ans/adminsecond%d.ans", i);
util.execSQLFile(admin_sqlfile, admin_ansfile, initfile, true, true);
}
for (int i = 1; i <= sql_num; i++) {
// delete user_num
std::string normalusername = hawq::test::stringFormat("usertest%d", i);
std::string superusername = hawq::test::stringFormat("usersuper%d", i);
util.execute(hawq::test::stringFormat("drop role %s;",normalusername.c_str()), false);
util.execute(hawq::test::stringFormat("drop role %s;",superusername.c_str()), false);
// delete policy
std::string cmd = hawq::test::stringFormat("ls -l %s/Ranger/policy/%d/ 2>/dev/null | grep \"^-\" | wc -l", rootPath.c_str(), i);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -d policy%d-%d", rootPath.c_str(), rangerHost.c_str(), i, j);
Command::getCommandStatus(cmd);
}
}
gpdfist.finalize_gpfdist();
}
}
static void clear_env(SQLUtility &util, int sql_id, string rootPath, string rangerHost)
{
int i = sql_id;
// delete user_num
std::string normalusername = hawq::test::stringFormat("usertest%d", i);
std::string superusername = hawq::test::stringFormat("usersuper%d", i);
util.execute(hawq::test::stringFormat("drop role %s;",normalusername.c_str()), false);
util.execute(hawq::test::stringFormat("drop role %s;",superusername.c_str()), false);
// delete policy
std::string cmd = hawq::test::stringFormat("ls -l %s/Ranger/policy/%d/ 2>/dev/null| grep \"^-\" | wc -l ", rootPath.c_str(), i);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -d policy%d-%d", rootPath.c_str(), rangerHost.c_str(), i, j);
Command::getCommandStatus(cmd);
}
}
TEST_F(TestHawqRanger, FallbackTest) {
SQLUtility util;
PolicyHelper helper(util.getTestRootPath(), rangerHost);
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
int idx = 10000;
int ret = 0;
const char * prefix = "manual";
std::string db = "hawq_feature_test_db";
std::string schema = get_private_schema_name();
std::string user = hawq::test::stringFormat("user%s%d", prefix, idx);
addUser(&util, prefix, idx, false);
// all needed policies
helper.AddSchemaPolicy("policy10000-1", user, db, schema, {"usage-schema"});
ret = helper.ActivateAllPoliciesOnRanger();
EXPECT_EQ(0,ret);
runSQLFile(&util, prefix, "success", idx, false, true, true);
//delete user
delUser(&util, prefix, idx);
//delete policy
helper.DeletePolicyOnRanger("pxfpolicy10000-1");
}
}
TEST_F(TestHawqRanger, DenyTest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
clearEnv(&util, "deny", 1);
util.execute("create table a(i int);");
addUser(&util, "deny", 1, true);
runSQLFile(&util, "deny", "succeed", 1);
addPolicy(&util, "deny", 1);
runSQLFile(&util, "deny", "fail", 1);
clearEnv(&util, "deny", 1);
}
}
TEST_F(TestHawqRanger, DenyExcludeTest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
clearEnv(&util, "denyexclude", 2);
clearEnv(&util, "deny", 2);
util.execute("create table a(i int);");
addUser(&util, "denyexclude", 2, true);
runSQLFile(&util, "denyexclude", "succeed", 2);
addPolicy(&util, "deny", 2);
runSQLFile(&util, "denyexclude", "fail", 2);
addPolicy(&util, "denyexclude", 2);
runSQLFile(&util, "denyexclude", "succeed2", 2);
clearEnv(&util, "denyexclude", 2);
clearEnv(&util, "deny", 2);
}
}
TEST_F(TestHawqRanger, AllowExcludeTest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
clearEnv(&util, "allowexclude", 3);
clearEnv(&util, "allow", 3);
util.execute("create table a(i int);");
addUser(&util, "allowexclude", 3, false);
addPolicy(&util, "allow", 3);
runSQLFile(&util, "allowexclude", "succeed", 3);
addPolicy(&util, "allowexclude", 3);
runSQLFile(&util, "allowexclude", "fail", 3);
clearEnv(&util, "allowexclude", 3);
clearEnv(&util, "allow", 3);
}
}
TEST_F(TestHawqRanger, ResourceExcludeTest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
clearEnv(&util, "resourceexclude", 4);
clearEnv(&util, "allow", 4);
util.execute("create table a(i int);");
util.execute("create table b(i int);");
addUser(&util, "resourceexclude", 4, false);
addPolicy(&util, "resourceexclude", 4);
// select a fail, select b succeed
runSQLFile(&util, "resourceexclude", "fail", 4);
//add usage-schema to public
addPolicy(&util, "allow", 4);
runSQLFile(&util, "resourceexclude", "succeed", 4);
clearEnv(&util, "resourceexclude", 4);
clearEnv(&util, "allow", 4);
}
}
TEST_F(TestHawqRanger, ResourceExcludeStarTest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
clearEnv(&util, "resourceexclude", 5);
clearEnv(&util, "allow", 5);
util.execute("create table a(i int);");
addUser(&util, "resourceexclude", 5, false);
addPolicy(&util, "resourceexclude", 5);
// fail in select table a , succeed in select table b
runSQLFile(&util, "resourceexclude", "fail", 5);
//add usage-schema to public
addPolicy(&util, "allow", 5);
runSQLFile(&util, "resourceexclude", "fail2", 5);
clearEnv(&util, "resourceexclude", 5);
clearEnv(&util, "allow", 5);
}
}
TEST_F(TestHawqRanger, ResourceIncludeATest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
clearEnv(&util, "allow", 6);
util.execute("create table a(i int);");
addUser(&util, "allow", 6, false);
addPolicy(&util, "allow", 6);
runSQLFile(&util, "allow", "fail", 6);
clearEnv(&util, "allow", 6);
}
}
/**
* read HIVE data using hcatalog(read-only) with PXF
*/
TEST_F(TestHawqRanger, PXFHcatalogTest) {
SQLUtility util;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
/*
* create a table in hive and populate some rows
*/
clearEnv(&util, "pxf", 1);
string rootPath(util.getTestRootPath());
string sqlPath = rootPath + "/Ranger/data/testhive.sql";
auto cmd = hawq::test::stringFormat("hive -f %s", sqlPath.c_str());
Command::getCommandStatus(cmd);
/*
* create a user and query this table, fail.
*/
addUser(&util, "pxf", 1, false);
runSQLFile(&util, "pxf", "fail", 1);
/*
* add allow policies for this user and query again, succeed.
*/
/*
usage of default
select of table
usage of current schema(e.g.testhawqranger_hcatalogtest)
*/
addPolicy(&util, "pxf", 1);
runSQLFile(&util, "pxf", "success", 1);
//clean
clearEnv(&util, "pxf", 1);
}
}
/**
* read and write HDFS data using external table with PXF
*/
TEST_F(TestHawqRanger, PXFHDFSTest) {
SQLUtility util;
PolicyHelper helper(util.getTestRootPath(), rangerHost);
//case idx and folder prefix
const char * prefix = "pxf";
int idx = 0;
int ret = 0;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
std::string db = "hawq_feature_test_db";
std::string schema = get_private_schema_name();
bool usingDefaultSchema= false;
std::string user;
// clean hdfs folder
std::string cmd = "";
cmd = hawq::test::stringFormat("hdfs dfs -rm -r /ranger_test/");
Command::getCommandStatus(cmd);
cmd = hawq::test::stringFormat("hdfs dfs -mkdir /ranger_test/");
Command::getCommandStatus(cmd);
// -- write --
idx = 2;
addUser(&util, prefix, idx, false);
user = hawq::test::stringFormat("user%s%d", prefix ,idx);
runSQLFile(&util, prefix, "fail", 2, usingDefaultSchema, false, true); // create writable table
// all needed policies
helper.AddSchemaPolicy("pxfpolicy2-1", user, db, schema, {"usage-schema","create"});
helper.AddProtocolPolicy("pxfpolicy2-2", user, "pxf", {"insert"});
helper.AddTablePolicy("pxfpolicy2-3", user, db, schema, "pxf_hdfs_writabletbl_1", {"insert"});
ret = helper.ActivateAllPoliciesOnRanger();
EXPECT_EQ(0,ret);
runSQLFile(&util, prefix, "success", 2, usingDefaultSchema, false, true); // create table
runSQLFile(&util, prefix, "success", 3, usingDefaultSchema, false, true); // insert
// -- read --
idx = 3;
addUser(&util, prefix, idx, false);
user = hawq::test::stringFormat("user%s%d", prefix ,idx);
runSQLFile(&util, prefix, "fail", 4, usingDefaultSchema, false, true); // create readable table
helper.Reset();
// all needed policies
helper.AddSchemaPolicy("pxfpolicy3-1", user, db, schema, {"usage-schema","create"});
helper.AddProtocolPolicy("pxfpolicy3-2", user, "pxf", {"select"});
helper.AddTablePolicy("pxfpolicy3-3", user, db, schema, "pxf_hdfs_textsimple_r1", {"select"});
ret = helper.ActivateAllPoliciesOnRanger();
EXPECT_EQ(0,ret);
runSQLFile(&util, prefix, "success", 4, usingDefaultSchema, false, true); // create table
runSQLFile(&util, prefix, "success", 5, usingDefaultSchema, false, true); // select
//delete user
delUser(&util, prefix, 2);
delUser(&util, prefix, 3);
//delete policy
helper.DeletePolicyOnRanger("pxfpolicy2-1");
helper.DeletePolicyOnRanger("pxfpolicy2-2");
helper.DeletePolicyOnRanger("pxfpolicy2-3");
helper.DeletePolicyOnRanger("pxfpolicy3-1");
helper.DeletePolicyOnRanger("pxfpolicy3-2");
helper.DeletePolicyOnRanger("pxfpolicy3-3");
}
}
/**
* read Hive data using external table with PXF
*/
TEST_F(TestHawqRanger, PXFHiveTest) {
SQLUtility util;
PolicyHelper helper(util.getTestRootPath(), rangerHost);
//case idx and folder prefix
const char * prefix = "pxf";
int idx = 0;
int ret = 0;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
std::string db = "hawq_feature_test_db";
std::string schema = get_private_schema_name();
bool usingDefaultSchema= false;
std::string user;
// create hive table
string rootPath(util.getTestRootPath());
string sqlPath = rootPath + "/Ranger/data/testhive_externaltable.sql";
auto cmd = hawq::test::stringFormat("hive -f %s", sqlPath.c_str());
Command::getCommandStatus(cmd);
// -- read --
idx = 4;
addUser(&util, prefix, idx, false);
user = hawq::test::stringFormat("user%s%d", prefix ,idx);
runSQLFile(&util, prefix, "fail", 6, usingDefaultSchema, false, true); // create readable table
helper.Reset();
// all needed policies
helper.AddSchemaPolicy("pxfpolicy4-1", user, db, schema, {"usage-schema","create"});
helper.AddProtocolPolicy("pxfpolicy4-2", user, "pxf", {"select"});
helper.AddTablePolicy("pxfpolicy4-3", user, db, schema, "testhive_ext", {"select"});
ret = helper.ActivateAllPoliciesOnRanger();
EXPECT_EQ(0,ret);
runSQLFile(&util, prefix, "success", 6, usingDefaultSchema, false, true); // create table
runSQLFile(&util, prefix, "success", 7, usingDefaultSchema, false, true); // select
//delete user
delUser(&util, prefix, idx);
//delete policy
helper.DeletePolicyOnRanger("pxfpolicy4-1");
helper.DeletePolicyOnRanger("pxfpolicy4-2");
helper.DeletePolicyOnRanger("pxfpolicy4-3");
}
}
/**
* read HBase data using external table with PXF
*/
TEST_F(TestHawqRanger, PXFHBaseTest) {
SQLUtility util;
PolicyHelper helper(util.getTestRootPath(), rangerHost);
//case idx and folder prefix
const char * prefix = "pxf";
int idx = 0;
int ret = 0;
if (util.getGUCValue("hawq_acl_type") == "ranger")
{
std::string db = "hawq_feature_test_db";
std::string schema = get_private_schema_name();
bool usingDefaultSchema= false;
std::string user;
// create hbase table
auto cmd = hawq::test::stringFormat(
"echo \" create 'test_hbase','f1'; put 'test_hbase','r1', 'f1:col1','100' \" | hbase shell");
Command::getCommandStatus(cmd);
// -- read --
idx = 5;
addUser(&util, prefix, idx, false);
user = hawq::test::stringFormat("user%s%d", prefix ,idx);
runSQLFile(&util, prefix, "fail", 8, usingDefaultSchema, false, true); // create readable table
helper.Reset();
// all needed policies
helper.AddSchemaPolicy("pxfpolicy5-1", user, db, schema, {"usage-schema","create"});
helper.AddProtocolPolicy("pxfpolicy5-2", user, "pxf", {"select"});
helper.AddTablePolicy("pxfpolicy5-3", user, db, schema, "test_hbase", {"select"});
ret = helper.ActivateAllPoliciesOnRanger();
EXPECT_EQ(0,ret);
runSQLFile(&util, prefix, "success", 8, usingDefaultSchema, false, true); // create table
runSQLFile(&util, prefix, "success", 9, usingDefaultSchema, false, true); // select
//delete user
delUser(&util, prefix, idx);
//delete policy
helper.DeletePolicyOnRanger("pxfpolicy5-1");
helper.DeletePolicyOnRanger("pxfpolicy5-2");
helper.DeletePolicyOnRanger("pxfpolicy5-3");
// drop hbase table
cmd = hawq::test::stringFormat(
"echo \" disable 'test_hbase'; drop 'test_hbase' \" | hbase shell");
Command::getCommandStatus(cmd);
}
}
// only drop user in database
void TestHawqRanger::delUser(hawq::test::SQLUtility* util, std::string case_name, int user_index)
{
string rootPath = util->getTestRootPath();
string cmd = "";
std::string username = hawq::test::stringFormat("user%s%d", case_name.c_str(), user_index);
util->execute(hawq::test::stringFormat("drop role %s;", username.c_str()), false);
}
void TestHawqRanger::addUser(hawq::test::SQLUtility* util, std::string case_name, int user_index, bool full_policy, int writable_index)
{
string rootPath = util->getTestRootPath();
string cmd = "";
if (user_index == -1)
{
cmd = hawq::test::stringFormat("ls -l %s/Ranger/sql/%s/*.sql 2>/dev/null| grep \"^-\" | wc -l", rootPath.c_str(), case_name.c_str());
int sql_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int i = 1; i <= sql_num; i++) {
// create user_num
std::string denyusername = hawq::test::stringFormat("user%s%d", case_name.c_str() ,i);
util->execute(hawq::test::stringFormat("create role %s with login createdb CREATEEXTTABLE CREATEROLE;", denyusername.c_str()),true);
if (full_policy)
{
cmd = hawq::test::stringFormat("python %s/Ranger/rangeruser.py -h %s -u %s -f True", rootPath.c_str(),
rangerHost.c_str(),denyusername.c_str());
} else {
cmd = hawq::test::stringFormat("python %s/Ranger/rangeruser.py -h %s -u %s", rootPath.c_str(),
rangerHost.c_str(),denyusername.c_str());
}
Command::getCommandStatus(cmd);
if (full_policy)
{
sleep(60);
}
}
} else {
std::string denyusername = hawq::test::stringFormat("user%s%d", case_name.c_str() ,user_index);
util->execute(hawq::test::stringFormat("create role %s with login createdb CREATEEXTTABLE CREATEROLE;", denyusername.c_str()),true);
if (full_policy)
{
cmd = hawq::test::stringFormat("python %s/Ranger/rangeruser.py -h %s -u %s -f True", rootPath.c_str(),
rangerHost.c_str(),denyusername.c_str());
} else
{
cmd = hawq::test::stringFormat("python %s/Ranger/rangeruser.py -h %s -u %s", rootPath.c_str(),
rangerHost.c_str(),denyusername.c_str());
}
Command::getCommandStatus(cmd);
if (full_policy)
{
sleep(60);
}
}
}
void TestHawqRanger::clearEnv(hawq::test::SQLUtility* util, std::string case_name, int user_index)
{
string rootPath = util->getTestRootPath();
string cmd = "";
if (user_index == -1)
{
cmd = hawq::test::stringFormat("ls -l %s/Ranger/sql/%s/*.sql 2>/dev/null| grep \"^-\" | wc -l", rootPath.c_str(), case_name.c_str());
int sql_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int i = 1; i <= sql_num; i++) {
// delete user_num
std::string denyusername = hawq::test::stringFormat("user%s%d", case_name.c_str(), i);
util->execute(hawq::test::stringFormat("drop role %s;",denyusername.c_str()), false);
// delete policy
std::string cmd = hawq::test::stringFormat("ls -l %s/Ranger/%spolicy/%d/ 2>/dev/null| grep \"^-\" | wc -l ", rootPath.c_str(), case_name.c_str(), i);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -d %spolicy%d-%d", rootPath.c_str(), rangerHost.c_str(), case_name.c_str(), i, j);
Command::getCommandStatus(cmd);
}
}
} else {
// delete user_num
std::string denyusername = hawq::test::stringFormat("user%s%d", case_name.c_str(), user_index);
util->execute(hawq::test::stringFormat("drop role %s;",denyusername.c_str()), false);
// delete policy
std::string cmd = hawq::test::stringFormat("ls -l %s/Ranger/%spolicy/%d/ 2>/dev/null| grep \"^-\" | wc -l ", rootPath.c_str(), case_name.c_str(), user_index);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -d %spolicy%d-%d", rootPath.c_str(), rangerHost.c_str(), case_name.c_str(), user_index, j);
Command::getCommandStatus(cmd);
}
}
}
void TestHawqRanger::runSQLFile(hawq::test::SQLUtility* util, std::string case_name, std::string ans_suffix, int sql_index, bool usingDefaultSchema, bool printTupleOnly, bool focus_run)
{
string rootPath = util->getTestRootPath();
auto cmd = hawq::test::stringFormat("ls -l %s/Ranger/sql/%s/*.sql 2>/dev/null| grep \"^-\" | wc -l", rootPath.c_str(), case_name.c_str());
// run all the sql files in folder.
if(sql_index == -1)
{
int sql_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int i = 1; i <= sql_num; i++) {
string deny_sqlfile = hawq::test::stringFormat("Ranger/sql/%s/%d.sql", i, case_name.c_str());
string deny_ansfile_succeed = hawq::test::stringFormat("Ranger/ans/%s%d_%s.ans", case_name.c_str(), i, ans_suffix.c_str());
auto cmd = hawq::test::stringFormat("ls -l %s/Ranger/%spolicy/%d/ 2>/dev/null| grep \"^-\"| wc -l", rootPath.c_str(), case_name.c_str(), i);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
if (focus_run || policy_num > 0){
util->execSQLFile(deny_sqlfile, deny_ansfile_succeed, initfile, usingDefaultSchema, printTupleOnly);
}
}
} else {
string deny_sqlfile = hawq::test::stringFormat("Ranger/sql/%s/%d.sql", case_name.c_str(), sql_index);
string deny_ansfile_succeed = hawq::test::stringFormat("Ranger/ans/%s%d_%s.ans", case_name.c_str(), sql_index, ans_suffix.c_str());
auto cmd = hawq::test::stringFormat("ls -l %s/Ranger/%spolicy/%d/ 2>/dev/null| grep \"^-\"| wc -l", rootPath.c_str(), case_name.c_str(), sql_index);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
if (focus_run || policy_num > 0){
util->execSQLFile(deny_sqlfile, deny_ansfile_succeed, initfile, usingDefaultSchema, printTupleOnly);
}
}
}
void TestHawqRanger::addPolicy(hawq::test::SQLUtility* util, std::string case_name, int policy_index)
{
string rootPath = util->getTestRootPath();
auto cmd = hawq::test::stringFormat("ls -l %s/Ranger/sql/%s/*.sql 2>/dev/null| grep \"^-\" | wc -l", rootPath.c_str(), case_name.c_str());
if (policy_index == -1)
{
int sql_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int i = 1; i <= sql_num; i++) {
auto cmd = hawq::test::stringFormat("ls -l %s/Ranger/%spolicy/%d/ 2>/dev/null| grep \"^-\"| wc -l", rootPath.c_str(), case_name.c_str(), i);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -a %s/Ranger/%spolicy/%d/%d.json", rootPath.c_str(), rangerHost.c_str(), rootPath.c_str(), case_name.c_str(), i, j);
Command::getCommandStatus(cmd);
}
}
} else {
auto cmd = hawq::test::stringFormat("ls -l %s/Ranger/%spolicy/%d/ 2>/dev/null| grep \"^-\"| wc -l", rootPath.c_str(), case_name.c_str(), policy_index);
int policy_num = std::atoi(Command::getCommandOutput(cmd).c_str());
for (int j = 1; j <= policy_num; j++) {
cmd = hawq::test::stringFormat("python %s/Ranger/rangerpolicy.py -h %s -a %s/Ranger/%spolicy/%d/%d.json", rootPath.c_str(), rangerHost.c_str(), rootPath.c_str(), case_name.c_str(), policy_index, j);
Command::getCommandStatus(cmd);
}
}
sleep(60);
}
/**
* get the private schema name based by current test
* example: testhawqranger_xxxtest
*/
std::string TestHawqRanger::get_private_schema_name()
{
const ::testing::TestInfo *const test_info = ::testing::UnitTest::GetInstance()->current_test_info();
string data = string(test_info->test_case_name()) + "_" + test_info->name();
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
return data;
}
|
FabianVolkers/portfolio
|
homepage/portfolio/migrations/0003_project_spotlight.py
|
<gh_stars>0
# Generated by Django 3.0.7 on 2020-06-30 16:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0002_auto_20200630_1631'),
]
operations = [
migrations.AddField(
model_name='project',
name='spotlight',
field=models.BooleanField(default=True),
preserve_default=False,
),
]
|
NCAR/sage-gateway-archive
|
src/main/java/sgf/gateway/service/security/impl/spring/GroupMembershipEventImpl.java
|
<reponame>NCAR/sage-gateway-archive<filename>src/main/java/sgf/gateway/service/security/impl/spring/GroupMembershipEventImpl.java
package sgf.gateway.service.security.impl.spring;
import org.springframework.context.ApplicationEvent;
import sgf.gateway.model.security.Group;
import sgf.gateway.model.security.User;
import sgf.gateway.service.security.GroupMembershipEvent;
/**
* Implementation of {@link GroupMembershipEvent} specific to the Spring application context (i.e. instances of this class will be detected by the Spring event
* infrastructure).
*/
public class GroupMembershipEventImpl extends ApplicationEvent implements GroupMembershipEvent {
private User user;
private Group group;
/**
* Constructor
*
* @param source : the object that published the event
* @param user : the user whose membership in the group has changed
* @param group : the group the membership refers to
*/
public GroupMembershipEventImpl(Object source, User user, Group group) {
super(source);
this.user = user;
this.group = group;
}
public User getUser() {
return user;
}
public Group getGroup() {
return group;
}
}
|
sacloud/libsacloud-v2
|
sacloud/accessor/size_mb_test.go
|
<filename>sacloud/accessor/size_mb_test.go
package accessor
import (
"testing"
"github.com/stretchr/testify/require"
)
type dummySizeMBAccessor struct {
size int
}
func (d *dummySizeMBAccessor) GetSizeMB() int {
return d.size
}
func (d *dummySizeMBAccessor) SetSizeMB(size int) {
d.size = size
}
func TestSizeMBAccessor(t *testing.T) {
expects := []struct {
input int
expect int
}{
{
input: 0,
expect: 0,
},
{
input: 1,
expect: 1024 * 1,
},
{
input: 2,
expect: 1024 * 2,
},
}
for _, tc := range expects {
var target SizeMB = &dummySizeMBAccessor{}
SetSizeGB(target, tc.input)
require.Equal(t, tc.input, GetSizeGB(target))
require.Equal(t, tc.expect, target.GetSizeMB())
}
}
|
danlangford/LegendsBrowser
|
src/main/java/legends/model/events/CompetitionEvent.java
|
package legends.model.events;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import legends.model.Entity;
import legends.model.HistoricalFigure;
import legends.model.Occasion;
import legends.model.Schedule;
import legends.model.World;
import legends.model.events.basic.HfRelatedEvent;
import legends.xml.annotation.Xml;
import legends.xml.annotation.XmlSubtype;
@XmlSubtype("competition")
public class CompetitionEvent extends OccasionEvent implements HfRelatedEvent {
@Xml("winner_hfid")
private int winnerHfId = -1;
@Xml(value = "competitor_hfid", elementClass = Integer.class, multiple = true)
private List<Integer> competitorHfIds = new ArrayList<>();
public int getWinnerHfId() {
return winnerHfId;
}
public void setWinnerHfId(int winnerHfId) {
this.winnerHfId = winnerHfId;
}
public List<Integer> getCompetitorHfIds() {
return competitorHfIds;
}
@Override
public boolean isRelatedToHf(int hfId) {
return winnerHfId == hfId || competitorHfIds.contains(hfId);
}
@Override
public String getShortDescription() {
Entity civ = World.getEntity(civId);
Occasion occ = civ.getOccasion(occasionId);
Schedule sch = occ.getSchedule(scheduleId);
String competitors = "";
if (competitorHfIds.size() > 0) {
competitors = ". Competing were ";
List<String> list = competitorHfIds.stream().map(World::getHistoricalFigure).map(HistoricalFigure::getLink)
.collect(Collectors.toList());
String last = list.remove(list.size() - 1);
competitors += list.stream().collect(Collectors.joining(", ")) + " and " + last;
}
String winner = "";
if (winnerHfId != -1)
winner = ". " + World.getHistoricalFigure(winnerHfId).getLink() + " was the victor";
String type = sch.getType();
switch (type) {
case "poetry competition":
type = "competition involving " + World.getPoeticForm(sch.getReference()).getLink();
break;
case "musical competition":
type = "competition involving " + World.getMusicalForm(sch.getReference()).getLink();
break;
case "dance competition":
type = "competition involving " + World.getDanceForm(sch.getReference()).getLink();
break;
case "":
type = "competition";
}
return civ.getLink() + " held a " + type + " " + location.getLink("in") + " as part of " + occ.getName()
+ competitors + winner;
}
}
|
aliyun/aliyun-tablestore-java-sdk
|
src/test/java/com/alicloud/openservices/tablestore/timeline/functionTest/TestTimelineService.java
|
<filename>src/test/java/com/alicloud/openservices/tablestore/timeline/functionTest/TestTimelineService.java<gh_stars>10-100
package com.alicloud.openservices.tablestore.timeline.functionTest;
import com.alicloud.openservices.tablestore.model.ColumnValue;
import com.alicloud.openservices.tablestore.model.search.SearchQuery;
import com.alicloud.openservices.tablestore.model.search.query.BoolQuery;
import com.alicloud.openservices.tablestore.model.search.query.RangeQuery;
import com.alicloud.openservices.tablestore.model.search.query.TermQuery;
import com.alicloud.openservices.tablestore.model.search.sort.FieldSort;
import com.alicloud.openservices.tablestore.model.search.sort.Sort;
import com.alicloud.openservices.tablestore.model.search.sort.SortOrder;
import com.alicloud.openservices.tablestore.timeline.TimelineMetaStore;
import com.alicloud.openservices.tablestore.timeline.TimelineQueue;
import com.alicloud.openservices.tablestore.timeline.TimelineException;
import com.alicloud.openservices.tablestore.timeline.TimelineStore;
import com.alicloud.openservices.tablestore.timeline.common.ServiceWrapper;
import com.alicloud.openservices.tablestore.timeline.model.*;
import com.alicloud.openservices.tablestore.timeline.query.SearchParameter;
import com.alicloud.openservices.tablestore.timeline.query.SearchResult;
import org.junit.*;
import java.util.Arrays;
import static com.alicloud.openservices.tablestore.timeline.query.FieldCondition.*;
import static org.junit.Assert.*;
public class TestTimelineService {
private static ServiceWrapper wrapper = null;
@BeforeClass
public static void setUp() throws Exception {
wrapper = ServiceWrapper.newInstance();
TimelineMetaStore metaService = wrapper.getMetaStore();
TimelineStore storeTableService = wrapper.getStoreTableStore();
metaService.prepareTables();
storeTableService.prepareTables();
TimelineIdentifier identifier = new TimelineIdentifier.Builder()
.addField("timelineId", "group_a")
.addField("long", 1000L)
.build();
TimelineMeta insertGroup = new TimelineMeta(identifier)
.setField("groupName", "tablestore")
.setField("createTime", 1);
metaService.insert(insertGroup);
TimelineQueue groupStore = storeTableService.createTimelineQueue(identifier);
for (int i = 0; i < 10; i++) {
TimelineMessage msg = generateMessage(i);
groupStore.store(msg);
}
/**
* wait for sync data into searchIndex
* */
ServiceWrapper.sleepForSyncData();
}
@AfterClass
public static void after() throws Exception {
wrapper.getMetaStore().dropAllTables();
wrapper.getStoreTableStore().dropAllTables();
wrapper.shutdown();
}
@Test
public void testSearchBySearchParameter() {
TimelineIdentifier identifier = new TimelineIdentifier.Builder()
.addField("timelineId", "group_a")
.addField("long", 1000L)
.build();
TimelineStore storeService = wrapper.getStoreTableStore();
SearchParameter parameter = new SearchParameter(
and(
field("text").equals("hello"),
field("timestamp").greaterEqual(0),
field("timestamp").lessEqual(5),
field("receivers").equals("user_a")
)
).limit(1).offset(1).calculateTotalCount().orderBy(new String[]{"timestamp"}, SortOrder.ASC);
SearchResult<TimelineEntry> searchResult = storeService.search(parameter);
assertTrue(searchResult.isAllSucceed());
assertEquals(6, searchResult.getTotalCount());
assertNotNull(searchResult.getNextToken());
assertEquals(1, searchResult.getEntries().size());
TimelineEntry entry = searchResult.getEntries().get(0).getData();
assertEquals("hello tablestore1", entry.getMessage().getString("text"));
assertEquals(1, entry.getMessage().getLong("timestamp"));
parameter.withToken(searchResult.getNextToken());
searchResult = storeService.search(parameter);
assertTrue(identifier.equals(searchResult.getEntries().get(0).getIdentifier()));
}
@Test
public void testSearchBySearchQuery() {
TimelineStore storeService = wrapper.getStoreTableStore();
TermQuery termQuery = new TermQuery();
termQuery.setFieldName("receivers");
termQuery.setTerm(ColumnValue.fromString("user_a"));
RangeQuery rangeQuery = new RangeQuery();
rangeQuery.setFieldName("timestamp");
rangeQuery.greaterThanOrEqual(ColumnValue.fromLong(5));
rangeQuery.lessThanOrEqual(ColumnValue.fromLong(6));
BoolQuery boolQuery = new BoolQuery();
boolQuery.setMustQueries(Arrays.asList(termQuery, rangeQuery));
SearchQuery searchQuery = new SearchQuery().setQuery(boolQuery);
searchQuery.setGetTotalCount(true);
searchQuery.setLimit(1);
searchQuery.setOffset(1);
Sort.Sorter fieldSort = new FieldSort("timestamp", SortOrder.DESC);
searchQuery.setSort(new Sort(Arrays.asList(fieldSort)));
SearchResult<TimelineEntry> searchResult1 = storeService.search(searchQuery);
assertTrue(searchResult1.isAllSucceed());
assertEquals(2, searchResult1.getTotalCount());
assertEquals(1, searchResult1.getEntries().size());
TimelineEntry entry1 = searchResult1.getEntries().get(0).getData();
assertEquals("hello tablestore5", entry1.getMessage().getString("text"));
assertEquals(5, entry1.getMessage().getLong("timestamp"));
}
@Test
public void testExceptionSearch() {
TimelineStore storeService = wrapper.getStoreTableStore();
TimelineStore syncService = wrapper.getSyncTableStore();
/**
* Test search exception
* */
TermQuery wrongQuery = new TermQuery();
wrongQuery.setFieldName("notExist");
wrongQuery.setTerm(ColumnValue.fromLong(8));
SearchQuery wrongSearchQuery = new SearchQuery().setQuery(wrongQuery);
wrongSearchQuery.setGetTotalCount(true);
wrongSearchQuery.setLimit(1);
try {
storeService.search(wrongSearchQuery);
} catch (Exception e) {
assertTrue(e instanceof TimelineException);
assertEquals("OTSParameterInvalid", e.getMessage());
}
try {
syncService.search(wrongSearchQuery);
} catch (Exception e) {
assertTrue(e instanceof TimelineException);
assertEquals("The store not support search cause not has data index", e.getMessage());
}
}
@Test
public void testCreateTimelineWithNull() {
TimelineStore storeService = wrapper.getStoreTableStore();
try {
storeService.createTimelineQueue(null);
} catch (Exception e) {
assertTrue(e instanceof TimelineException);
assertEquals("Identifier should not be null.", e.getMessage());
}
}
private static TimelineMessage generateMessage(int i) {
return new TimelineMessage()
.setField("text", "hello tablestore" + i)
.setField("receivers", Arrays.asList("user_a", "user_b"))
.setField("timestamp", i);
}
}
|
lgessler/cts
|
coptic/annis/admin.py
|
from django.contrib import admin
from annis.models import AnnisServer
admin.site.register(AnnisServer)
|
likewindy/FISS
|
src/components/model/style/Xf.js
|
import CellAlignment from './CellAlignment.js';
import CellProtection from './CellProtection.js';
import ExtensionList from './ExtensionList.js';
export default class Xf {
constructor() {
/*
<xsd:complexType name="CT_Xf">
<xsd:sequence>
<xsd:element name="alignment" type="CT_CellAlignment" minOccurs="0" maxOccurs="1"/>
<xsd:element name="protection" type="CT_CellProtection" minOccurs="0" maxOccurs="1"/>
<xsd:element name="extLst" type="CT_ExtensionList" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
<xsd:attribute name="numFmtId" type="ST_NumFmtId" use="optional"/>
<xsd:attribute name="fontId" type="ST_FontId" use="optional"/>
<xsd:attribute name="fillId" type="ST_FillId" use="optional"/>
<xsd:attribute name="borderId" type="ST_BorderId" use="optional"/>
<xsd:attribute name="xfId" type="ST_CellStyleXfId" use="optional"/>
<xsd:attribute name="quotePrefix" type="xsd:boolean" use="optional" default="false"/>
<xsd:attribute name="pivotButton" type="xsd:boolean" use="optional" default="false"/>
<xsd:attribute name="applyNumberFormat" type="xsd:boolean" use="optional"/>
<xsd:attribute name="applyFont" type="xsd:boolean" use="optional"/>
<xsd:attribute name="applyFill" type="xsd:boolean" use="optional"/>
<xsd:attribute name="applyBorder" type="xsd:boolean" use="optional"/>
<xsd:attribute name="applyAlignment" type="xsd:boolean" use="optional"/>
<xsd:attribute name="applyProtection" type="xsd:boolean" use="optional"/>
</xsd:complexType>
*/
this.alignment =new CellAlignment();
this.protection =new CellProtection();
this.extLst =new ExtensionList();
this.numFmtId =null;
this.fontId =null;
this.fillId =null;
this.borderId =null;
this.xfId =null;
this.quotePrefix =false; //boolean
this.pivotButton =false; //boolean
this.applyNumberFormat =false ; //boolean
this.applyFont =false; //boolean
this.applyFill =false; //boolean
this.applyBorder =false; //boolean
this.applyAlignment =false; //boolean
this.applyProtection =false; //boolean
}
SetNumFmtId(numFmtId){
this.numFmtId=numFmtId;
this.applyNumberFormat =true ;
}
SetfontId(fontId){
this.fontId=fontId;
this.applyNumberFormat =true ;
}
SetFillId(fillId){
this.fillId=fillId;
this.applyFill =true ;
}
SetBorderId(borderId){
this.borderId=borderId;
this.applyBorder =true ;
}
ParseFromXml(xml){
if(xml==null) return;
if(xml._numFmtId!=null)
this.numFmtId =parseInt(xml._numFmtId);
if(xml._fontId!=null)
this.fontId =parseInt(xml._fontId);
if(xml._fillId!=null)
this.fillId =parseInt(xml._fillId);
if(xml._borderId!=null)
this.borderId =parseInt(xml._borderId);
if(xml._xfId!=null)
this.xfId =parseInt(xml._xfId);
if(xml._quotePrefix!=null&&xml._quotePrefix=="1")
this.quotePrefix =true; //boolean
if(xml._pivotButton!=null&&xml._pivotButton=="1")
this.pivotButton =true; //boolean
if(xml._applyNumberFormat!=null&&xml._applyNumberFormat=="1")
this.applyNumberFormat =true ; //boolean
if(xml._applyFont!=null&&xml._applyFont=="1")
this.applyFont =true; //boolean
if(xml._applyFill!=null&&xml._applyFill=="1")
this.applyFill =true; //boolean
if(xml._applyBorder!=null&&xml._applyBorder=="1")
this.applyBorder =true; //boolean
if(xml._applyAlignment!=null&&xml._applyAlignment=="1")
this.applyAlignment =true; //boolean
if(xml._applyProtection!=null&&xml._applyProtection=="1")
this.applyProtection =true; //boolean
this.alignment.ParseFromXml(xml.alignment);
}
}
|
pierce-m/p4c
|
frontends/p4/moveDeclarations.cpp
|
<reponame>pierce-m/p4c
/*
Copyright 2013-present Barefoot Networks, Inc.
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.
*/
#include "moveDeclarations.h"
namespace P4 {
const IR::Node* MoveDeclarations::postorder(IR::P4Action* action) {
if (findContext<IR::P4Control>() == nullptr) {
// Else let the parent control get these
auto body = new IR::IndexedVector<IR::StatOrDecl>();
auto m = getMoves();
body->insert(body->end(), m->begin(), m->end());
body->append(*action->body->components);
action->body = new IR::BlockStatement(
action->body->srcInfo, action->body->annotations, body);
pop();
}
return action;
}
const IR::Node* MoveDeclarations::postorder(IR::P4Control* control) {
LOG1("Visiting " << control << " toMove " << toMove.size());
auto decls = new IR::IndexedVector<IR::Declaration>();
for (auto decl : *getMoves()) {
LOG1("Moved " << decl);
decls->push_back(decl);
}
decls->append(*control->controlLocals);
control->controlLocals = decls;
pop();
return control;
}
const IR::Node* MoveDeclarations::postorder(IR::P4Parser* parser) {
auto newStateful = new IR::IndexedVector<IR::Declaration>();
newStateful->append(*getMoves());
newStateful->append(*parser->parserLocals);
parser->parserLocals = newStateful;
pop();
return parser;
}
const IR::Node* MoveDeclarations::postorder(IR::Function* function) {
auto body = new IR::IndexedVector<IR::StatOrDecl>();
auto m = getMoves();
body->insert(body->end(), m->begin(), m->end());
body->append(*function->body->components);
function->body = new IR::BlockStatement(
function->body->srcInfo, function->body->annotations, body);
pop();
return function;
}
const IR::Node* MoveDeclarations::postorder(IR::Declaration_Variable* decl) {
auto parent = getContext()->node;
// We must keep the initializer here
if (decl->initializer != nullptr &&
!parent->is<IR::IndexedVector<IR::Declaration>>()) {
// Don't split initializers from declarations that are at the "toplevel".
// We cannot have assignment statements there.
LOG1("Moving and splitting " << decl);
auto move = new IR::Declaration_Variable(decl->srcInfo, decl->name,
decl->annotations, decl->type, nullptr);
addMove(move);
auto varRef = new IR::PathExpression(decl->name);
auto keep = new IR::AssignmentStatement(decl->srcInfo, varRef, decl->initializer);
return keep;
} else {
LOG1("Moving " << decl);
addMove(decl);
return nullptr;
}
}
const IR::Node* MoveDeclarations::postorder(IR::Declaration_Constant* decl) {
if (findContext<IR::P4Control>() == nullptr &&
findContext<IR::P4Action>() == nullptr &&
findContext<IR::P4Parser>() == nullptr)
// This is a global declaration
return decl;
addMove(decl);
return nullptr;
}
const IR::Node* MoveInitializers::postorder(IR::Declaration_Variable* decl) {
if (getContext()->parent == nullptr)
return decl;
auto parent = getContext()->parent->node;
if (!parent->is<IR::P4Control>() &&
!parent->is<IR::P4Parser>())
// We are not in the local toplevel declarations
return decl;
if (decl->initializer == nullptr)
return decl;
auto varRef = new IR::PathExpression(decl->name);
auto assign = new IR::AssignmentStatement(decl->srcInfo, varRef, decl->initializer);
toMove->push_back(assign);
decl->initializer = nullptr;
return decl;
}
const IR::Node* MoveInitializers::postorder(IR::ParserState* state) {
if (state->name != IR::ParserState::start ||
toMove->empty())
return state;
toMove->append(*state->components);
state->components = toMove;
toMove = new IR::IndexedVector<IR::StatOrDecl>();
return state;
}
const IR::Node* MoveInitializers::postorder(IR::P4Control* control) {
if (toMove->empty())
return control;
toMove->append(*control->body->components);
auto newBody = new IR::BlockStatement(
Util::SourceInfo(), control->body->annotations, toMove);
control->body = newBody;
toMove = new IR::IndexedVector<IR::StatOrDecl>();
return control;
}
} // namespace P4
|
kkcookies99/UAST
|
Dataset/Leetcode/valid/26/402.java
|
<reponame>kkcookies99/UAST
class Solution {
public int XXX(int[] nums) {
if(nums==null || nums.length==0){return 0;}
if(nums.length==1){return 1;}
else{
int slowindex=1;
for(int fastindex=1; fastindex<nums.length; fastindex++)
{
int fastindex_copy=fastindex-1;
if(nums[fastindex_copy] != nums[fastindex])
{nums[slowindex++]=nums[fastindex];}
}
return slowindex;
}
}
}
|
heiseish/Competitive-Programming
|
kattis_done/abandonedanimal.cpp
|
// #include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <set>
using namespace std;
int inf = 1 << 30;
int main() {
int n, k;
cin >> n >> k;
// Set up data structures
unordered_map<string, set<int> > m;
vector<int> items;
// Read in the first half of the data
for(int i = 0; i < k; i++) {
int store;
string item;
cin >> store >> item;
m[item].insert(store);
}
// Keep track of input
vector<string> input;
// Read in the second half
int q;
cin >> q;
for(int i = 0; i < q; i++) {
string item;
cin >> item;
input.push_back(item);
}
// Get max from lo to hi
// Get rid of the later inputs that appear before earlier inputs
int maxhere = 0;
for(int i = 0; i < q; i++) {
string curr = input[i];
vector<int> rem;
for(auto i : m[curr]) {
if(i < maxhere) {
rem.push_back(i);
}
}
for(auto i : rem) {
m[curr].erase(i);
}
if(m[curr].size() > 0) {
maxhere = max(*m[curr].begin(), maxhere);
}
}
// Get min from hi to lo
// Get rid of the earlier inputs that appear after later inputs
int minhere = inf;
for(int i = q-1; i >= 0; i--) {
string curr = input[i];
vector<int> rem;
for(auto i : m[curr]) {
if(i > minhere) {
rem.push_back(i);
}
}
for(auto i : rem) {
m[curr].erase(i);
}
if(m[curr].size() > 0) {
minhere = min(*m[curr].rbegin(), minhere);
}
}
// Find answer
bool works = true;
bool ambig = false;
for(auto i : input) {
if(m[i].size() < 1) {
works = false;
}
if(m[i].size() > 1) {
ambig = true;
}
}
// Print answer
if(!works) {
cout << "impossible" << endl;
}
else if(ambig) {
cout << "ambiguous" << endl;
}
else {
cout << "unique" << endl;
}
}
|
Stratio/cassandra
|
tools/stress/src/org/apache/cassandra/stress/generatedata/DistributionSeqBatch.java
|
<reponame>Stratio/cassandra
package org.apache.cassandra.stress.generatedata;
public class DistributionSeqBatch extends DataGenHex
{
final Distribution delegate;
final int batchSize;
final long maxKey;
private int batchIndex;
private long batchKey;
// object must be published safely if passed between threadCount, due to batchIndex not being volatile. various
// hacks possible, but not ideal. don't want to use volatile as object intended for single threaded use.
public DistributionSeqBatch(int batchSize, long maxKey, Distribution delegate)
{
this.batchIndex = batchSize;
this.batchSize = batchSize;
this.maxKey = maxKey;
this.delegate = delegate;
}
@Override
long next(long operationIndex)
{
if (batchIndex >= batchSize)
{
batchKey = delegate.next();
batchIndex = 0;
}
long r = batchKey + batchIndex++;
if (r > maxKey)
{
batchKey = delegate.next();
batchIndex = 1;
r = batchKey;
}
return r;
}
@Override
public boolean isDeterministic()
{
return false;
}
}
|
Xemrion/Exam-work
|
OilSpillage/PNet/include/IncludeMe.h
|
<gh_stars>1-10
#pragma once
#include "Network.h"
#include "Server.h"
#include "Client.h"
|
Asymmetrik/nifi-nar-bundles
|
nifi-asymmetrik-standard-services/nifi-asymmetrik-mongo-service-bundle/nifi-asymmetrik-mongo-service/src/test/java/com/asymmetrik/nifi/services/mongo/StandardMongoClientServiceIT.java
|
<gh_stars>10-100
package com.asymmetrik.nifi.services.mongo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Requires a Mongo instance running at localhost:28017
*/
public class StandardMongoClientServiceIT {
private static final String MONGO_DATABASE_NAME = "testUpdateMongo" + UUID.randomUUID();
final static String DB_LOCATION = "target/db";
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setup() {
System.setProperty("derby.stream.error.file", "target/derby.log");
}
@Test
public void test_mongoservice_not_enabled() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
runner.addControllerService("test-mongo-closed", service);
runner.enableControllerService(service);
// Close MongoClient
MongoClient client = service.getMongoClient();
// NOTE: This test requires mongo to be running
assertEquals("localhost:27017", client.getConnectPoint());
// Close the mongo connection
client.close();
// Now, this should throw an illegal state exception
thrown.expect(IllegalStateException.class);
client.getConnectPoint();
}
/**
* Unknown database system.
*/
@SuppressWarnings("unused")
@Test
public void testUnknownDatabaseSystem() throws InitializationException {
new StandardMongoClientService();
}
@Test
public void single_host_without_credentials() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
runner.addControllerService("test-good1", service);
runner.setProperty(service, StandardMongoClientService.HOSTS, "localhost:27017");
runner.enableControllerService(service);
runner.assertValid(service);
StandardMongoClientService mongoService = (StandardMongoClientService) runner.getProcessContext().getControllerServiceLookup().getControllerService("test-good1");
assertNotNull(mongoService);
MongoClient mongoClient = mongoService.getMongoClient();
assertNotNull(mongoClient);
assertEquals(0, mongoClient.getDatabase(MONGO_DATABASE_NAME).getCollection("sample").count());
mongoClient.dropDatabase(MONGO_DATABASE_NAME);
}
@Test
public void validating_valid_inputs_1() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
runner.addControllerService("test_hosts", service, props);
runner.assertValid(service);
}
@Test
public void validating_incomplete_auth_inputs_1() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
props.put(StandardMongoClientService.USERNAME.getName(), "mongouser");
runner.addControllerService("test_hosts", service, props);
runner.assertNotValid(service);
}
@Test
public void validating_incomplete_auth_inputs_2() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
props.put(StandardMongoClientService.PASSWORD.getName(), "<PASSWORD>");
runner.addControllerService("test_hosts", service, props);
runner.assertNotValid(service);
}
@Test
public void validating_incomplete_auth_inputs_3() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
props.put(StandardMongoClientService.AUTH_DATABASE.getName(), "mongouser");
runner.addControllerService("test_hosts", service, props);
runner.assertNotValid(service);
}
@Test
public void validating_incomplete_auth_inputs_4() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
props.put(StandardMongoClientService.USERNAME.getName(), "mongouser");
props.put(StandardMongoClientService.PASSWORD.getName(), "<PASSWORD>");
runner.addControllerService("test_hosts", service, props);
runner.assertNotValid(service);
}
@Test
public void validating_incomplete_auth_inputs_5() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
props.put(StandardMongoClientService.USERNAME.getName(), "mongouser");
props.put(StandardMongoClientService.AUTH_DATABASE.getName(), "mongouser");
runner.addControllerService("test_hosts", service, props);
runner.assertNotValid(service);
}
@Test
public void validating_incomplete_auth_inputs_6() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
props.put(StandardMongoClientService.PASSWORD.getName(), "<PASSWORD>");
props.put(StandardMongoClientService.AUTH_DATABASE.getName(), "mongouser");
runner.addControllerService("test_hosts", service, props);
runner.assertNotValid(service);
}
@Test
public void validating_complete_auth_inputs() throws InitializationException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final StandardMongoClientService service = new StandardMongoClientService();
Map<String, String> props = new HashMap<>();
props.put(StandardMongoClientService.HOSTS.getName(), "localhost:27017");
props.put(StandardMongoClientService.USERNAME.getName(), "mongouser");
props.put(StandardMongoClientService.PASSWORD.getName(), "<PASSWORD>");
props.put(StandardMongoClientService.AUTH_DATABASE.getName(), "mongouser");
runner.addControllerService("test_hosts", service, props);
runner.assertValid(service);
}
@Test
public void test_various_host_inputs() {
StandardMongoClientService service = new StandardMongoClientService();
// Single host without specifying port
List<ServerAddress> addresses = service.parseServerAddresses("e01sv05");
assertEquals("Expecting one host", 1, addresses.size());
ServerAddress address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be default port: 27017", 27017, address.getPort());
// Multiple hosts without specifying port
addresses = service.parseServerAddresses("e01sv05, e01sv06");
assertEquals("Expecting two hosts", 2, addresses.size());
address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be default port: 27017", 27017, address.getPort());
address = addresses.get(1);
assertEquals("should be host: e01sv06", "e01sv06", address.getHost());
assertEquals("should be default port: 27017", 27017, address.getPort());
// Multiple hosts, specifying port
addresses = service.parseServerAddresses("e01sv05:2700, e01sv05:2701");
assertEquals("Expecting two hosts", 2, addresses.size());
address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 2700", 2700, address.getPort());
address = addresses.get(1);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 2701", 2701, address.getPort());
// Multiple, repeating hosts, specifying port
addresses = service.parseServerAddresses("e01sv05, e01sv05");
assertEquals("Expecting two hosts", 2, addresses.size());
address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27017", 27017, address.getPort());
address = addresses.get(1);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27017", 27017, address.getPort());
// Try space delimiter
addresses = service.parseServerAddresses("e01sv05:27017 e01sv05:27018");
assertEquals("Expecting one host", 2, addresses.size());
address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27017", 27017, address.getPort());
address = addresses.get(1);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27018", 27018, address.getPort());
// Try repeated space delimiter
addresses = service.parseServerAddresses("e01sv05:27017 e01sv05:27018");
assertEquals("Expecting one host", 2, addresses.size());
address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27017", 27017, address.getPort());
address = addresses.get(1);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27018", 27018, address.getPort());
// Try semi-colon delimiter
addresses = service.parseServerAddresses("e01sv05:27017;e01sv05:27018");
assertEquals("Expecting one host", 2, addresses.size());
address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27017", 27017, address.getPort());
address = addresses.get(1);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27018", 27018, address.getPort());
// Try repeated semi-colon delimiter
addresses = service.parseServerAddresses("e01sv05:27017;;;;e01sv05:27018");
assertEquals("Expecting one host", 2, addresses.size());
address = addresses.get(0);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27017", 27017, address.getPort());
address = addresses.get(1);
assertEquals("should be host: e01sv05", "e01sv05", address.getHost());
assertEquals("should be port: 27018", 27018, address.getPort());
}
}
|
cflinchbaugh/Memorinity
|
src/components/buttons/Button.js
|
import React from 'react';
import styled from 'styled-components';
const StyleWrapper = styled.div`
.button {
color: ${props => props.theme.primaryColor};
background: transparent;
transition: all 0.35s;
display: inline-block;
border: solid 1px orange;
border-radius: 15px;
padding: 8px 20px;
box-shadow: 1px 8px 19px 3px rgba(61,55,61,0.25);
user-select: none;
&:hover {
cursor: pointer;
background-color: #566184;
color: ${props => props.theme.primaryLightColor}
box-shadow: 1px 8px 19px 3px rgba(61,55,61,0.48);
}
}
`
function Button (props) {
let buttonData = {
className: 'button',
onClick: props.onClickFunction,
onMouseOver: props.onMouseOverFunction
}
return (
<StyleWrapper>
<button {...buttonData }>
{ props.label }
</button>
</StyleWrapper>
)
}
export default Button
|
UV-CDAT/ParaView
|
Qt/Core/pqPluginManager.cxx
|
<gh_stars>0
/*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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.
========================================================================*/
#include "pqPluginManager.h"
#include "pqApplicationCore.h"
#include "pqObjectBuilder.h"
#include "pqServer.h"
#include "pqServerManagerModel.h"
#include "pqSettings.h"
#include "vtkPVPluginsInformation.h"
#include "vtkSmartPointer.h"
#include "vtkSMPluginLoaderProxy.h"
#include "vtkSMPluginManager.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMProxyManager.h"
#include "vtkSMSession.h"
#include "vtkWeakPointer.h"
#include <QCoreApplication>
#include <QPointer>
#include <QSet>
#include <QtDebug>
#include <vtksys/ios/sstream>
class pqPluginManager::pqInternals
{
public:
QSet<QString> LocalHiddenPlugins;
QSet<QString> RemoteHiddenPlugins;
QList<QPointer<pqServer> > Servers;
QString getXML(vtkPVPluginsInformation* info, bool remote)
{
vtksys_ios::ostringstream stream;
stream << "<?xml version=\"1.0\" ?>\n";
stream << "<Plugins>\n";
for (unsigned int cc=0; cc < info->GetNumberOfPlugins(); cc++)
{
if ((remote &&
this->RemoteHiddenPlugins.contains(info->GetPluginFileName(cc))) ||
(!remote &&
this->LocalHiddenPlugins.contains(info->GetPluginFileName(cc))))
{
continue;
}
stream << " <Plugin name=\"" << info->GetPluginName(cc) << "\""
<< " filename=\"" << info->GetPluginFileName(cc) << "\""
<< " auto_load=\"" << (info->GetAutoLoad(cc)? 1 : 0) << "\" />\n";
}
stream << "</Plugins>\n";
//cout << stream.str().c_str() << endl;
return QString(stream.str().c_str());
}
};
//-----------------------------------------------------------------------------
pqPluginManager::pqPluginManager(QObject* parentObject)
: Superclass(parentObject)
{
this->Internals = new pqInternals();
pqServerManagerModel* smmodel =
pqApplicationCore::instance()->getServerManagerModel();
// we ensure that the auto-load plugins are loaded before the application
// realizes that a new server connection has been made.
// (BUG #12238).
QObject::connect(smmodel, SIGNAL(preServerAdded(pqServer*)),
this, SLOT(loadPluginsFromSettings(pqServer*)));
QObject::connect(smmodel, SIGNAL(serverRemoved(pqServer*)),
this, SLOT(onServerDisconnected(pqServer*)));
// After the new server has been setup, we can validate if the plugin
// requirements have been met successfully.
QObject::connect(pqApplicationCore::instance()->getObjectBuilder(),
SIGNAL(finishedAddingServer(pqServer*)),
this, SLOT(onServerConnected(pqServer*)));
// observer plugin loaded events from PluginManager to detect plugins loaded
// from Python or otherwise.
vtkSMPluginManager* mgr =
vtkSMProxyManager::GetProxyManager()->GetPluginManager();
mgr->AddObserver(vtkSMPluginManager::PluginLoadedEvent,
this, &pqPluginManager::updatePluginLists);
}
//-----------------------------------------------------------------------------
pqPluginManager::~pqPluginManager()
{
// save all settings for each open server session.
foreach (pqServer* server, this->Internals->Servers)
{
this->onServerDisconnected(server);
}
delete this->Internals;
}
//-----------------------------------------------------------------------------
void pqPluginManager::loadPluginsFromSettings()
{
// Load local plugins information and then load those plugins.
pqSettings* settings = pqApplicationCore::instance()->settings();
QString key = QString("/PluginsList/Local/%1").arg(
QCoreApplication::applicationFilePath());
QString local_plugin_config = settings->value(key).toString();
if (!local_plugin_config.isEmpty())
{
vtkSMProxyManager::GetProxyManager()->GetPluginManager()->
LoadPluginConfigurationXMLFromString(
local_plugin_config.toAscii().data(), NULL, false);
}
}
//-----------------------------------------------------------------------------
void pqPluginManager::loadPluginsFromSettings(pqServer* server)
{
// Tell the server to load all default-plugins.
if (server && server->isRemote())
{
// locate the xml-config from settings associated with this server and ask
// the server to parse it.
pqSettings* settings = pqApplicationCore::instance()->settings();
QString uri = server->getResource().schemeHostsPorts().toURI();
QString key = QString("/PluginsList/%1/%2").arg(uri).arg(
QCoreApplication::applicationFilePath());
QString remote_plugin_config = settings->value(key).toString();
// now pass this xml to the vtkPVPluginTracker on the remote
// processes.
if (!remote_plugin_config.isEmpty())
{
vtkSMProxyManager::GetProxyManager()->GetPluginManager()->
LoadPluginConfigurationXMLFromString(
remote_plugin_config.toAscii().data(), server->session(), true);
}
}
}
//-----------------------------------------------------------------------------
void pqPluginManager::onServerConnected(pqServer* server)
{
this->Internals->Servers.push_back(server);
this->updatePluginLists();
// Validate plugins i.e. check plugins that are required on client and server
// are indeed present on both.
if (!this->verifyPlugins(server))
{
emit this->requiredPluginsNotLoaded(server);
}
}
//-----------------------------------------------------------------------------
void pqPluginManager::onServerDisconnected(pqServer* server)
{
pqSettings* settings = pqApplicationCore::instance()->settings();
if (server && server->isRemote())
{
// locate the xml-config from settings associated with this server and ask
// the server to parse it.
QString uri = server->getResource().schemeHostsPorts().toURI();
QString key = QString("/PluginsList/%1/%2").arg(uri).arg(
QCoreApplication::applicationFilePath());
settings->setValue(key,
this->Internals->getXML(this->loadedExtensions(server, true), true));
}
// just save the local plugin info to be on the safer side.
QString key = QString("/PluginsList/Local/%1").arg(
QCoreApplication::applicationFilePath());
settings->setValue(key,
this->Internals->getXML(this->loadedExtensions(server, false), false));
this->Internals->Servers.removeAll(server);
}
//-----------------------------------------------------------------------------
void pqPluginManager::updatePluginLists()
{
emit this->pluginsUpdated();
}
//-----------------------------------------------------------------------------
vtkPVPluginsInformation* pqPluginManager::loadedExtensions(
pqServer* session, bool remote)
{
vtkSMPluginManager* mgr = vtkSMProxyManager::GetProxyManager()->GetPluginManager();
return (remote && session && session->isRemote())?
mgr->GetRemoteInformation(session->session()) :
mgr->GetLocalInformation();
}
//-----------------------------------------------------------------------------
pqPluginManager::LoadStatus pqPluginManager::loadExtension(
pqServer* server, const QString& lib, QString* vtkNotUsed(errorMsg), bool remote)
{
vtkSMPluginManager* mgr = vtkSMProxyManager::GetProxyManager()->GetPluginManager();
bool ret_val = false;
if (remote && server && server->isRemote())
{
ret_val = mgr->LoadRemotePlugin(lib.toAscii().data(), server->session());
}
else
{
ret_val = mgr->LoadLocalPlugin(lib.toAscii().data());
}
return ret_val? LOADED : NOTLOADED;
}
//-----------------------------------------------------------------------------
QStringList pqPluginManager::pluginPaths(pqServer* session, bool remote)
{
vtkSMPluginManager* mgr = vtkSMProxyManager::GetProxyManager()->GetPluginManager();
QString paths = remote? mgr->GetRemotePluginSearchPaths(session->session()):
mgr->GetLocalPluginSearchPaths();
return paths.split(';', QString::SkipEmptyParts);
}
//-----------------------------------------------------------------------------
void pqPluginManager::hidePlugin(const QString& lib, bool remote)
{
if (remote)
{
this->Internals->RemoteHiddenPlugins.insert(lib);
}
else
{
this->Internals->LocalHiddenPlugins.insert(lib);
}
}
//-----------------------------------------------------------------------------
bool pqPluginManager::isHidden(const QString& lib, bool remote)
{
return remote?
this->Internals->RemoteHiddenPlugins.contains(lib) :
this->Internals->LocalHiddenPlugins.contains(lib);
}
//-----------------------------------------------------------------------------
bool pqPluginManager::verifyPlugins(pqServer* activeServer)
{
if (!activeServer || !activeServer->isRemote())
{
// no verification needed for non-remote servers.
return true;
}
vtkPVPluginsInformation* local_info = this->loadedExtensions(activeServer, false);
vtkPVPluginsInformation* remote_info = this->loadedExtensions(activeServer, true);
return vtkPVPluginsInformation::PluginRequirementsSatisfied(
local_info, remote_info);
}
|
ecralx/rotten-potatoes-api
|
project/server/models/genre.py
|
# project/server/models/genre.py
class Genre():
def __init__(self, tmdb_id, name):
self._tmdb_id = tmdb_id
self._name = name
@staticmethod
def from_dict(genre_dict):
""" Create a genre instance from a dict (generally taken from tmdb) """
return Genre(
genre_dict['id'] if genre_dict.get('id') else genre_dict['tmdb_id'],
genre_dict['name']
)
def to_dict(self):
""" Return all non empty attributes as a dict """
attributes = {
'tmdb_id': self._tmdb_id,
'name': self._name,
}
return {key: value for key,value in attributes.items() if value}
@property
def tmdb_id(self):
return int(self._tmdb_id)
@property
def name(self):
return int(self._name)
|
MODriscoll/AIForGames
|
NavMeshTester/Source/Behaviours/Decorator/Inverter.cpp
|
<filename>NavMeshTester/Source/Behaviours/Decorator/Inverter.cpp
#include "Behaviours\Decorator\Inverter.h"
namespace Behaviour
{
Inverter::Inverter(const behaviour_ptr& a_Child)
: IDecorator("Inverter", a_Child)
{
}
Inverter::Inverter(const behaviour_ptr& a_Child, const std::string& a_Tag)
: IDecorator(a_Tag, a_Child)
{
}
eBehaviourResult Inverter::Execute(Agent* a_Agent, float deltaTime)
{
// Execute the child behaviour, capture the result
eBehaviourResult Result = m_Child->Execute(a_Agent, deltaTime);
// Is the result pending?
if (Result == eBehaviourResult::Pending)
{
// Return the result
return Result;
}
else
{
// Validate result
VALIDATERESULT(Result);
// Is the result a success?
if (Result == eBehaviourResult::Success)
{
// Return failed result
return eBehaviourResult::Failure;
}
else
{
// Return successfull result
return eBehaviourResult::Success;
}
}
}
behaviour_ptr Inverter::Clone(const std::string& a_Tag, const behaviour_ptr& a_Child) const
{
// Create the new inverter behaviour with given tag and child
auto Inv = std::make_shared<Inverter>(a_Child, a_Tag);
// Return the clone
return Inv;
}
}
|
xakep666/konfig
|
loader/kletcd/etcdloader.go
|
<filename>loader/kletcd/etcdloader.go
package kletcd
import (
"bytes"
"context"
"time"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/lalamove/konfig"
"github.com/lalamove/konfig/parser"
"github.com/lalamove/konfig/watcher/kwpoll"
"github.com/lalamove/nui/ncontext"
"github.com/lalamove/nui/nstrings"
"go.etcd.io/etcd/clientv3"
)
var (
defaultTimeout = 5 * time.Second
_ konfig.Loader = (*Loader)(nil)
)
const (
defaultName = "etcd"
)
// Key is an Etcd Key to load
type Key struct {
// Key is the etcd key
Key string
// Parser is the parser for the key
// If nil, the value is casted to a string before adding to the config.Store
Parser parser.Parser
}
// Config is the structure representing the config of a Loader
type Config struct {
// Name is the name of the loader
Name string
// StopOnFailure tells wether a failure to load configs should closed the config and all registered closers
StopOnFailure bool
// Client is the etcd client
Client *clientv3.Client
// Keys is the list of keys to fetch
Keys []Key
// Timeout is the timeout duration when fetching a key
Timeout time.Duration
// Prefix is a prefix to prepend keys when adding into the konfig.Store
Prefix string
// Replacer is a Replacer for the key before adding to the konfig.Store
Replacer nstrings.Replacer
// Watch tells wether there should be a watcher with the loader
Watch bool
// Rater is the rater to pass to the poll watcher
Rater kwpoll.Rater
// MaxRetry is the maximum number of times we can retry to load if it fails
MaxRetry int
// RetryDelay is the time between each retry when a load fails
RetryDelay time.Duration
// Debug sets debug mode on the etcdloader
Debug bool
// Contexter provides a context, default value is contexter wrapping context package. It is used mostly for testing.
Contexter ncontext.Contexter
kvClient clientv3.KV
}
// Loader is the structure of a loader
type Loader struct {
*kwpoll.PollWatcher
cfg *Config
}
// New returns a new loader with the given config
func New(cfg *Config) *Loader {
if cfg.Timeout == 0 {
cfg.Timeout = defaultTimeout
}
if cfg.Contexter == nil {
cfg.Contexter = ncontext.DefaultContexter
}
if cfg.Name == "" {
cfg.Name = defaultName
}
if cfg.kvClient == nil {
cfg.kvClient = cfg.Client.KV
}
var l = &Loader{
cfg: cfg,
}
if cfg.Watch {
var v = konfig.Values{}
var err = l.Load(v)
if err != nil {
panic(err)
}
l.PollWatcher = kwpoll.New(&kwpoll.Config{
Loader: l,
Rater: cfg.Rater,
InitValue: v,
Debug: cfg.Debug,
Diff: true,
})
}
return l
}
// Name returns the name of the loader
func (l *Loader) Name() string { return l.cfg.Name }
// Load loads the values from the keys defined by the config in the konfig.Store
func (l *Loader) Load(s konfig.Values) error {
for _, k := range l.cfg.Keys {
values, err := l.keyValue(k.Key)
if err != nil {
return err
}
for _, v := range values {
var configKey = l.cfg.Prefix + string(v.Key)
if l.cfg.Replacer != nil {
configKey = l.cfg.Replacer.Replace(configKey)
}
// if the key has a parser, we parse the key value using the provided Parser
// else we just convert the value to a string
if k.Parser != nil {
if err := k.Parser.Parse(bytes.NewReader(v.Value), s); err != nil {
return err
}
} else {
s.Set(configKey, string(v.Value))
}
}
}
return nil
}
// MaxRetry is the maximum number of time to retry when a load fails
func (l *Loader) MaxRetry() int {
return l.cfg.MaxRetry
}
// RetryDelay is the delay between each retry
func (l *Loader) RetryDelay() time.Duration {
return l.cfg.RetryDelay
}
func (l *Loader) keyValue(k string) ([]*mvccpb.KeyValue, error) {
var ctx, cancel = l.cfg.Contexter.WithTimeout(
context.Background(),
l.cfg.Timeout,
)
defer cancel()
values, err := l.cfg.kvClient.Get(ctx, k)
if err != nil {
return nil, err
}
return values.Kvs, nil
}
// StopOnFailure returns wether a load failure should stop the config and the registered closers
func (l *Loader) StopOnFailure() bool {
return l.cfg.StopOnFailure
}
|
osborne37686/jsonmarshaller
|
srctest/com/twolattes/json/OuterClass.java
|
package com.twolattes.json;
public class OuterClass {
@Entity
public static class InnerClass {
@Value
String field;
}
}
|
Antonio-Sitoe/Mini-projectos
|
Snake-Game-main/js/script.js
|
window.onload = function () {
var stage = document.getElementById('stage');
let letra = document.querySelector('#jogango')
var ctx = stage.getContext('2d')
const rect = stage.getBoundingClientRect();
let arrowBotons = document.querySelectorAll('.arrow span')
document.addEventListener('keydown', keyPush)
setInterval(game, 80);
const vel = 1;
var vx = vy = 0;
var px = 10;
var py = 15;
var tp = 20;
var qp = 30;
var ax = ay = 15;
var trail = [];
tail = 5;
if (rect.width === 300) {
var tp = 15;
var qp = 20;
const width = "300px";
const height = "300px";
stage.getAttribute('width');
stage.getAttribute('height');
stage.setAttribute('width', width)
stage.setAttribute('height', height)
}
function game() {
px += vx;
py += vy;
if (px < 0) {
px = qp - 1;
}
if (px > qp - 1) {
px = 0
}
if (py < 0) {
py = qp - 1;
}
if (py > qp - 1) {
py = 0;
}
ctx.fillStyle = "#1B4633";
ctx.fillRect(0, 0, stage.clientWidth, stage.height)
ctx.fillStyle = "#ff5100";
ctx.fillRect(ax * tp, ay * tp, tp, tp);
ctx.fillStyle = "#5DE620";
for (var i = 0; i < trail.length; i++) {
ctx.fillRect(trail[i].x * tp, trail[i].y * tp, tp - 1, tp - 1);
if (trail[i].x == px && trail[i].y == py) {
vx = vy = 0;
tail = 5;
}
}
trail.push({ x: px, y: py })
while (trail.length > tail) {
trail.shift();
}
if (ax == px && ay == py) {
tail++;
ax = Math.floor(Math.random() * qp)
ay = Math.floor(Math.random() * qp)
}
}
function keyPush(event) {
switch (event.keyCode) {
case 37://left
vx = -vel;
vy = 0;
letra.innerText = "Jogando"
break
case 38://up
vx = 0;
vy = -vel;
letra.innerText = "Jogando"
break
case 39://lrighn
vx = vel;
vy = 0;
letra.innerText = "Jogando"
break
case 40://down
vx = 0;
vy = vel;
letra.innerText = "Jogando"
break
}
}
arrowBotons.forEach((item) => {
function callback() {
if (item.classList.contains('left')) {
vx = -vel;
vy = 0;
} else if (item.classList.contains('up')) {
vx = 0;
vy = -vel;
} else if (item.classList.contains('rigth')) {
vx = vel;
vy = 0;
} else if (item.classList.contains('down')) {
vx = 0;
vy = vel;
}
}
item.addEventListener('click', callback)
})
}
|
cypherdotXd/o3de
|
Gems/WhiteBox/Code/Tests/WhiteBoxTestRailsAutomation.cpp
|
<filename>Gems/WhiteBox/Code/Tests/WhiteBoxTestRailsAutomation.cpp
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "WhiteBoxTestFixtures.h"
#include "WhiteBoxTestUtil.h"
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
namespace UnitTest
{
using TestRailsAutomationFixture = EditorWhiteBoxModifierTestFixture;
constexpr bool LogActions = false;
TEST_F(TestRailsAutomationFixture, C28798184_PressAndDragOnAPolygonTranslatesItAlongTheSurfaceNormal)
{
namespace Api = WhiteBox::Api;
using ::testing::Pointwise;
// the initial starting position of the entity (in front and to the left of the camera)
const AZ::Transform initialEntityTransformWorld =
AZ::Transform::CreateTranslation(AZ::Vector3(-10.0f, 10.0f, 0.0f));
// world space delta we will be moving the polygon face
const auto worldTranslationDelta = AZ::Vector3::CreateAxisX(20.0f);
// the face handle we will use to get the parent polygon from
const int faceHandle = 7;
// move the entity to its starting position
AzToolsFramework::SetWorldTransform(m_whiteBoxEntityId, initialEntityTransformWorld);
// select the entity with the White Box Component
AzToolsFramework::SelectEntity(m_whiteBoxEntityId);
// mimic pressing the 'Edit' button on the Component Card
EnterComponentMode<WhiteBox::EditorWhiteBoxComponent>();
// grab the White Box Mesh (for use with the White Box Tool Api)
WhiteBox::WhiteBoxMesh* whiteBox;
WhiteBox::EditorWhiteBoxComponentRequestBus::EventResult(
whiteBox, AZ::EntityComponentIdPair(m_whiteBoxEntityId, m_whiteBoxComponent->GetId()),
&WhiteBox::EditorWhiteBoxComponentRequestBus::Events::GetWhiteBoxMesh);
// the initial position of the white box mesh vertices
const auto initialVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// the center position of the polygon modifier
MultiSpacePoint initialModifierMidPoint(
Api::PolygonMidpoint(*whiteBox, Api::FacePolygonHandle(*whiteBox, Api::FaceHandle(faceHandle))),
initialEntityTransformWorld, m_cameraState);
// where we expect the interaction to leave the modifier after the movement
const auto finalScreenModifierMidPoint =
AzFramework::WorldToScreen(initialModifierMidPoint.GetWorldSpace() + worldTranslationDelta, m_cameraState);
// clone the initial vertex positions as our starting point for the expected positions
AZStd::vector<AZ::Vector3> expectedFinalLocalFaceVertexPositions(initialVertexLocalPositions);
// where we expect the polygon vertices to end up after the movement
expectedFinalLocalFaceVertexPositions[1] += worldTranslationDelta;
expectedFinalLocalFaceVertexPositions[2] += worldTranslationDelta;
expectedFinalLocalFaceVertexPositions[5] += worldTranslationDelta;
expectedFinalLocalFaceVertexPositions[6] += worldTranslationDelta;
m_actionDispatcher->LogActions(LogActions)
->CameraState(m_cameraState)
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str())
->Trace("Moving mouse to polygon modifier midpoint")
->MousePosition(initialModifierMidPoint.GetScreenSpace())
->Trace("Dragging polygon to extrude")
->MouseLButtonDown()
->MousePosition(finalScreenModifierMidPoint)
->MouseLButtonUp()
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str());
// grab the white box mesh vertices
const auto finalVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// check that the number of vertices hasn't changed (no extrusions)
EXPECT_EQ(finalVertexLocalPositions.size(), initialVertexLocalPositions.size());
// check our expected modified vertices and the vertices after the modifier match
EXPECT_THAT(
finalVertexLocalPositions,
Pointwise(ContainerIsCloseTolerance(0.01f), expectedFinalLocalFaceVertexPositions));
}
TEST_F(TestRailsAutomationFixture, C28798192_PressAndDragOutwardsFromAPolygonWithCtrlHeldWillExtrudeThePolygon)
{
namespace Api = WhiteBox::Api;
using ::testing::Pointwise;
// the initial starting position of the entity (in front and to the left of the camera)
const AZ::Transform initialEntityTransformWorld =
AZ::Transform::CreateTranslation(AZ::Vector3(-10.0f, 10.0f, 0.0f));
// world space delta we will be moving the polygon face
const auto worldTranslationDelta = AZ::Vector3::CreateAxisX(20.0f);
// the face handle we will use to get the parent polygon from
const int faceHandle = 7;
// move the entity to its starting position
AzToolsFramework::SetWorldTransform(m_whiteBoxEntityId, initialEntityTransformWorld);
// select the entity with the White Box Component
AzToolsFramework::SelectEntity(m_whiteBoxEntityId);
// mimic pressing the 'Edit' button on the Component Card
EnterComponentMode<WhiteBox::EditorWhiteBoxComponent>();
// grab the White Box Mesh (for use with the White Box Tool Api)
WhiteBox::WhiteBoxMesh* whiteBox;
WhiteBox::EditorWhiteBoxComponentRequestBus::EventResult(
whiteBox, AZ::EntityComponentIdPair(m_whiteBoxEntityId, m_whiteBoxComponent->GetId()),
&WhiteBox::EditorWhiteBoxComponentRequestBus::Events::GetWhiteBoxMesh);
// the initial position of the white box mesh vertices
const auto initialVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// the center position of the polygon modifier
MultiSpacePoint initialModifierMidPoint(
Api::PolygonMidpoint(*whiteBox, Api::FacePolygonHandle(*whiteBox, Api::FaceHandle(faceHandle))),
initialEntityTransformWorld, m_cameraState);
// where we expect the interaction to leave the modifier after the movement
const auto finalScreenModifierMidPoint =
AzFramework::WorldToScreen(initialModifierMidPoint.GetWorldSpace() + worldTranslationDelta, m_cameraState);
// clone the initial vertex positions as our starting point for the expected positions
AZStd::vector<AZ::Vector3> expectedFinalLocalFaceVertexPositions(initialVertexLocalPositions);
// where we expect the extra polygon vertices added by the extrusion to be after the movement
expectedFinalLocalFaceVertexPositions.emplace_back(initialVertexLocalPositions[5] + worldTranslationDelta);
expectedFinalLocalFaceVertexPositions.emplace_back(initialVertexLocalPositions[6] + worldTranslationDelta);
expectedFinalLocalFaceVertexPositions.emplace_back(initialVertexLocalPositions[2] + worldTranslationDelta);
expectedFinalLocalFaceVertexPositions.emplace_back(initialVertexLocalPositions[1] + worldTranslationDelta);
m_actionDispatcher->LogActions(LogActions)
->CameraState(m_cameraState)
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str())
->Trace("Moving mouse to polygon modifier midpoint")
->MousePosition(initialModifierMidPoint.GetScreenSpace())
->KeyboardModifierDown(AzToolsFramework::ViewportInteraction::KeyboardModifier::Ctrl)
->Trace("Dragging polygon to extrude")
->MouseLButtonDown()
->MousePosition(finalScreenModifierMidPoint)
->MouseLButtonUp()
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str());
// grab the white box mesh vertices
const auto finalVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// check that the number of vertices has changed (one extrusion)
EXPECT_EQ(finalVertexLocalPositions.size(), initialVertexLocalPositions.size() + 4);
// check our expected modified vertices and the vertices after the modifier match
EXPECT_THAT(
finalVertexLocalPositions,
Pointwise(ContainerIsCloseTolerance(0.01f), expectedFinalLocalFaceVertexPositions));
}
TEST_F(
TestRailsAutomationFixture, C28798192_PressAndDragOnAPolygonScaleModifierScalesTheVerticesAboutThePolygonCenter)
{
namespace Api = WhiteBox::Api;
using ::testing::Pointwise;
// the initial starting position of the entity (in front and to the left of the camera)
const AZ::Transform initialEntityTransformWorld =
AZ::Transform::CreateTranslation(AZ::Vector3(-10.0f, 10.0f, 0.0f));
// world space delta we will be moving the polygon face
const auto worldTranslationDelta = AZ::Vector3::CreateAxisX(20.0f);
// the face handle we will use to get the parent polygon from
const int faceHandle = 7;
// the polygon vertex handle we will be dragging
const int vertexHandle = 2;
// lerp amount to derive mid point between polygon vertex and polygon mid point
const float vertexLerp = 0.5f;
// move the entity to its starting position
AzToolsFramework::SetWorldTransform(m_whiteBoxEntityId, initialEntityTransformWorld);
// select the entity with the White Box Component
AzToolsFramework::SelectEntity(m_whiteBoxEntityId);
// mimic pressing the 'Edit' button on the Component Card
EnterComponentMode<WhiteBox::EditorWhiteBoxComponent>();
// grab the White Box Mesh (for use with the White Box Tool Api)
WhiteBox::WhiteBoxMesh* whiteBox;
WhiteBox::EditorWhiteBoxComponentRequestBus::EventResult(
whiteBox, AZ::EntityComponentIdPair(m_whiteBoxEntityId, m_whiteBoxComponent->GetId()),
&WhiteBox::EditorWhiteBoxComponentRequestBus::Events::GetWhiteBoxMesh);
// the initial position of the white box mesh vertices
const auto initialVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// the center position of the polygon modifier
MultiSpacePoint initialModifierMidPoint(
Api::PolygonMidpoint(*whiteBox, Api::FacePolygonHandle(*whiteBox, Api::FaceHandle(faceHandle))),
initialEntityTransformWorld, m_cameraState);
// the position of the vertex handle of the polygon we will be resizing
MultiSpacePoint initialModifierVertex(
initialVertexLocalPositions[vertexHandle], initialEntityTransformWorld, m_cameraState);
// mid point between polygon vertex and polygon modifier mid point
MultiSpacePoint finalModifierVertex(
initialModifierVertex.GetLocalSpace().Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp),
initialEntityTransformWorld, m_cameraState);
// clone the initial vertex positions as our starting point for the expected positions
AZStd::vector<AZ::Vector3> expectedFinalLocalFaceVertexPositions(initialVertexLocalPositions);
// where we expect the polygon vertices to end up after the movement (moved half-way towards the face mid point)
expectedFinalLocalFaceVertexPositions[1] =
initialVertexLocalPositions[1].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
expectedFinalLocalFaceVertexPositions[2] =
initialVertexLocalPositions[2].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
expectedFinalLocalFaceVertexPositions[5] =
initialVertexLocalPositions[5].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
expectedFinalLocalFaceVertexPositions[6] =
initialVertexLocalPositions[6].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
m_actionDispatcher->LogActions(LogActions)
->CameraState(m_cameraState)
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str())
->Trace("Moving mouse to polygon modifier midpoint")
->MousePosition(initialModifierMidPoint.GetScreenSpace())
->Trace("Selecting polygon")
->MouseLButtonDown()
->MouseLButtonUp()
->Trace("Moving mouse to polygon vertex % d", vertexHandle)
->MousePosition(initialModifierVertex.GetScreenSpace())
->Trace("Selecting polygon vertex % d", vertexHandle)
->MouseLButtonDown()
->Trace("Dragging vertex %d towards centroid of polygon", vertexHandle)
->MousePosition(finalModifierVertex.GetScreenSpace())
->MouseLButtonUp()
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str());
// grab the white box mesh vertices
const auto finalVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// check that the number of vertices has not changed
EXPECT_EQ(finalVertexLocalPositions.size(), initialVertexLocalPositions.size());
// check our expected modified vertices and the vertices after the modifier match
EXPECT_THAT(
finalVertexLocalPositions,
Pointwise(ContainerIsCloseTolerance(0.01f), expectedFinalLocalFaceVertexPositions));
}
TEST_F(TestRailsAutomationFixture, C28798193_PressAndDragInwardsFromAPolygonWithCtrlHeldWillImpressThePolygon)
{
namespace Api = WhiteBox::Api;
using ::testing::Pointwise;
// the initial starting position of the entity (in front and to the left of the camera)
const AZ::Transform initialEntityTransformWorld =
AZ::Transform::CreateTranslation(AZ::Vector3(-10.0f, 10.0f, 0.0f));
// world space delta we will be moving the polygon face
const auto worldTranslationDelta = AZ::Vector3::CreateAxisX(20.0f);
// the face handle we will use to get the parent polygon from
const int faceHandle = 7;
// the polygon vertex handle we will be dragging
const int vertexHandle = 2;
// lerp amount to derive mid point between polygon vertex and polygon mid point
const float vertexLerp = 0.5f;
// move the entity to its starting position
AzToolsFramework::SetWorldTransform(m_whiteBoxEntityId, initialEntityTransformWorld);
// select the entity with the White Box Component
AzToolsFramework::SelectEntity(m_whiteBoxEntityId);
// mimic pressing the 'Edit' button on the Component Card
EnterComponentMode<WhiteBox::EditorWhiteBoxComponent>();
// grab the White Box Mesh (for use with the White Box Tool Api)
WhiteBox::WhiteBoxMesh* whiteBox;
WhiteBox::EditorWhiteBoxComponentRequestBus::EventResult(
whiteBox, AZ::EntityComponentIdPair(m_whiteBoxEntityId, m_whiteBoxComponent->GetId()),
&WhiteBox::EditorWhiteBoxComponentRequestBus::Events::GetWhiteBoxMesh);
// the initial position of the white box mesh vertices
const auto initialVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// the center position of the polygon modifier
MultiSpacePoint initialModifierMidPoint(
Api::PolygonMidpoint(*whiteBox, Api::FacePolygonHandle(*whiteBox, Api::FaceHandle(faceHandle))),
initialEntityTransformWorld, m_cameraState);
// the position of the vertex handle of the polygon we will be resizing
MultiSpacePoint initialModifierVertex(
initialVertexLocalPositions[vertexHandle], initialEntityTransformWorld, m_cameraState);
// mid point between polygon vertex and polygon modifier mid point
MultiSpacePoint finalModifierVertex(
initialModifierVertex.GetLocalSpace().Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp),
initialEntityTransformWorld, m_cameraState);
// where we expect the interaction to leave the modifier after the movement
const auto finalScreenModifierMidPoint =
AzFramework::WorldToScreen(initialModifierMidPoint.GetWorldSpace() + worldTranslationDelta, m_cameraState);
// clone the initial vertex positions as our starting point for the expected positions
AZStd::vector<AZ::Vector3> expectedFinalLocalFaceVertexPositions(initialVertexLocalPositions);
// where we expect the polygon vertices to end up after the movement (moved half-way towards the face mid point)
expectedFinalLocalFaceVertexPositions[1] =
initialVertexLocalPositions[1].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
expectedFinalLocalFaceVertexPositions[2] =
initialVertexLocalPositions[2].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
expectedFinalLocalFaceVertexPositions[5] =
initialVertexLocalPositions[5].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
expectedFinalLocalFaceVertexPositions[6] =
initialVertexLocalPositions[6].Lerp(initialModifierMidPoint.GetLocalSpace(), vertexLerp);
// where we expect the extra polygon vertices added by the impression to be after the movement
expectedFinalLocalFaceVertexPositions.emplace_back(
expectedFinalLocalFaceVertexPositions[5] + worldTranslationDelta);
expectedFinalLocalFaceVertexPositions.emplace_back(
expectedFinalLocalFaceVertexPositions[6] + worldTranslationDelta);
expectedFinalLocalFaceVertexPositions.emplace_back(
expectedFinalLocalFaceVertexPositions[2] + worldTranslationDelta);
expectedFinalLocalFaceVertexPositions.emplace_back(
expectedFinalLocalFaceVertexPositions[1] + worldTranslationDelta);
m_actionDispatcher->LogActions(LogActions)
->CameraState(m_cameraState)
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str())
->Trace("Moving mouse to polygon modifier midpoint")
->MousePosition(initialModifierMidPoint.GetScreenSpace())
->Trace("Selecting polygon")
->MouseLButtonDown()
->MouseLButtonUp()
->Trace("Moving mouse to polygon vertex % d", vertexHandle)
->MousePosition(initialModifierVertex.GetScreenSpace())
->Trace("Selecting polygon vertex % d", vertexHandle)
->MouseLButtonDown()
->Trace("Dragging vertex %d towards centroid of polygon", vertexHandle)
->MousePosition(finalModifierVertex.GetScreenSpace())
->MouseLButtonUp()
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str())
->Trace("Moving mouse to centroid of polygon")
->MousePosition(initialModifierMidPoint.GetScreenSpace())
->Trace("Impressing polygon and extruding")
->KeyboardModifierDown(AzToolsFramework::ViewportInteraction::KeyboardModifier::Ctrl)
->MouseLButtonDown()
->MousePosition(finalScreenModifierMidPoint)
->MouseLButtonUp()
->Trace(WhiteBox::VerticesToString(whiteBox, initialEntityTransformWorld).c_str());
// grab the white box mesh vertices
const auto finalVertexLocalPositions = Api::MeshVertexPositions(*whiteBox);
// check that the number of vertices has changed (one impression)
EXPECT_EQ(finalVertexLocalPositions.size(), initialVertexLocalPositions.size() + 4);
// check our expected modified vertices and the vertices after the modifier match
EXPECT_THAT(
finalVertexLocalPositions,
Pointwise(ContainerIsCloseTolerance(0.01f), expectedFinalLocalFaceVertexPositions));
}
} // namespace UnitTest
|
vertigo-io/vertigo-bot-factory
|
vertigo-bot-designer/src/main/javagen/io/vertigo/chatbot/designer/domain/analytics/SentenseDetail.java
|
package io.vertigo.chatbot.designer.domain.analytics;
import io.vertigo.core.lang.Generated;
import io.vertigo.datamodel.structure.model.DtObject;
import io.vertigo.datamodel.structure.stereotype.Field;
import io.vertigo.datamodel.structure.util.DtObjectUtil;
/**
* This class is automatically generated.
* DO NOT EDIT THIS FILE DIRECTLY.
*/
@Generated
public final class SentenseDetail implements DtObject {
private static final long serialVersionUID = 1L;
private String messageId;
private java.time.Instant date;
private String text;
private String intentRasa;
private java.math.BigDecimal confidence;
private Long topId;
private String modelName;
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'Rasa message ID'.
* @return String messageId
*/
@Field(smartType = "STyIdStr", label = "Rasa message ID")
public String getMessageId() {
return messageId;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'Rasa message ID'.
* @param messageId String
*/
public void setMessageId(final String messageId) {
this.messageId = messageId;
}
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'Date'.
* @return Instant date
*/
@Field(smartType = "STyInstant", label = "Date")
public java.time.Instant getDate() {
return date;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'Date'.
* @param date Instant
*/
public void setDate(final java.time.Instant date) {
this.date = date;
}
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'User text'.
* @return String text
*/
@Field(smartType = "STyLabel", label = "User text")
public String getText() {
return text;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'User text'.
* @param text String
*/
public void setText(final String text) {
this.text = text;
}
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'Rasa intent'.
* @return String intentRasa
*/
@Field(smartType = "STyLabel", label = "Rasa intent")
public String getIntentRasa() {
return intentRasa;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'Rasa intent'.
* @param intentRasa String
*/
public void setIntentRasa(final String intentRasa) {
this.intentRasa = intentRasa;
}
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'Confidence'.
* @return BigDecimal confidence
*/
@Field(smartType = "STyPercentage", label = "Confidence")
public java.math.BigDecimal getConfidence() {
return confidence;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'Confidence'.
* @param confidence BigDecimal
*/
public void setConfidence(final java.math.BigDecimal confidence) {
this.confidence = confidence;
}
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'Topic selection'.
* @return Long topId
*/
@Field(smartType = "STyId", label = "Topic selection")
public Long getTopId() {
return topId;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'Topic selection'.
* @param topId Long
*/
public void setTopId(final Long topId) {
this.topId = topId;
}
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'Model Name'.
* @return String modelName
*/
@Field(smartType = "STyLabel", label = "Model Name")
public String getModelName() {
return modelName;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'Model Name'.
* @param modelName String
*/
public void setModelName(final String modelName) {
this.modelName = modelName;
}
/** {@inheritDoc} */
@Override
public String toString() {
return DtObjectUtil.toString(this);
}
}
|
anitajjx/matrixone
|
pkg/vm/engine/aoe/storage/memtable/v1/base/types.go
|
// Copyright 2021 Matrix Origin
//
// 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 base
import (
"github.com/matrixorigin/matrixone/pkg/container/batch"
"github.com/matrixorigin/matrixone/pkg/vm/engine/aoe/storage/common"
"github.com/matrixorigin/matrixone/pkg/vm/engine/aoe/storage/metadata/v1"
)
type ICollection interface {
common.IRef
Append(bat *batch.Batch, index *metadata.LogIndex) (err error)
Flush() error
String() string
GetMeta() *metadata.Table
}
type IManager interface {
WeakRefCollection(id uint64) ICollection
StrongRefCollection(id uint64) ICollection
RegisterCollection(interface{}) (c ICollection, err error)
UnregisterCollection(id uint64) (c ICollection, err error)
CollectionIDs() map[uint64]uint64
String() string
}
|
manisharmagarg/qymatix
|
api/qymatix/users.py
|
import numpy as np
import pandas as pd
from api.infrastructure.mysql import connection
import logging
logger = logging.getLogger(__name__)
def getCustomersPerUser(dbname='username', cur='', username='all', user_id=0, raw=False, local=False):
'''
'''
dbname = dbname.replace('results_', 'data_')
if "data_" not in dbname:
dbname = "data_" + dbname
try:
if cur == '':
mysql_connection = connection.MySQLConnection(dbname)
con = mysql_connection.connect()
cur = con.cursor()
if username == 'all' and user_id == 0:
script = "\
SELECT {0}.customers.id, {1}.users.id\
FROM ({1}.Users_Customers\
LEFT JOIN {0}.customers\
ON {1}.Users_Customers.customer_id={0}.customers.id)\
LEFT JOIN {1}.users\
ON {1}.Users_Customers.user_id=users.id\
".format(dbname.replace('data_', 'data_'), dbname)
elif username != 'all' and user_id == 0:
script = "\
SELECT {0}.customers.id, {1}.users.id\
FROM ({1}.Users_Customers\
LEFT JOIN {0}.customers\
ON {1}.Users_Customers.customer_id={0}.customers.id)\
LEFT JOIN {1}.users\
ON {1}.Users_Customers.user_id=users.id\
WHERE {1}.users.username='{2}';\
".format(dbname.replace('data_', 'data_'), dbname, username)
else:
script = "\
SELECT {0}.customers.id, {1}.users.id\
FROM ({1}.Users_Customers\
LEFT JOIN {0}.customers\
ON {1}.Users_Customers.customer_id={0}.customers.id)\
LEFT JOIN {1}.users\
ON {1}.Users_Customers.user_id=users.id\
WHERE {1}.users.id='{2}';\
".format(dbname.replace('data_', 'data_'), dbname, user_id)
cur.execute(script)
data = np.asarray(cur.fetchall())
try:
df = pd.DataFrame(data, columns=['customer_id', 'user_id'])
grouped = df.groupby('user_id')
groups = {}
for name, group in grouped:
groups[name] = group['customer_id'].to_json(orient='records')
except Exception as e:
print(e)
groups = {}
# raise
# groups = {'No groups': 2}
except Exception as e:
# print("Error {}: {}".format(e.args[0],e.args[1]))
groups = e.args[1]
groups = ''
return groups
finally:
try:
if con:
con.close()
except:
return "DB connection failed."
return groups
if __name__ == "__main__":
dbname = 'qymatix_de'
# groups = getGroups(dbname, username=username, user_id=0)
# groups = getGroups(dbname, username="chancho_babe", user_id=0)
# print(groups)
# addUserToGroup(dbname, 1, 2)
# addUserToGroup(dbname, 20, 1)
# addUserToGroup(dbname, 17, 2)
# username = 'all'
# customers = getCustomersPerUser(dbname, username=username, user_id=0)
username = 'all'
# username = 'paul__qy___test_com'
user_id = 20
user_id = 141
user_id = 0
dbname = 'qymatix_best'
username = 'all'
username = 'philipp__spm_li'
dbname = 'spm_li'
customers = getCustomersPerUser(dbname, username=username, user_id=user_id)
print(customers)
print(customers[customers.keys()[0]])
|
Splyse/nos-client
|
src/renderer/shared/components/SidePanel/index.js
|
import React from 'react';
import { string } from 'prop-types';
import styles from './SidePanel.scss';
const SidePanel = ({ step, title, text }) => (
<div className={styles.sidePanel}>
<div className={styles.step}>Step {step} / 3</div>
<div className={styles.title}>{title}</div>
<span role="img" aria-label="description">
{text}
</span>
</div>
);
SidePanel.propTypes = {
step: string.isRequired,
title: string.isRequired,
text: string.isRequired
};
SidePanel.defaultProps = {};
export default SidePanel;
|
MRoc/MSynth
|
source/msynthlib/framework/thread/MSyncThread.h
|
<filename>source/msynthlib/framework/thread/MSyncThread.h<gh_stars>1-10
#ifndef __MSyncThread
#define __MSyncThread
#include "MThread.h"
#include "IRunnable.h"
/**
* a thread that can be synchronized with a win32 event
*/
class MSyncThread :
public MThread
{
protected:
/**
* the handle to the win32 event
*/
HANDLE ivHandleEvent;
/**
* reference to the run method to be
* invoked when event is triggered.
*/
IRunnable* ivPtRunnable;
public:
/**
* constructor
*
* the runnable::run method is invoked
* every time the event is triggered.
*/
MSyncThread( IRunnable* pRunnable );
/**
* destructor
*/
virtual ~MSyncThread();
/**
* waits for the event until resume
* is invoked from another thread.
*/
virtual void run();
/**
* triggers the event,
* invoked from another thread.
*/
virtual bool trigger();
};
#endif
|
parndt/cli
|
spec/unit/hanami/cli/commands/monolith/generate/slice_spec.rb
|
# frozen_string_literal: true
require "hanami/cli/commands/monolith/generate/slice"
require "hanami"
require "ostruct"
require "securerandom"
RSpec.describe Hanami::CLI::Commands::Monolith::Generate::Slice do
subject { described_class.new(fs: fs, inflector: inflector, generator: generator) }
let(:fs) { Dry::Files.new(memory: true) }
let(:inflector) { Dry::Inflector.new }
let(:generator) { Hanami::CLI::Generators::Monolith::Slice.new(fs: fs, inflector: inflector) }
let(:app) { "Bookshelf" }
let(:slice) { "main" }
it "generates slice" do
pending "FIXME: something changed and the output has too many new-lines now"
expect(Hanami).to receive(:application)
.and_return(OpenStruct.new(namespace: app))
routes_contents = <<~CODE
# frozen_string_literal: true
Hanami.application.routes do
end
CODE
fs.write("config/routes.rb", routes_contents)
subject.call(name: slice, url_prefix: "/")
# config/routes.rb
routes = <<~EXPECTED
# frozen_string_literal: true
Hanami.application.routes do
slice :main, at: "/" do
end
end
EXPECTED
expect(fs.read("config/routes.rb")).to eq(routes)
expect(fs.directory?(directory = "slices/#{slice}")).to be(true)
fs.chdir(directory) do
# action.rb
action = <<~EXPECTED
# auto_register: false
# frozen_string_literal: true
require "#{inflector.underscore(app)}/action"
module #{inflector.classify(slice)}
class Action < #{inflector.classify(app)}::Action
end
end
EXPECTED
expect(fs.read("action.rb")).to eq(action)
# view.rb
view = <<~EXPECTED
# auto_register: false
# frozen_string_literal: true
require "#{inflector.underscore(app)}/view"
module #{inflector.classify(slice)}
class View < #{inflector.classify(app)}::View
end
end
EXPECTED
expect(fs.read("view.rb")).to eq(view)
# entities.rb
entities = <<~EXPECTED
# auto_register: false
# frozen_string_literal: true
module #{inflector.classify(slice)}
module Entities
end
end
Dir[File.join(__dir__, "entities", "*.rb")].each(&method(:require))
EXPECTED
expect(fs.read("entities.rb")).to eq(entities)
# repository.rb
repository = <<~EXPECTED
# frozen_string_literal: true
require "#{inflector.underscore(app)}/repository"
require_relative "entities"
module #{inflector.classify(slice)}
class Repository < #{inflector.classify(app)}::Repository
struct_namespace Entities
end
end
EXPECTED
expect(fs.read("repository.rb")).to eq(repository)
# actions/.keep
actions_keep = <<~EXPECTED
EXPECTED
expect(fs.read("actions/.keep")).to eq(actions_keep)
# views/.keep
views_keep = <<~EXPECTED
EXPECTED
expect(fs.read("views/.keep")).to eq(views_keep)
# templates/.keep
templates_keep = <<~EXPECTED
EXPECTED
expect(fs.read("templates/.keep")).to eq(templates_keep)
# templates/.keep
templates_layouts_keep = <<~EXPECTED
EXPECTED
expect(fs.read("templates/layouts/.keep")).to eq(templates_layouts_keep)
# entities/.keep
entities_keep = <<~EXPECTED
EXPECTED
expect(fs.read("entities/.keep")).to eq(entities_keep)
# repository/.keep
repositories_keep = <<~EXPECTED
EXPECTED
expect(fs.read("repositories/.keep")).to eq(repositories_keep)
end
end
it "uses slice name as URL prefix default" do
pending "FIXME: something changed and the output has too many new-lines now"
expect(Hanami).to receive(:application)
.and_return(OpenStruct.new(namespace: app))
routes_contents = <<~CODE
# frozen_string_literal: true
Hanami.application.routes do
end
CODE
fs.write("config/routes.rb", routes_contents)
subject.call(name: "FooBar")
# config/routes.rb
routes = <<~EXPECTED
# frozen_string_literal: true
Hanami.application.routes do
slice :foo_bar, at: "/foo_bar" do
end
end
EXPECTED
expect(fs.read("config/routes.rb")).to eq(routes)
end
it "ensures that slice URL prefix is valid" do
expect(Hanami).to receive(:application)
.and_return(OpenStruct.new(namespace: app))
.at_least(:once)
routes_contents = <<~CODE
# frozen_string_literal: true
Hanami.application.routes do
end
CODE
fs.write("config/routes.rb", routes_contents)
subject.call(name: slice_name = SecureRandom.alphanumeric(16).downcase)
expected = %(slice :#{slice_name}, at: "/#{slice_name}" do)
expect(fs.read("config/routes.rb")).to match(expected)
subject.call(name: slice_name = SecureRandom.alphanumeric(16).downcase, url_prefix: "/")
expected = %(slice :#{slice_name}, at: "/" do)
expect(fs.read("config/routes.rb")).to match(expected)
subject.call(name: slice_name = SecureRandom.alphanumeric(16).downcase, url_prefix: "/foo_bar")
expected = %(slice :#{slice_name}, at: "/foo_bar" do)
expect(fs.read("config/routes.rb")).to match(expected)
subject.call(name: slice_name = SecureRandom.alphanumeric(16).downcase, url_prefix: "/FooBar")
expected = %(slice :#{slice_name}, at: "/foo_bar" do)
expect(fs.read("config/routes.rb")).to match(expected)
expect { subject.call(name: slice, url_prefix: " ") }.to raise_error(ArgumentError, "invalid URL prefix: ` '")
expect { subject.call(name: slice, url_prefix: "a") }.to raise_error(ArgumentError, "invalid URL prefix: `a'")
expect { subject.call(name: slice, url_prefix: "//") }.to raise_error(ArgumentError, "invalid URL prefix: `//'")
expect {
subject.call(name: slice, url_prefix: "//FooBar")
}.to raise_error(ArgumentError, "invalid URL prefix: `//FooBar'")
end
end
|
airking05/go-docker-api-client
|
client/exec/exec_inspect_responses.go
|
// Code generated by go-swagger; DO NOT EDIT.
package exec
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
models "github.com/airking05/go-docker-api-client/models"
)
// ExecInspectReader is a Reader for the ExecInspect structure.
type ExecInspectReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *ExecInspectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewExecInspectOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 404:
result := NewExecInspectNotFound()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewExecInspectInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
// NewExecInspectOK creates a ExecInspectOK with default headers values
func NewExecInspectOK() *ExecInspectOK {
return &ExecInspectOK{}
}
/*ExecInspectOK handles this case with default header values.
No error
*/
type ExecInspectOK struct {
Payload *models.ExecInspectOKBody
}
func (o *ExecInspectOK) Error() string {
return fmt.Sprintf("[GET /exec/{id}/json][%d] execInspectOK %+v", 200, o.Payload)
}
func (o *ExecInspectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ExecInspectOKBody)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewExecInspectNotFound creates a ExecInspectNotFound with default headers values
func NewExecInspectNotFound() *ExecInspectNotFound {
return &ExecInspectNotFound{}
}
/*ExecInspectNotFound handles this case with default header values.
No such exec instance
*/
type ExecInspectNotFound struct {
Payload *models.ErrorResponse
}
func (o *ExecInspectNotFound) Error() string {
return fmt.Sprintf("[GET /exec/{id}/json][%d] execInspectNotFound %+v", 404, o.Payload)
}
func (o *ExecInspectNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ErrorResponse)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewExecInspectInternalServerError creates a ExecInspectInternalServerError with default headers values
func NewExecInspectInternalServerError() *ExecInspectInternalServerError {
return &ExecInspectInternalServerError{}
}
/*ExecInspectInternalServerError handles this case with default header values.
Server error
*/
type ExecInspectInternalServerError struct {
Payload *models.ErrorResponse
}
func (o *ExecInspectInternalServerError) Error() string {
return fmt.Sprintf("[GET /exec/{id}/json][%d] execInspectInternalServerError %+v", 500, o.Payload)
}
func (o *ExecInspectInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ErrorResponse)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
|
skarnet/nsss
|
src/include/nsss/nsss-all.h
|
/* ISC license. */
#ifndef NSSS_ALL_H
#define NSSS_ALL_H
#include <nsss/pwd-all.h>
#include <nsss/grp-all.h>
#include <nsss/shadow-all.h>
#endif
|
ctishen/LuatOS
|
luat/rtt/luat_msh_rtt.c
|
<filename>luat/rtt/luat_msh_rtt.c
#include "luat_base.h"
#include "luat_malloc.h"
#include "luat_msgbus.h"
#include "luat_timer.h"
#include "luat_gpio.h"
#define LUAT_LOG_TAG "luat.msh"
#include "luat_log.h"
#include "luat_dbg.h"
#include "rtthread.h"
#include <rtdevice.h>
#ifdef FINSH_USING_MSH
extern lua_State *L;
static int msgbus_handler(lua_State *L, void* ptr) {
int re = luaL_dostring(L, (const char*)ptr);
if (re) {
LLOGE("luaL_dostring return re != 0\n");
LLOGE(lua_tostring(L, -1));
}
luat_heap_free(ptr);
return 0;
}
static void loadstr(int argc, char**argv) {
if (argc < 2)
return;
char* buff = luat_heap_malloc(strlen(argv[1])+1);
strcpy(buff, argv[1]);
rtos_msg_t msg;
msg.handler = msgbus_handler;
msg.ptr = buff;
luat_msgbus_put(&msg, 0);
};
#include "luat_dbg.h"
static void dbg(int argc, char**argv) {
if (argc < 2)
return;
if (!strcmp("start", argv[1])) {
luat_dbg_set_hook_state(2);
}
else if (!strcmp("next", argv[1]) || !strcmp("step", argv[1])) {
luat_dbg_set_hook_state(4);
}
else if (!strcmp("stepin", argv[1]) || !strcmp("stepIn", argv[1])) {
luat_dbg_set_hook_state(5);
}
else if (!strcmp("stepout", argv[1]) || !strcmp("stepOut", argv[1])) {
luat_dbg_set_hook_state(6);
}
else if (!strcmp("continue", argv[1])) {
luat_dbg_set_hook_state(2);
}
else if (!strcmp("bt", argv[1])) {
if (argc > 2) {
luat_dbg_set_runcb(luat_dbg_backtrace, (void*)atoi(argv[2]));
}
else {
luat_dbg_set_runcb(luat_dbg_backtrace, (void*)-1);
}
}
else if (!strcmp("vars", argv[1])) {
if (argc > 2) {
luat_dbg_set_runcb(luat_dbg_vars, (void*)atoi(argv[2]));
}
else {
luat_dbg_set_runcb(luat_dbg_vars, (void*)0);
}
}
else if (!strcmp("break", argv[1])) {
if (!strcmp("add", argv[2]) && argc == 5) {
luat_dbg_breakpoint_add(argv[3], atoi(argv[4]));
}
else if (!strcmp("del", argv[2]) && argc == 4) {
luat_dbg_breakpoint_del(atoi(argv[3]));
}
else if (!strcmp("clr", argv[2]) || !strcmp("clear", argv[2])) {
if (argc > 3)
luat_dbg_breakpoint_clear(argv[3]);
else
luat_dbg_breakpoint_clear(NULL);
}
}
};
MSH_CMD_EXPORT(loadstr , run lua code);
MSH_CMD_EXPORT(dbg , luat debugger);
#endif
|
tiagobarretomc/transmetaisWeb
|
src/br/com/transmetais/controller/UserSession.java
|
<filename>src/br/com/transmetais/controller/UserSession.java
package br.com.transmetais.controller;
import java.io.Serializable;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.SessionScoped;
import br.com.transmetais.bean.Usuario;
@Component
@SessionScoped
public class UserSession implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7335609776581390861L;
private Usuario user;
public boolean isLogged() {
return getUser() != null;
}
public void logout() {
setUser(null);
}
public Usuario getUser() {
return user;
}
public void setUser(Usuario user) {
this.user = user;
}
}
|
pimmu1s/Origami
|
src/graph/clean/vertices_isolated.js
|
<gh_stars>100-1000
/**
* Rabbit Ear (c) <NAME>
*/
export const get_edge_isolated_vertices = ({ vertices_coords, edges_vertices }) => {
let count = vertices_coords.length;
const seen = Array(count).fill(false);
edges_vertices.forEach((ev) => {
ev.filter(v => !seen[v]).forEach((v) => {
seen[v] = true;
count -= 1;
});
});
return seen
.map((s, i) => (s ? undefined : i))
.filter(a => a !== undefined);
};
export const get_face_isolated_vertices = ({ vertices_coords, faces_vertices }) => {
let count = vertices_coords.length;
const seen = Array(count).fill(false);
faces_vertices.forEach((fv) => {
fv.filter(v => !seen[v]).forEach((v) => {
seen[v] = true;
count -= 1;
});
});
return seen
.map((s, i) => (s ? undefined : i))
.filter(a => a !== undefined);
};
// todo this could be improved. for loop instead of forEach + filter.
// break the loop early.
export const get_isolated_vertices = ({ vertices_coords, edges_vertices, faces_vertices }) => {
let count = vertices_coords.length;
const seen = Array(count).fill(false);
if (edges_vertices) {
edges_vertices.forEach((ev) => {
ev.filter(v => !seen[v]).forEach((v) => {
seen[v] = true;
count -= 1;
});
});
}
if (faces_vertices) {
faces_vertices.forEach((fv) => {
fv.filter(v => !seen[v]).forEach((v) => {
seen[v] = true;
count -= 1;
});
});
}
return seen
.map((s, i) => (s ? undefined : i))
.filter(a => a !== undefined);
};
|
philcali/rss
|
rss-api/src/main/java/me/philcali/rss/api/exception/ArticleInstanceStorageException.java
|
package me.philcali.rss.api.exception;
public class ArticleInstanceStorageException extends RuntimeException {
private static final long serialVersionUID = 1829781894209798729L;
public ArticleInstanceStorageException(final Throwable ex) {
super(ex);
}
}
|
CMU-TRP/podd-api
|
accounts/management/commands/create_authority_invite_for_ph.py
|
<filename>accounts/management/commands/create_authority_invite_for_ph.py<gh_stars>1-10
# -*- encoding: utf-8 -*-
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from accounts.models import Authority, AuthorityInvite
from common.constants import USER_STATUS_PUBLIC_HEALTH
from common.functions import get_data_from_csv
from reports.models import AdministrationArea
class Command(BaseCommand):
args = 'domain_id'
help = 'create invitation code for public health authority.'
def handle(self, *args, **options):
if not args:
raise CommandError('Please provide domain_id')
domain_id = args[0]
settings.CURRENT_DOMAIN_ID = domain_id
# first pass
for authority in Authority.objects.filter(domain_id=domain_id):
if not AuthorityInvite.objects.filter(status=USER_STATUS_PUBLIC_HEALTH, authority=authority, disabled=False).exists():
print 'create invite for %s' % (authority.code,)
ph_invite = AuthorityInvite(
authority=authority,
status=USER_STATUS_PUBLIC_HEALTH
)
ph_invite.save()
|
mareknovotny/kie-wb-common
|
kie-wb-common-stunner/kie-wb-common-stunner-client/kie-wb-common-stunner-widgets/src/test/java/org/kie/workbench/common/stunner/client/widgets/presenters/AbstractCanvasHandlerViewerTest.java
|
<filename>kie-wb-common-stunner/kie-wb-common-stunner-client/kie-wb-common-stunner-widgets/src/test/java/org/kie/workbench/common/stunner/client/widgets/presenters/AbstractCanvasHandlerViewerTest.java
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.client.widgets.presenters;
import com.google.gwt.user.client.ui.Widget;
import org.kie.workbench.common.stunner.client.lienzo.canvas.wires.WiresCanvas;
import org.kie.workbench.common.stunner.client.widgets.canvas.view.LienzoPanel;
import org.kie.workbench.common.stunner.client.widgets.canvas.wires.WiresCanvasPresenter;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandResultBuilder;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.graph.Graph;
import org.kie.workbench.common.stunner.core.graph.content.Bounds;
import org.kie.workbench.common.stunner.core.graph.content.definition.DefinitionSet;
import org.kie.workbench.common.stunner.core.graph.content.view.BoundImpl;
import org.kie.workbench.common.stunner.core.graph.content.view.BoundsImpl;
import org.mockito.Mock;
import org.uberfire.mvp.ParameterizedCommand;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
public abstract class AbstractCanvasHandlerViewerTest {
protected final static Bounds GRAPH_BOUNDS = new BoundsImpl(new BoundImpl(0d,
0d),
new BoundImpl(100d,
100d));
@Mock
protected WiresCanvasPresenter canvas;
@Mock
protected WiresCanvas.View canvasView;
@Mock
protected Widget canvasViewWidget;
@Mock
protected LienzoPanel lienzoPanel;
@Mock
protected AbstractCanvasHandler canvasHandler;
@Mock
protected Diagram diagram;
@Mock
protected Graph graph;
@Mock
protected DefinitionSet graphContent;
protected Diagram canvasHandlerDiagram;
@SuppressWarnings("unchecked")
public void init() throws Exception {
this.canvasHandlerDiagram = null;
when(canvas.getView()).thenReturn(canvasView);
when(canvasView.asWidget()).thenReturn(canvasViewWidget);
when(canvas.getLienzoPanel()).thenReturn(lienzoPanel);
when(canvasHandler.getCanvas()).thenReturn(canvas);
when(canvasHandler.getAbstractCanvas()).thenReturn(canvas);
// The different viewer/editors tested reply on the canvas handler to obtain
// the diagram instance, so applying mocked answers for CanvasHandler #open,
// #clear and #destroy to handle the right diagram instance.
doAnswer(invocationOnMock -> {
final Diagram d = (Diagram) invocationOnMock.getArguments()[0];
final ParameterizedCommand<CommandResult<?>> c = (ParameterizedCommand) invocationOnMock.getArguments()[1];
AbstractCanvasHandlerViewerTest.this.canvasHandlerDiagram = d;
when(canvasHandler.getDiagram()).thenReturn(canvasHandlerDiagram);
c.execute(CanvasCommandResultBuilder.SUCCESS);
return null;
}).when(canvasHandler).draw(any(Diagram.class),
any(ParameterizedCommand.class));
doAnswer(invocationOnMock -> {
AbstractCanvasHandlerViewerTest.this.canvasHandlerDiagram = null;
when(canvasHandler.getDiagram()).thenReturn(canvasHandlerDiagram);
return null;
}).when(canvasHandler).clear();
doAnswer(invocationOnMock -> {
AbstractCanvasHandlerViewerTest.this.canvasHandlerDiagram = null;
when(canvasHandler.getDiagram()).thenReturn(canvasHandlerDiagram);
return null;
}).when(canvasHandler).destroy();
when(diagram.getGraph()).thenReturn(graph);
when(graph.getContent()).thenReturn(graphContent);
when(graphContent.getBounds()).thenReturn(GRAPH_BOUNDS);
}
}
|
bencmitchell/teaching-vacancies
|
spec/models/equal_opportunities_report_spec.rb
|
require "rails_helper"
RSpec.describe EqualOpportunitiesReport do
it { is_expected.to belong_to(:vacancy) }
describe "#trigger_event" do
it "triggers an event of the correct type" do
expect { described_class.new.trigger_event }.to have_triggered_event(:equal_opportunities_report_published).with_data({ table_name: "equal_opportunities_reports" })
end
end
end
|
jaylinhong/jdk14-learn
|
src/jdk14-source/jdk.jdi/com/sun/tools/jdi/PacketStream.java
|
/*
* Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.tools.jdi;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.sun.jdi.BooleanValue;
import com.sun.jdi.ByteValue;
import com.sun.jdi.CharValue;
import com.sun.jdi.ClassType;
import com.sun.jdi.DoubleValue;
import com.sun.jdi.Field;
import com.sun.jdi.FloatValue;
import com.sun.jdi.IntegerValue;
import com.sun.jdi.InterfaceType;
import com.sun.jdi.InternalException;
import com.sun.jdi.InvalidTypeException;
import com.sun.jdi.Location;
import com.sun.jdi.LongValue;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.PrimitiveValue;
import com.sun.jdi.ShortValue;
import com.sun.jdi.Value;
class PacketStream {
final VirtualMachineImpl vm;
private int inCursor = 0;
final Packet pkt;
private ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
private boolean isCommitted = false;
PacketStream(VirtualMachineImpl vm, int cmdSet, int cmd) {
this.vm = vm;
this.pkt = new Packet();
pkt.cmdSet = (short)cmdSet;
pkt.cmd = (short)cmd;
}
PacketStream(VirtualMachineImpl vm, Packet pkt) {
this.vm = vm;
this.pkt = pkt;
this.isCommitted = true; /* read only stream */
}
int id() {
return pkt.id;
}
void send() {
if (!isCommitted) {
pkt.data = dataStream.toByteArray();
vm.sendToTarget(pkt);
isCommitted = true;
}
}
void waitForReply() throws JDWPException {
if (!isCommitted) {
throw new InternalException("waitForReply without send");
}
vm.waitForTargetReply(pkt);
if (pkt.errorCode != Packet.ReplyNoError) {
throw new JDWPException(pkt.errorCode);
}
}
void writeBoolean(boolean data) {
if(data) {
dataStream.write( 1 );
} else {
dataStream.write( 0 );
}
}
void writeByte(byte data) {
dataStream.write( data );
}
void writeChar(char data) {
dataStream.write( (byte)((data >>> 8) & 0xFF) );
dataStream.write( (byte)((data >>> 0) & 0xFF) );
}
void writeShort(short data) {
dataStream.write( (byte)((data >>> 8) & 0xFF) );
dataStream.write( (byte)((data >>> 0) & 0xFF) );
}
void writeInt(int data) {
dataStream.write( (byte)((data >>> 24) & 0xFF) );
dataStream.write( (byte)((data >>> 16) & 0xFF) );
dataStream.write( (byte)((data >>> 8) & 0xFF) );
dataStream.write( (byte)((data >>> 0) & 0xFF) );
}
void writeLong(long data) {
dataStream.write( (byte)((data >>> 56) & 0xFF) );
dataStream.write( (byte)((data >>> 48) & 0xFF) );
dataStream.write( (byte)((data >>> 40) & 0xFF) );
dataStream.write( (byte)((data >>> 32) & 0xFF) );
dataStream.write( (byte)((data >>> 24) & 0xFF) );
dataStream.write( (byte)((data >>> 16) & 0xFF) );
dataStream.write( (byte)((data >>> 8) & 0xFF) );
dataStream.write( (byte)((data >>> 0) & 0xFF) );
}
void writeFloat(float data) {
writeInt(Float.floatToIntBits(data));
}
void writeDouble(double data) {
writeLong(Double.doubleToLongBits(data));
}
void writeID(int size, long data) {
switch (size) {
case 8:
writeLong(data);
break;
case 4:
writeInt((int)data);
break;
case 2:
writeShort((short)data);
break;
default:
throw new UnsupportedOperationException("JDWP: ID size not supported: " + size);
}
}
void writeNullObjectRef() {
writeObjectRef(0);
}
void writeObjectRef(long data) {
writeID(vm.sizeofObjectRef, data);
}
void writeClassRef(long data) {
writeID(vm.sizeofClassRef, data);
}
void writeMethodRef(long data) {
writeID(vm.sizeofMethodRef, data);
}
void writeModuleRef(long data) {
writeID(vm.sizeofModuleRef, data);
}
void writeFieldRef(long data) {
writeID(vm.sizeofFieldRef, data);
}
void writeFrameRef(long data) {
writeID(vm.sizeofFrameRef, data);
}
void writeByteArray(byte[] data) {
dataStream.write(data, 0, data.length);
}
void writeString(String string) {
try {
byte[] stringBytes = string.getBytes("UTF8");
writeInt(stringBytes.length);
writeByteArray(stringBytes);
} catch (java.io.UnsupportedEncodingException e) {
throw new InternalException("Cannot convert string to UTF8 bytes");
}
}
void writeLocation(Location location) {
ReferenceTypeImpl refType = (ReferenceTypeImpl)location.declaringType();
byte tag;
if (refType instanceof ClassType) {
tag = JDWP.TypeTag.CLASS;
} else if (refType instanceof InterfaceType) {
// It's possible to have executable code in an interface
tag = JDWP.TypeTag.INTERFACE;
} else {
throw new InternalException("Invalid Location");
}
writeByte(tag);
writeClassRef(refType.ref());
writeMethodRef(((MethodImpl)location.method()).ref());
writeLong(location.codeIndex());
}
void writeValue(Value val) {
try {
writeValueChecked(val);
} catch (InvalidTypeException exc) { // should never happen
throw new RuntimeException(
"Internal error: Invalid Tag/Type pair");
}
}
void writeValueChecked(Value val) throws InvalidTypeException {
writeByte(ValueImpl.typeValueKey(val));
writeUntaggedValue(val);
}
void writeUntaggedValue(Value val) {
try {
writeUntaggedValueChecked(val);
} catch (InvalidTypeException exc) { // should never happen
throw new RuntimeException(
"Internal error: Invalid Tag/Type pair");
}
}
void writeUntaggedValueChecked(Value val) throws InvalidTypeException {
byte tag = ValueImpl.typeValueKey(val);
if (isObjectTag(tag)) {
if (val == null) {
writeObjectRef(0);
} else {
if (!(val instanceof ObjectReference)) {
throw new InvalidTypeException();
}
writeObjectRef(((ObjectReferenceImpl)val).ref());
}
} else {
switch (tag) {
case JDWP.Tag.BYTE:
if(!(val instanceof ByteValue))
throw new InvalidTypeException();
writeByte(((PrimitiveValue)val).byteValue());
break;
case JDWP.Tag.CHAR:
if(!(val instanceof CharValue))
throw new InvalidTypeException();
writeChar(((PrimitiveValue)val).charValue());
break;
case JDWP.Tag.FLOAT:
if(!(val instanceof FloatValue))
throw new InvalidTypeException();
writeFloat(((PrimitiveValue)val).floatValue());
break;
case JDWP.Tag.DOUBLE:
if(!(val instanceof DoubleValue))
throw new InvalidTypeException();
writeDouble(((PrimitiveValue)val).doubleValue());
break;
case JDWP.Tag.INT:
if(!(val instanceof IntegerValue))
throw new InvalidTypeException();
writeInt(((PrimitiveValue)val).intValue());
break;
case JDWP.Tag.LONG:
if(!(val instanceof LongValue))
throw new InvalidTypeException();
writeLong(((PrimitiveValue)val).longValue());
break;
case JDWP.Tag.SHORT:
if(!(val instanceof ShortValue))
throw new InvalidTypeException();
writeShort(((PrimitiveValue)val).shortValue());
break;
case JDWP.Tag.BOOLEAN:
if(!(val instanceof BooleanValue))
throw new InvalidTypeException();
writeBoolean(((PrimitiveValue)val).booleanValue());
break;
}
}
}
/**
* Read byte represented as one bytes.
*/
byte readByte() {
byte ret = pkt.data[inCursor];
inCursor += 1;
return ret;
}
/**
* Read boolean represented as one byte.
*/
boolean readBoolean() {
byte ret = readByte();
return (ret != 0);
}
/**
* Read char represented as two bytes.
*/
char readChar() {
int b1, b2;
b1 = pkt.data[inCursor++] & 0xff;
b2 = pkt.data[inCursor++] & 0xff;
return (char)((b1 << 8) + b2);
}
/**
* Read short represented as two bytes.
*/
short readShort() {
int b1, b2;
b1 = pkt.data[inCursor++] & 0xff;
b2 = pkt.data[inCursor++] & 0xff;
return (short)((b1 << 8) + b2);
}
/**
* Read int represented as four bytes.
*/
int readInt() {
int b1,b2,b3,b4;
b1 = pkt.data[inCursor++] & 0xff;
b2 = pkt.data[inCursor++] & 0xff;
b3 = pkt.data[inCursor++] & 0xff;
b4 = pkt.data[inCursor++] & 0xff;
return ((b1 << 24) + (b2 << 16) + (b3 << 8) + b4);
}
/**
* Read long represented as eight bytes.
*/
long readLong() {
long b1,b2,b3,b4;
long b5,b6,b7,b8;
b1 = pkt.data[inCursor++] & 0xff;
b2 = pkt.data[inCursor++] & 0xff;
b3 = pkt.data[inCursor++] & 0xff;
b4 = pkt.data[inCursor++] & 0xff;
b5 = pkt.data[inCursor++] & 0xff;
b6 = pkt.data[inCursor++] & 0xff;
b7 = pkt.data[inCursor++] & 0xff;
b8 = pkt.data[inCursor++] & 0xff;
return ((b1 << 56) + (b2 << 48) + (b3 << 40) + (b4 << 32)
+ (b5 << 24) + (b6 << 16) + (b7 << 8) + b8);
}
/**
* Read float represented as four bytes.
*/
float readFloat() {
return Float.intBitsToFloat(readInt());
}
/**
* Read double represented as eight bytes.
*/
double readDouble() {
return Double.longBitsToDouble(readLong());
}
/**
* Read string represented as four byte length followed by
* characters of the string.
*/
String readString() {
String ret;
int len = readInt();
try {
ret = new String(pkt.data, inCursor, len, "UTF8");
} catch(java.io.UnsupportedEncodingException e) {
System.err.println(e);
ret = "Conversion error!";
}
inCursor += len;
return ret;
}
private long readID(int size) {
switch (size) {
case 8:
return readLong();
case 4:
return readInt();
case 2:
return readShort();
default:
throw new UnsupportedOperationException("JDWP: ID size not supported: " + size);
}
}
/**
* Read object represented as vm specific byte sequence.
*/
long readObjectRef() {
return readID(vm.sizeofObjectRef);
}
long readClassRef() {
return readID(vm.sizeofClassRef);
}
ObjectReferenceImpl readTaggedObjectReference() {
byte typeKey = readByte();
return vm.objectMirror(readObjectRef(), typeKey);
}
ObjectReferenceImpl readObjectReference() {
return vm.objectMirror(readObjectRef());
}
StringReferenceImpl readStringReference() {
long ref = readObjectRef();
return vm.stringMirror(ref);
}
ArrayReferenceImpl readArrayReference() {
long ref = readObjectRef();
return vm.arrayMirror(ref);
}
ThreadReferenceImpl readThreadReference() {
long ref = readObjectRef();
return vm.threadMirror(ref);
}
ThreadGroupReferenceImpl readThreadGroupReference() {
long ref = readObjectRef();
return vm.threadGroupMirror(ref);
}
ClassLoaderReferenceImpl readClassLoaderReference() {
long ref = readObjectRef();
return vm.classLoaderMirror(ref);
}
ClassObjectReferenceImpl readClassObjectReference() {
long ref = readObjectRef();
return vm.classObjectMirror(ref);
}
ReferenceTypeImpl readReferenceType() {
byte tag = readByte();
long ref = readObjectRef();
return vm.referenceType(ref, tag);
}
ModuleReferenceImpl readModule() {
long ref = readModuleRef();
return vm.moduleMirror(ref);
}
/**
* Read method reference represented as vm specific byte sequence.
*/
long readMethodRef() {
return readID(vm.sizeofMethodRef);
}
/**
* Read module reference represented as vm specific byte sequence.
*/
long readModuleRef() {
return readID(vm.sizeofModuleRef);
}
/**
* Read field reference represented as vm specific byte sequence.
*/
long readFieldRef() {
return readID(vm.sizeofFieldRef);
}
/**
* Read field represented as vm specific byte sequence.
*/
Field readField() {
ReferenceTypeImpl refType = readReferenceType();
long fieldRef = readFieldRef();
return refType.getFieldMirror(fieldRef);
}
/**
* Read frame represented as vm specific byte sequence.
*/
long readFrameRef() {
return readID(vm.sizeofFrameRef);
}
/**
* Read a value, first byte describes type of value to read.
*/
ValueImpl readValue() {
byte typeKey = readByte();
return readUntaggedValue(typeKey);
}
ValueImpl readUntaggedValue(byte typeKey) {
ValueImpl val = null;
if (isObjectTag(typeKey)) {
val = vm.objectMirror(readObjectRef(), typeKey);
} else {
switch(typeKey) {
case JDWP.Tag.BYTE:
val = new ByteValueImpl(vm, readByte());
break;
case JDWP.Tag.CHAR:
val = new CharValueImpl(vm, readChar());
break;
case JDWP.Tag.FLOAT:
val = new FloatValueImpl(vm, readFloat());
break;
case JDWP.Tag.DOUBLE:
val = new DoubleValueImpl(vm, readDouble());
break;
case JDWP.Tag.INT:
val = new IntegerValueImpl(vm, readInt());
break;
case JDWP.Tag.LONG:
val = new LongValueImpl(vm, readLong());
break;
case JDWP.Tag.SHORT:
val = new ShortValueImpl(vm, readShort());
break;
case JDWP.Tag.BOOLEAN:
val = new BooleanValueImpl(vm, readBoolean());
break;
case JDWP.Tag.VOID:
val = new VoidValueImpl(vm);
break;
}
}
return val;
}
/**
* Read location represented as vm specific byte sequence.
*/
Location readLocation() {
byte tag = readByte();
long classRef = readObjectRef();
long methodRef = readMethodRef();
long codeIndex = readLong();
if (classRef != 0) {
/* Valid location */
ReferenceTypeImpl refType = vm.referenceType(classRef, tag);
return new LocationImpl(vm, refType, methodRef, codeIndex);
} else {
/* Null location (example: uncaught exception) */
return null;
}
}
byte[] readByteArray(int length) {
byte[] array = new byte[length];
System.arraycopy(pkt.data, inCursor, array, 0, length);
inCursor += length;
return array;
}
List<Value> readArrayRegion() {
byte typeKey = readByte();
int length = readInt();
List<Value> list = new ArrayList<>(length);
boolean gettingObjects = isObjectTag(typeKey);
for (int i = 0; i < length; i++) {
/*
* Each object comes back with a type key which might
* identify a more specific type than the type key we
* passed in, so we use it in the decodeValue call.
* (For primitives, we just use the original one)
*/
if (gettingObjects) {
typeKey = readByte();
}
Value value = readUntaggedValue(typeKey);
list.add(value);
}
return list;
}
void writeArrayRegion(List<Value> srcValues) {
writeInt(srcValues.size());
for (int i = 0; i < srcValues.size(); i++) {
Value value = srcValues.get(i);
writeUntaggedValue(value);
}
}
int skipBytes(int n) {
inCursor += n;
return n;
}
byte command() {
return (byte)pkt.cmd;
}
static boolean isObjectTag(byte tag) {
return (tag == JDWP.Tag.OBJECT) ||
(tag == JDWP.Tag.ARRAY) ||
(tag == JDWP.Tag.STRING) ||
(tag == JDWP.Tag.THREAD) ||
(tag == JDWP.Tag.THREAD_GROUP) ||
(tag == JDWP.Tag.CLASS_LOADER) ||
(tag == JDWP.Tag.CLASS_OBJECT);
}
}
|
bwplotka/keanu
|
keanu-project/src/test/java/io/improbable/keanu/algorithms/mcmc/HamiltonianTest.java
|
package io.improbable.keanu.algorithms.mcmc;
import io.improbable.keanu.DeterministicRule;
import io.improbable.keanu.algorithms.NetworkSamples;
import io.improbable.keanu.network.BayesianNetwork;
import io.improbable.keanu.tensor.dbl.DoubleTensor;
import io.improbable.keanu.testcategory.Slow;
import io.improbable.keanu.vertices.Vertex;
import io.improbable.keanu.vertices.dbl.KeanuRandom;
import io.improbable.keanu.vertices.dbl.probabilistic.GaussianVertex;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class HamiltonianTest {
@Rule
public DeterministicRule deterministicRule = new DeterministicRule();
@Category(Slow.class)
@Test
public void samplesGaussian() {
double mu = 0.0;
double sigma = 1.0;
KeanuRandom random = KeanuRandom.getDefaultRandom();
BayesianNetwork simpleGaussian = MCMCTestDistributions.createSimpleGaussian(mu, sigma, random.nextGaussian(0, 1), random);
Hamiltonian hmc = Hamiltonian.builder()
.leapFrogCount(20)
.stepSize(0.05)
.build();
NetworkSamples posteriorSamples = hmc.getPosteriorSamples(
simpleGaussian,
simpleGaussian.getLatentVertices(),
2000
);
Vertex<DoubleTensor> vertex = simpleGaussian.getContinuousLatentVertices().get(0);
MCMCTestDistributions.samplesMatchSimpleGaussian(mu, sigma, posteriorSamples.get(vertex).asList(), 0.1);
}
@Test
public void samplesContinuousPrior() {
BayesianNetwork bayesNet = MCMCTestDistributions.createSumOfGaussianDistribution(20.0, 1.0, 46.0, 20.0);
Hamiltonian hmc = Hamiltonian.builder()
.leapFrogCount(20)
.stepSize(0.1)
.build();
NetworkSamples posteriorSamples = hmc.getPosteriorSamples(
bayesNet,
bayesNet.getLatentVertices(),
600
);
Vertex<DoubleTensor> A = bayesNet.getContinuousLatentVertices().get(0);
Vertex<DoubleTensor> B = bayesNet.getContinuousLatentVertices().get(1);
MCMCTestDistributions.samplesMatchesSumOfGaussians(44.0, posteriorSamples.get(A).asList(), posteriorSamples.get(B).asList());
}
@Category(Slow.class)
@Test
public void samplesFromDonut() {
BayesianNetwork donutBayesNet = MCMCTestDistributions.create2DDonutDistribution();
Vertex<DoubleTensor> A = donutBayesNet.getContinuousLatentVertices().get(0);
Vertex<DoubleTensor> B = donutBayesNet.getContinuousLatentVertices().get(1);
Hamiltonian hmc = Hamiltonian.builder()
.leapFrogCount(15)
.stepSize(0.02)
.build();
Map<Vertex, List<DoubleTensor>> samples = new HashMap<>();
hmc.generatePosteriorSamples(donutBayesNet, donutBayesNet.getLatentVertices())
.stream()
.limit(350)
.forEach(x -> {
samples.computeIfAbsent(A, k -> new ArrayList<>()).add(x.get(A));
samples.computeIfAbsent(B, k -> new ArrayList<>()).add(x.get(B));
});
MCMCTestDistributions.samplesMatch2DDonut(samples.get(A), samples.get(B));
}
@Test
public void canDefaultToSettingsInBuilderAndIsConfigurableAfterBuilding() {
GaussianVertex A = new GaussianVertex(0.0, 1.0);
BayesianNetwork net = new BayesianNetwork(A.getConnectedGraph());
net.probeForNonZeroProbability(100, KeanuRandom.getDefaultRandom());
Hamiltonian hmc = Hamiltonian.builder()
.build();
assertTrue(hmc.getLeapFrogCount() > 0);
assertTrue(hmc.getStepSize() > 0);
assertNotNull(hmc.getRandom());
NetworkSamples posteriorSamples = hmc.getPosteriorSamples(
net,
net.getLatentVertices(),
2
);
hmc.setRandom(null);
assertNull(hmc.getRandom());
assertFalse(posteriorSamples.get(A).asList().isEmpty());
}
@Test
public void canStreamSamples() {
Hamiltonian hmc = Hamiltonian.builder()
.leapFrogCount(10)
.stepSize(0.4)
.build();
double mu = 0;
double sigma = 1;
GaussianVertex A = new GaussianVertex(mu, sigma);
BayesianNetwork network = new BayesianNetwork(A.getConnectedGraph());
List<DoubleTensor> samples = hmc.generatePosteriorSamples(network, network.getLatentVertices())
.downSampleInterval(1)
.stream()
.limit(500)
.map(x -> x.get(A))
.collect(Collectors.toList());
MCMCTestDistributions.samplesMatchSimpleGaussian(mu, sigma, samples, 0.3);
}
}
|
amvnetworks/amv-trafficsoft-datahub
|
xfcd-consumer-sqlite/src/main/java/org/amv/trafficsoft/xfcd/consumer/sqlite/TrafficsoftXfcdXfcdSqliteDaoImpl.java
|
<reponame>amvnetworks/amv-trafficsoft-datahub
package org.amv.trafficsoft.xfcd.consumer.sqlite;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.amv.trafficsoft.xfcd.consumer.jdbc.TrafficsoftXfcdXfcdEntity;
import org.amv.trafficsoft.xfcd.consumer.jdbc.TrafficsoftXfcdXfcdJdbcDao;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
@Transactional(transactionManager = "trafficsoftDeliveryJdbcConsumerTransactionManager")
public class TrafficsoftXfcdXfcdSqliteDaoImpl implements TrafficsoftXfcdXfcdJdbcDao {
private final NamedParameterJdbcTemplate jdbcTemplate;
private final RowMapper<TrafficsoftXfcdXfcdEntity> rowMapper;
public TrafficsoftXfcdXfcdSqliteDaoImpl(NamedParameterJdbcTemplate jdbcTemplate, RowMapper<TrafficsoftXfcdXfcdEntity> rowMapper) {
this.jdbcTemplate = requireNonNull(jdbcTemplate);
this.rowMapper = requireNonNull(rowMapper);
}
@Override
public void saveAll(List<TrafficsoftXfcdXfcdEntity> entities) {
requireNonNull(entities);
/**
* `INSERT OR IGNORE` is used here so no DuplicateKeyException is thrown
* if the delivery has already been saved.
* This might happen if a delivery has been saved but not confirmed
* for example due to an application shutdown.
*/
String sql = "INSERT OR IGNORE INTO `amv_trafficsoft_xfcd_xfcd` " +
"(`CREATED_AT`, `IMXFCD_N_ID`, `TYPE`, `VAL`, `VALSTR`) " +
"VALUES (:createdAt, :nodeId, :type, :value, :valueAsString)";
entities.forEach(entity -> {
Map<String, Object> paramMap = Maps.newHashMapWithExpectedSize(5);
paramMap.put("createdAt", Timestamp.from(Instant.now()));
paramMap.put("nodeId", entity.getNodeId());
paramMap.put("type", entity.getType());
paramMap.put("value", entity.getValue().orElse(null));
paramMap.put("valueAsString", entity.getValueAsString().orElse(null));
jdbcTemplate.update(sql, paramMap);
});
}
@Override
public List<TrafficsoftXfcdXfcdEntity> findByNodeId(long nodeId) {
String sql = "SELECT `IMXFCD_N_ID`, `TYPE`, `VAL`, `VALSTR` " +
"FROM `IMXFCD_Xfcd` " +
"WHERE `IMXFCD_N_ID` = :nodeId " +
"ORDER BY `TYPE`";
List<TrafficsoftXfcdXfcdEntity> xfcds = jdbcTemplate.query(sql, ImmutableMap.<String, Object>builder()
.put("nodeId", nodeId)
.build(), rowMapper);
return ImmutableList.copyOf(xfcds);
}
@Override
public List<TrafficsoftXfcdXfcdEntity> findByNodeIds(List<Long> nodeIds) {
requireNonNull(nodeIds, "`nodeIds` must not be null");
if (nodeIds.isEmpty()) {
return Collections.emptyList();
}
String sql = "SELECT `IMXFCD_N_ID`, `TYPE`, `VAL`, `VALSTR` " +
"FROM `IMXFCD_Xfcd` " +
"WHERE `IMXFCD_N_ID` IN(:nodeIds) " +
"ORDER BY `TYPE`";
List<TrafficsoftXfcdXfcdEntity> xfcds = jdbcTemplate.query(sql, ImmutableMap.<String, Object>builder()
.put("nodeIds", nodeIds)
.build(), rowMapper);
return ImmutableList.copyOf(xfcds);
}
}
|
heypano/weirdcharacters
|
src/api/cats.js
|
import service from "../util/service";
export function getCats() {
return service.get("cats");
}
export function getCats2() {
return service.get("cats2");
}
export function getCats3() {
return service.get("cats3");
}
export default {
getCats: getCats,
getCats2: getCats2,
getCats3: getCats3
};
|
icarito/steal-tools
|
lib/bundle/minify_source.js
|
var minifiers = {
css: require("../build_types/minify_css"),
js: require("../build_types/minify_js").async
};
module.exports = function(bundle, options) {
var opts = options || {};
var minify = minifiers[bundle.buildType];
// Minification is optional, but on by default
var shouldMinify = (opts.minify !== false) && !!minify;
return shouldMinify ?
minify(bundle.source, opts) :
Promise.resolve(bundle.source);
};
|
minhaj3/onsite-seo
|
Gruntfile.js
|
<filename>Gruntfile.js
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
copy: {
seoData: {
files: [
{ expand: true, src: ['seo-data.json'], dest: 'app', filter: 'isFile' }
]
},
dist: {
files: [
{
expand: true,
cwd: 'app',
src: ['*.json'],
dest: 'dist'
},
{
expand: true,
cwd: 'app/bower_components/bootstrap/fonts',
src: ['*'],
dest: 'dist/fonts'
}
]
}
},
browserify: {
dist: {
files: {
'app/js/bundle.js': ['lib/ratings.js', 'lib/urlUtils.js', 'lib/properties.js','lib/lightdom.js'],
'lib/inspectorBundle.js': ['lib/inspector.js']
},
options: {
alias: 'lib/ratings.js:ratings,lib/urlUtils.js:urlUtils,lib/properties.js:properties,lib/lightdom.js:lightdom,lib/inspector.js:inspector'
}
}
},
watch: {
app: {
files: ['app/**', 'lib/**'],
tasks: ['app'],
options: {
livereload: true,
spawn: false
}
}
},
processhtml: {
dist: {
options: {
process: true,
inline: true
},
files: {
'dist/index.html': ['dist/index.html']
}
}
},
ngtemplates: {
app: {
options: {
module: 'seoApp',
usemin: 'dist/js/seoapp.js',
htmlmin: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: false, // Only if you don't use comment directives!
removeEmptyAttributes: true
}
},
cwd: 'app',
src: ['partials/**/*.html'],
dest: '.tmp/js/templates.js'
}
},
useminPrepare: {
html: 'app/index.html',
options: {
dest: 'dist'
}
},
usemin: {
html: ['dist/{,*/}*.html'],
css: ['dist/css/{,*/}*.css'],
options: {
dirs: ['dist']
}
},
express: {
dev: {
options: {
port: 3000,
bases: ['app'],
serverreload: false
}
},
server: {
options: {
port: 3000,
bases: ['dist']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-express');
grunt.loadNpmTasks('grunt-processhtml');
grunt.loadNpmTasks('grunt-usemin');
grunt.loadNpmTasks('grunt-angular-templates');
grunt.registerTask('app', ['copy:seoData', 'browserify']);
grunt.registerTask('dist', [
'app',
'useminPrepare',
'ngtemplates:app',
'copy:dist',
'processhtml:dist',
'concat',
'uglify',
'cssmin',
'usemin']);
grunt.registerTask('dev', ['app', 'express:dev', 'watch:app']);
grunt.registerTask('server', ['dist', 'express:server', 'express-keepalive']);
grunt.registerTask('default', ['app']);
};
|
joycgj/camelmq
|
cmq-remoting/src/main/java/camel/tc/cmq/protocol/consumer/MetaInfoRequestPayloadHolder.java
|
<gh_stars>0
package camel.tc.cmq.protocol.consumer;
import io.netty.buffer.ByteBuf;
import camel.tc.cmq.protocol.PayloadHolder;
import camel.tc.cmq.utils.PayloadHolderUtils;
// done
public class MetaInfoRequestPayloadHolder implements PayloadHolder {
private final MetaInfoRequest request;
public MetaInfoRequestPayloadHolder(MetaInfoRequest request) {
this.request = request;
}
@Override
public void writeBody(ByteBuf out) {
PayloadHolderUtils.writeStringMap(request.getAttrs(), out);
}
}
|
schrepfler/bullet-ui
|
app/utils/codemirror-adapter.js
|
/*
* Copyright 2020, Yahoo Inc.
* Licensed under the terms of the Apache License, Version 2.0.
* See the LICENSE file associated with the project for terms.
*/
import CodeMirror from 'codemirror';
import 'codemirror/mode/sql/sql';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/hint/sql-hint';
import isEmpty from 'bullet-ui/utils/is-empty';
import QueryConverter from 'bullet-ui/utils/query-converter';
const MIME = 'text/x-bql';
// Adapted from https://github.com/codemirror/CodeMirror/blob/master/mode/sql/sql.js
function set(str) {
let object = { };
str.split(' ').forEach(word => {
object[word] = true;
});
return object;
}
export function defineBQL() {
CodeMirror.defineMIME(MIME, {
name: 'sql',
keywords: set('select as cast count distinct sum min max avg from where if and or not xor is all any true false ' +
'null group by having order asc desc limit every first time record linear region manual stream ' +
'windowing tumbling quantile freq cumfreq top sizeis sizeof filter rlike containskey containsvalue ' +
'lateral view outer explode trim abs between substr substring unixtimestamp'),
builtin: set('string boolean integer long float double map list'),
atoms: set('false true null'),
operatorChars: /^[*+\-/%<>!=&|^]/,
dateSQL: { },
support: set('ODBCdotTable zerolessFloat doubleQuote commentHash commentSlashSlash')
});
}
export function addEditor(element, columns, initialContent) {
defineBQL();
let options = getConfiguration(columns);
if (!isEmpty(initialContent)) {
options.value = QueryConverter.formatQuery(initialContent);
}
options.mode = MIME;
return CodeMirror(element, options);
}
export function getEditorContent(editor) {
return editor.getValue();
}
export function isEditorClean(editor) {
return editor.isClean();
}
export function markEditorClean(editor) {
return editor.markClean();
}
function getConfiguration(columns) {
return {
lineNumbers: true,
lineWrapping: true,
extraKeys: {
"Ctrl-Space": "autocomplete",
"Tab": "autocomplete"
},
hintOptions: {
defaultTable: 'default',
tables: {
default: columns
}
},
autoCloseBrackets: true,
matchBrackets: true
};
}
|
pnavaro/ElasticFDA.jl
|
deps/src/gropt/incl/dlaeda.h
|
#ifdef __cplusplus
extern "C" {
#endif
#include "f2c.h"
int dlaeda_(integer *n, integer *tlvls, integer *curlvl, integer *curpbm, integer *prmptr, integer *perm, integer *givptr, integer *givcol, doublereal *givnum, doublereal *q, integer *qptr, doublereal *z__, doublereal *ztemp, integer *info);
#ifdef __cplusplus
}
#endif
|
tuhongwei/python-exercise
|
function/decorator.py
|
<reponame>tuhongwei/python-exercise
import functools
def log(*text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args,**kw):
print('begin call')
print('%s %s():' % (text,func.__name__))
return_value = func(*args,**kw)
print('end call')
return return_value
return wrapper
return decorator
@log('excute')
def now():
print('2016-10-31')
now()
print(now.__name__)
|
akiellor/selenium
|
java/client/src/org/openqa/selenium/internal/seleniumemulation/ElementFinder.java
|
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
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.openqa.selenium.internal.seleniumemulation;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import com.thoughtworks.selenium.SeleniumException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import java.util.Map;
public class ElementFinder {
private final String findElement;
private Map<String, String> additionalLocators = Maps.newHashMap();
@VisibleForTesting
protected ElementFinder() {
findElement = null;
}
public ElementFinder(JavascriptLibrary library) {
String rawScript = library.getSeleniumScript("findElement.js");
findElement = "return (" + rawScript + ")(arguments[0]);";
String linkTextLocator = "return (" + library.getSeleniumScript("linkLocator.js") + ").call(null, arguments[0], document)";
add("link", linkTextLocator);
}
public WebElement findElement(WebDriver driver, String locator) {
WebElement toReturn = null;
String strategy = searchAdditionalStrategies(locator);
if (strategy != null) {
String actualLocator = locator.substring(locator.indexOf('=') + 1);
// TODO(simon): Recurse into child documents
try {
toReturn = (WebElement) ((JavascriptExecutor) driver).executeScript(strategy, actualLocator);
if (toReturn == null) {
throw new SeleniumException("Element " + locator + " not found");
}
return toReturn;
} catch (WebDriverException e) {
throw new SeleniumException("Element " + locator + " not found");
}
}
try {
toReturn = findElementDirectlyIfNecessary(driver, locator);
if (toReturn != null) {
return toReturn;
}
return (WebElement) ((JavascriptExecutor) driver)
.executeScript(findElement, locator);
} catch (WebDriverException e) {
throw new SeleniumException("Element " + locator + " not found", e);
}
}
public void add(String strategyName, String implementation) {
additionalLocators.put(strategyName, implementation);
}
private String searchAdditionalStrategies(String locator) {
int index = locator.indexOf('=');
if (index == -1) {
return null;
}
String key = locator.substring(0, index);
return additionalLocators.get(key);
}
private WebElement findElementDirectlyIfNecessary(WebDriver driver, String locator) {
if (locator.startsWith("xpath=")) {
return driver.findElement(By.xpath(locator.substring("xpath=".length())));
}
if (locator.startsWith("//")) {
return driver.findElement(By.xpath(locator));
}
if (locator.startsWith("css=")) {
return driver.findElement(By.cssSelector(locator.substring("css=".length())));
}
return null;
}
}
|
wlhcode/lscct
|
src/U/U06311.cpp
|
<filename>src/U/U06311.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,sigma=0;
cin>>n;
for(int i=1;i*i<=n;i++){
if(n%i==0){
sigma+=i;
if(n/i!=i) sigma+=n/i;
}
}
cout<<sigma<<endl;
}
|
timwillett4/FunctionalPlus
|
include/fplus/result.hpp
|
// Copyright 2015, <NAME> and the FunctionalPlus contributors.
// https://github.com/Dobiasd/FunctionalPlus
// 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)
#pragma once
#include <fplus/function_traits.hpp>
#include <fplus/maybe.hpp>
#include <fplus/internal/asserts/functions.hpp>
#include <fplus/internal/composition.hpp>
#include <fplus/internal/invoke.hpp>
#include <cassert>
#include <functional>
#include <memory>
namespace fplus
{
template <typename Ok, typename Error>
class result;
template <typename Ok, typename Error>
result<Ok, Error> ok(const Ok& val);
template <typename Ok, typename Error>
result<Ok, Error> error(const Error& error);
// Can hold a value of type Ok or an error of type Error.
template <typename Ok, typename Error>
class result
{
public:
bool is_ok() const { return static_cast<bool>(ptr_ok_); }
bool is_error() const { return static_cast<bool>(ptr_error_); }
const Ok& unsafe_get_ok() const {
check_either_or_invariant(); assert(is_ok()); return *ptr_ok_;
}
const Error& unsafe_get_error() const {
check_either_or_invariant(); assert(is_error()); return *ptr_error_;
}
typedef Ok ok_t;
typedef Error error_t;
result(const result<Ok, Error>& other) :
ptr_ok_(other.is_ok() ? ptr_ok(new Ok(other.unsafe_get_ok())) : ptr_ok()),
ptr_error_(other.is_error() ? ptr_error(new Error(other.unsafe_get_error())) : ptr_error())
{
check_either_or_invariant();
}
result<Ok, Error>& operator = (const result<Ok, Error>& other)
{
ptr_ok_ = other.is_ok() ? ptr_ok(new Ok(other.unsafe_get_ok())) : ptr_ok();
ptr_error_ = other.is_error() ? ptr_error(new Error(other.unsafe_get_error())) : ptr_error();
return *this;
}
private:
void check_either_or_invariant() const
{
assert(is_ok() != is_error());
}
result() : ptr_ok_(ptr_ok()), ptr_error_(ptr_error()) {}
typedef std::unique_ptr<Ok> ptr_ok;
typedef std::unique_ptr<Error> ptr_error;
friend result<Ok, Error> ok<Ok, Error>(const Ok& ok);
friend result<Ok, Error> error<Ok, Error>(const Error& error);
ptr_ok ptr_ok_;
ptr_error ptr_error_;
};
// API search type: is_ok : Result a b -> Bool
// fwd bind count: 0
// Is not error?
template <typename Ok, typename Error>
bool is_ok(const result<Ok, Error>& result)
{
return result.is_ok();
}
// API search type: is_error : Result a b -> Bool
// fwd bind count: 0
// Is not OK?
template <typename Ok, typename Error>
bool is_error(const result<Ok, Error>& result)
{
return !is_ok(result);
}
// API search type: unsafe_get_ok : Result a b -> a
// fwd bind count: 0
// Crashes if result is error!
template <typename Ok, typename Error>
Ok unsafe_get_ok(const result<Ok, Error>& result)
{
return result.unsafe_get_ok();
}
// API search type: unsafe_get_error : Result a b -> b
// fwd bind count: 0
// Crashes if result is ok!
template <typename Ok, typename Error>
Error unsafe_get_error(const result<Ok, Error>& result)
{
return result.unsafe_get_error();
}
// API search type: ok_with_default : (a, Result a b) -> a
// fwd bind count: 1
// Get the value from a result or the default in case it is error.
template <typename Ok, typename Error>
Ok ok_with_default(const Ok& defaultValue, const result<Ok, Error>& result)
{
if (is_ok(result))
return unsafe_get_ok(result);
return defaultValue;
}
// API search type: ok : a -> Result a b
// fwd bind count: 0
// Wrap a value in a result as a Ok.
template <typename Ok, typename Error>
result<Ok, Error> ok(const Ok& val)
{
result<Ok, Error> x;
x.ptr_ok_.reset(new Ok(val));
return x;
}
// API search type: error : b -> Result a b
// fwd bind count: 0
// Construct an error of a certain result type.
template <typename Ok, typename Error>
result<Ok, Error> error(const Error& error)
{
result<Ok, Error> x;
x.ptr_error_.reset(new Error(error));
return x;
}
// API search type: to_maybe : Result a b -> Maybe a
// fwd bind count: 0
// Convert ok to just, error to nothing.
template <typename Ok, typename Error>
maybe<Ok> to_maybe(const result<Ok, Error>& result)
{
if (is_ok(result))
return just<Ok>(unsafe_get_ok(result));
else
return nothing<Ok>();
}
// API search type: from_maybe : (b, Maybe a) -> Result a b
// fwd bind count: 1
// Convert just to ok, nothing to error.
template <typename Error, typename Ok>
result<Ok, Error> from_maybe(const Error& err, const maybe<Ok>& maybe)
{
if (is_just(maybe))
return ok<Ok, Error>(unsafe_get_just(maybe));
else
return error<Ok, Error>(err);
}
// API search type: throw_on_error : (e, Result a b) -> a
// fwd bind count: 1
// Throws the given exception in case of error.
// Return ok value if ok.
template <typename E, typename Ok, typename Error>
Ok throw_on_error(const E& e, const result<Ok, Error>& result)
{
if (is_error(result))
throw e;
return unsafe_get_ok(result);
}
// API search type: throw_type_on_error : Result a b -> a
// Throws the given exception type constructed with error value if error.
// Return ok value if ok.
template <typename E, typename Ok, typename Error>
Ok throw_type_on_error(const result<Ok, Error>& result)
{
if (is_error(result))
throw E(unsafe_get_error(result));
return unsafe_get_ok(result);
}
// True if ok values are the same or if errors are the same.
template <typename Ok, typename Error>
bool operator == (const result<Ok, Error>& x, const result<Ok, Error>& y)
{
if (is_ok(x) && is_ok(y))
return unsafe_get_ok(x) == unsafe_get_ok(y);
if (is_error(x) && is_error(y))
return unsafe_get_error(x) == unsafe_get_error(y);
return false;
}
// False if ok values are the same or if both errors are the same.
template <typename Ok, typename Error>
bool operator != (const result<Ok, Error>& x, const result<Ok, Error>& y)
{
return !(x == y);
}
// API search type: lift_result : ((a -> b), Result a c) -> Result b c
// fwd bind count: 1
// Lifts a function into the result functor.
// A function that for example was able to convert and int into a string,
// now can convert a result<int, Err> into a result<string, Err>.
// An error stays the same error, regardless of the conversion.
template <typename Error, typename F, typename A>
auto lift_result(F f, const result<A, Error>& r)
{
internal::trigger_static_asserts<internal::unary_function_tag, F, A>();
using B = std::decay_t<internal::invoke_result_t<F, A>>;
if (is_ok(r))
return ok<B, Error>(internal::invoke(f, unsafe_get_ok(r)));
return error<B, Error>(unsafe_get_error(r));
}
// API search type: lift_result_both : ((a -> c), (b -> d), Result a b) -> Result c d
// fwd bind count: 2
// Lifts two functions into the result functor.
template <typename F, typename G, typename A, typename B>
auto lift_result_both(F f, G g, const result<A, B>& r)
{
internal::trigger_static_asserts<internal::unary_function_tag, F, A>();
internal::trigger_static_asserts<internal::unary_function_tag, G, B>();
using C = std::decay_t<internal::invoke_result_t<F, A>>;
using D = std::decay_t<internal::invoke_result_t<G, B>>;
if (is_ok(r))
return ok<C, D>(internal::invoke(f, unsafe_get_ok(r)));
return error<C, D>(internal::invoke(g, unsafe_get_error(r)));
}
// API search type: unify_result : ((a -> c), (b -> c), Result a b) -> c
// fwd bind count: 2
// Extracts the value (Ok or Error) from a Result
// as defined by the two given functions.
template <typename F, typename G, typename A, typename B>
auto unify_result(F f, G g, const result<A, B>& r)
{
internal::trigger_static_asserts<internal::unary_function_tag, F, A>();
internal::trigger_static_asserts<internal::unary_function_tag, G, B>();
static_assert(std::is_same<internal::invoke_result_t<F, A>,
internal::invoke_result_t<G, B>>::value,
"Both functions must return the same type.");
if (is_ok(r))
return internal::invoke(f, unsafe_get_ok(r));
return internal::invoke(g, unsafe_get_error(r));
}
// API search type: join_result : Result (Result a b) b -> Result a b
// Flattens a nested result.
// join_result(Ok Ok x) == Ok x
// join_result(Ok Error e) == Error e
// join_result(Error e) == Error e
template <typename OK, typename Error>
result<OK, Error> join_result(const result<result<OK, Error>, Error>& r)
{
if (is_ok(r))
return unsafe_get_ok(r);
else
return error<OK, Error>(r.unsafe_get_error());
}
// API search type: and_then_result : ((a -> Result c b), (Result a b)) -> Result c b
// fwd bind count: 1
// Monadic bind.
// Returns the error if the result is an error.
// Otherwise return the result of applying
// the function to the ok value of the result.
template <typename Ok, typename Error, typename F>
auto and_then_result(F f, const result<Ok, Error>& r)
{
internal::trigger_static_asserts<internal::unary_function_tag, F, Ok>();
using FOut = std::decay_t<internal::invoke_result_t<F, Ok>>;
static_assert(std::is_same<Error, typename FOut::error_t>::value,
"Error type must stay the same.");
if (is_ok(r))
return internal::invoke(f, unsafe_get_ok(r));
else
return error<typename FOut::ok_t, typename FOut::error_t>(r.unsafe_get_error());
}
// @TODO - add tests then commit/submit PR
// API search type: and_then_result : ((a -> b -> Result c d) -> (Result a d) -> (Result b d) -> Result c b
// fwd bind count: 2
// Monadic bind for binary functions.
// Returns the error if any result is an error.
// Otherwise return the result of applying
// the function to the ok values of the result.
template <typename Ok1, typename Ok2, typename Error, typename F>
auto and_then_result2(F f, const result<Ok1, Error>& r1, const result<Ok2, Error>& r2)
{
internal::trigger_static_asserts<internal::binary_function_tag, F, Ok1, Ok2>();
using FOut = std::decay_t<internal::invoke_result_t<F, Ok1, Ok2>>;
static_assert(std::is_same<Error, typename FOut::error_t>::value,
"Error type must stay the same.");
if (is_ok(r1) && is_ok(r2))
return internal::invoke(f, unsafe_get_ok(r1), unsafe_get_ok(r2));
else if(is_error(r1))
return error<typename FOut::ok_t, typename FOut::error_t>(r1.unsafe_get_error());
else
return error<typename FOut::ok_t, typename FOut::error_t>(r2.unsafe_get_error());
}
// API search type: and_then_result : ((a -> b -> c -> Result d e) -> (Result a e) -> (Result b e) -> (Result c e) -> Result d e
// fwd bind count: 3
// Monadic bind for ternary functions.
// Returns the error if any result is an error.
// Otherwise return the result of applying
// the function to the ok values of the result.
template <typename Ok1, typename Ok2, typename Ok3, typename Error, typename F>
auto and_then_result3(F f, const result<Ok1, Error>& r1, const result<Ok2, Error>& r2, const result<Ok3, Error>& r3)
{
internal::trigger_static_asserts<internal::ternary_function_tag, F, Ok1, Ok2, Ok3>();
using FOut = std::decay_t<internal::invoke_result_t<F, Ok1, Ok2, Ok3>>;
static_assert(std::is_same<Error, typename FOut::error_t>::value,
"Error type must stay the same.");
if (is_ok(r1) && is_ok(r2) && is_ok(r3))
return internal::invoke(f, unsafe_get_ok(r1), unsafe_get_ok(r2), unsafe_get_ok(r3));
else if(is_error(r1))
return error<typename FOut::ok_t, typename FOut::error_t>(r1.unsafe_get_error());
else if(is_error(r2))
return error<typename FOut::ok_t, typename FOut::error_t>(r2.unsafe_get_error());
else
return error<typename FOut::ok_t, typename FOut::error_t>(r3.unsafe_get_error());
}
// API search type: compose_result : ((a -> Result b c), (b -> Result d c)) -> (a -> Result d c)
// Left-to-right Kleisli composition of monads.
// It is possible to compose a variadic number of callables.
// The first callable can take a variadic number of parameters.
template <typename... Callables>
auto compose_result(Callables&&... callables)
{
auto bind_result = [](auto f, auto g) {
return [f = std::move(f), g = std::move(g)](auto&&... args)
{
internal::trigger_static_asserts<internal::check_arity_tag,
decltype(f),
decltype(args)...>();
using FOut = std::decay_t<
internal::invoke_result_t<decltype(f), decltype(args)...>>;
internal::trigger_static_asserts<internal::unary_function_tag,
decltype(g),
typename FOut::ok_t>();
using GOut = std::decay_t<
internal::invoke_result_t<decltype(g), typename FOut::ok_t>>;
static_assert(std::is_same<typename FOut::error_t,
typename GOut::error_t>::value,
"Error type must stay the same.");
auto resultB =
internal::invoke(f, std::forward<decltype(args)>(args)...);
if (is_ok(resultB))
return internal::invoke(g, unsafe_get_ok(resultB));
return error<typename GOut::ok_t, typename GOut::error_t>(
unsafe_get_error(resultB));
};
};
return internal::compose_binary_lift(bind_result,
std::forward<Callables>(callables)...);
}
} // namespace fplus
|
LuisBallena/SGSTT_DUPLICATE
|
src/main/java/com/sgstt/dao/impl/ModuloImpl.java
|
<filename>src/main/java/com/sgstt/dao/impl/ModuloImpl.java
package com.sgstt.dao.impl;
import com.sgstt.dao.ModuloDao;
import com.sgstt.entidad.Modulo;
import com.sgstt.hibernate.HibernateConexion;
import com.sgstt.hibernate.HibernateImpl;
import java.io.Serializable;
/**
*
* @author SGSTT
*/
public class ModuloImpl extends HibernateImpl<Modulo,Integer> implements ModuloDao,Serializable{
private static final long serialVersionUID = -8604278535776908487L;
public ModuloImpl(HibernateConexion conexion) {
super(conexion);
}
}
|
Shsl4/CProjects
|
VEngine/VEngine/Source/renderer.c
|
#include <VEngine/Headers/renderer.h>
#include <VEngine/Headers/vector.h>
#include <VEngine/Headers/VEngine.h>
#include <VEngine/Headers/window.h>
SDL_Color White = {255, 255, 255};
int Renderer_getWidth(Renderer *renderer)
{
return renderer->m_width;
}
int Renderer_getHeight(Renderer *renderer)
{
return renderer->m_height;
}
void Renderer_clear(Renderer* renderer)
{
SDL_Renderer* rendererSDL = renderer->m_rendererSDL;
SDL_SetRenderDrawColor(rendererSDL, (Uint8)25, (Uint8)25, (Uint8)25, (Uint8)255);
SDL_RenderClear(rendererSDL);
}
void Renderer_fill(Renderer *renderer, Color color)
{
SDL_Rect rect;
SDL_Renderer* rendererSDL = renderer->m_rendererSDL;
rect.x = 0;
rect.y = 0;
rect.w = renderer->m_width;
rect.h = renderer->m_height;
SDL_SetRenderDrawBlendMode(rendererSDL, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(rendererSDL, (Uint8)color.r, (Uint8)color.g, (Uint8)color.b, (Uint8)color.a);
SDL_RenderFillRect(rendererSDL, &rect);
}
void Renderer_drawPoint(Renderer *renderer, int x, int y, Color color)
{
SDL_Renderer* rendererSDL = renderer->m_rendererSDL;
SDL_SetRenderDrawBlendMode(rendererSDL, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(rendererSDL, (Uint8)color.r, (Uint8)color.g, (Uint8)color.b, (Uint8)color.a);
SDL_RenderDrawLine(rendererSDL, x - 5, y, x + 5, y);
SDL_RenderDrawLine(rendererSDL, x, y - 5, x, y + 5);
}
void Renderer_drawLine(Renderer *renderer, int x1, int y1, int x2, int y2, Color color)
{
SDL_Renderer* rendererSDL = renderer->m_rendererSDL;
SDL_SetRenderDrawBlendMode(rendererSDL, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(rendererSDL, (Uint8)color.r, (Uint8)color.g, (Uint8)color.b, (Uint8)color.a);
SDL_RenderDrawLine(rendererSDL, x1, y1, x2, y2);
}
Color makeColor(int r, int g, int b, int a)
{
Color color;
color.r = (uint8_t)r;
color.g = (uint8_t)g;
color.b = (uint8_t)b;
color.a = (uint8_t)a;
return color;
}
void Renderer_update(Renderer* renderer)
{
SDL_RenderPresent(renderer->m_rendererSDL);
}
int randInRange(int min, int max){
return rand() % ( max - min + 1 ) + min;
}
Color randomColor() {
Color result = { .r = randInRange(100, 255),
.g = randInRange(100, 255),
.b = randInRange(100, 255),
.a = 255};
return result;
}
void drawText(SDL_Renderer* renderer, Vec2 pos, TTF_Font* font, char *text, SDL_Color color, bool freeText) {
SDL_Surface* surfaceMessage = TTF_RenderText_Blended(font, text, color);
SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
SDL_Rect Message_rect = { .x = pos.x, .y = pos.y, .w = strlen(text) * 10.0f, .h = TEXT_DRAW_HEIGHT};
SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
SDL_FreeSurface(surfaceMessage);
SDL_DestroyTexture(Message);
if(freeText){
free(text);
}
}
void drawText_FromEnd(SDL_Renderer *renderer, Vec2 pos, TTF_Font *font, char *text, SDL_Color color, bool freeText) {
SDL_Surface* surfaceMessage = TTF_RenderText_Blended(font, text, color);
SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
SDL_Rect Message_rect = { .x = Renderer_getWidth(getRenderer()) - strlen(text) * 10.0f - pos.x, .y = pos.y, .w = strlen(text) * 10.0f, .h = TEXT_DRAW_HEIGHT};
SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
SDL_FreeSurface(surfaceMessage);
SDL_DestroyTexture(Message);
if(freeText){
free(text);
}
}
|
PdrPaes/C
|
funcaoRecursivaVetor.c
|
<gh_stars>1-10
#include <stdio.h>
#include <stdlib.h>
int soma(int vet[]){
if (vet[]== vet [11]){
return 0;
}else{
return vet[2] +soma(vet[2] - vet[2-1]}
}
int main()
{
int vetor[10];
int i;
srand(time(NULL));
printf("10 posicoes do vetor:\n");
for(i=1;i<=10;i++){
vetor[i] = rand()%11;
printf("[%d]",vetor[i]);
}
}
|
ifestudy/ife-task
|
task33/icepro/js/main.js
|
//所有内容通过square访问
var canvas = $('#canvas');
var square = new square(".command-editor",canvas[0].getContext('2d'),10);
square.rander.start();
// var exec = square.robot.isInCommandList( "tun lef" );
// square.robot.invoke( exec );
// console.log(exec);
var timer;
$("#run").on('click',function(){
var arr = square.robot.run(square.editor.getCode());
console.log(arr);
timer = setInterval(function(){
if(arr.length > 0){
var fn = arr.shift();
fn();
}else{
clearInterval(timer);
}
},1000);
});
|
Qt-Widgets/orion-qt
|
core/OriResult.h
|
#ifndef ORI_RESULT_H
#define ORI_RESULT_H
#include <QString>
namespace Ori {
template <typename TResult> class Result
{
public:
TResult result() const { return _result; }
const QString& error() const { return _error; }
bool ok() const { return _error.isEmpty(); }
static Result fail(const QString& error) { return Result(error); }
static Result ok(TResult result) { return Result(QString(), result); }
private:
Result(const QString& error): _error(error) {}
Result(const QString& error, TResult result): _error(error), _result(result) {}
QString _error;
TResult _result;
};
}
#endif // ORI_RESULT_H
|
karaulyanovsap/scimono
|
scimono-server/src/main/java/com/sap/scimono/entity/bulk/ResponseOperation.java
|
package com.sap.scimono.entity.bulk;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sap.scimono.api.API;
import com.sap.scimono.api.helper.ScimErrorResponseParser;
import com.sap.scimono.entity.ErrorResponse;
import com.sap.scimono.entity.Group;
import com.sap.scimono.entity.User;
import com.sap.scimono.exception.InternalScimonoException;
import com.sap.scimono.exception.InvalidInputException;
import com.sap.scimono.exception.SCIMException;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseOperation extends BulkOperation {
private static final long serialVersionUID = 2729999986283853529L;
private static final String LOCATION_FIELD = "location";
private static final String STATUS_FIELD = "status";
private static final String RESPONSE_FIELD = "response";
private final String location;
private final String status;
private final ErrorResponse response;
private String resourceId;
private String resourceType;
@JsonCreator
private ResponseOperation(@JsonProperty(value = METHOD_FIELD, required = true) final String method,
@JsonProperty(value = BULK_ID_FIELD) final String bulkId,
@JsonProperty(value = LOCATION_FIELD) final String location,
@JsonProperty(VERSION_FIELD) final String version,
@JsonProperty(RESPONSE_FIELD) final ErrorResponse response,
@JsonProperty(value = STATUS_FIELD, required = true) final String status) {
super(method, bulkId, version);
String validatedLocation = getValidatedLocation(getMethod(), response, location);
this.location = getNormalizedLocation(getMethod(), response, validatedLocation);
this.resourceId = extractResourceId(this.location);
this.resourceType = extractResourceType(this.location);
this.status = status;
this.response = response;
}
private ResponseOperation(Builder builder) {
super(builder);
this.location = builder.location;
this.status = builder.status;
this.response = builder.errorResponse;
this.resourceType = builder.resourceType;
this.resourceId = builder.resourceId;
}
public String getLocation() {
return location;
}
public String getStatus() {
return status;
}
public ErrorResponse getResponse() {
return response;
}
@JsonIgnore
public String getResourceId() {
return resourceId;
}
@JsonIgnore
public String getResourceType() {
return resourceType;
}
@JsonIgnore
public boolean isSuccessful() {
return response == null;
}
@JsonIgnore
public Builder builder() {
return new Builder(this);
}
static Builder error(RequestOperation reqOperation, SCIMException scimException) {
ErrorResponse scimError = ScimErrorResponseParser.parseException(scimException);
return error(reqOperation, scimError);
}
static Builder error(RequestOperation reqOperation, ErrorResponse scimError) {
return new Builder().forRequestOperation(reqOperation).withError(scimError).withStatus(scimError.getStatus())
.withLocation(reqOperation.getPath());
}
static Builder success(RequestOperation reqOperation) {
String statusCode = String.valueOf(reqOperation.getMethod().getSuccessfulStatus().getStatusCode());
return new Builder().forRequestOperation(reqOperation).withStatus(statusCode);
}
private String extractResourceId(String normalizedLocation) {
if (normalizedLocation != null) {
String[] pathSegments = normalizedLocation.split("/");
return pathSegments[pathSegments.length - 1];
}
return null;
}
private String extractResourceType(String normalizedLocation) {
if (normalizedLocation != null) {
String[] pathSegments = normalizedLocation.split("/");
String endpoint = pathSegments[pathSegments.length - 2];
if (API.USERS.equalsIgnoreCase(endpoint)) {
return User.RESOURCE_TYPE_USER;
} else if (API.GROUPS.equalsIgnoreCase(endpoint)) {
return Group.RESOURCE_TYPE_GROUP;
}
}
return null;
}
private static String getValidatedLocation(RequestMethod requestMethod, ErrorResponse errorResponse, String initLocation) {
boolean hasErrorResponse = errorResponse != null;
boolean isPostMethod = requestMethod == RequestMethod.POST;
String location = removeEndingSlash(initLocation);
boolean isMissingLocation = location == null;
boolean isLocationMissingFromNonPostMethod = !isPostMethod && isMissingLocation && !hasErrorResponse;
boolean isPostMethodWithError = isPostMethod && hasErrorResponse;
if (isLocationMissingFromNonPostMethod) {
throw new InvalidInputException("Expected resource location for request method: " + requestMethod);
}
if (isPostMethodWithError || isMissingLocation) {
return null;
}
return location;
}
private static String getNormalizedLocation(RequestMethod requestMethod, ErrorResponse errorResponse, String location) {
boolean hasErrorResponse = errorResponse != null;
try {
URL locationUrl = new URL(location);
return locationUrl.toURI().normalize().toASCIIString();
} catch (MalformedURLException | URISyntaxException e) {
if (!hasErrorResponse) {
throw new InternalScimonoException(String.format(
"The resource's location could not be normalized in order to extract the resource type and id. Location is: %s, method is: %s", location,
requestMethod));
}
}
return null;
}
private static String removeEndingSlash(String location) {
if (location != null && location.endsWith("/")) {
location = location.substring(0, location.length() - 1);
}
return location;
}
public static class Builder extends BulkOperation.Builder<ResponseOperation> {
private String status;
private ErrorResponse errorResponse;
private String resourceId;
private String resourceType;
private String location;
private Builder() {
}
private Builder(ResponseOperation operation) {
super(operation);
this.location = operation.location;
this.errorResponse = operation.response;
this.resourceId = operation.resourceId;
this.resourceType = operation.resourceType;
this.status = operation.getStatus();
}
private Builder forRequestOperation(RequestOperation requestOperation) {
super.setBulkId(requestOperation.getBulkId()).setMethod(requestOperation.getMethod());
this.resourceType = requestOperation.getResourceType();
this.resourceId = requestOperation.getResourceId().orElse(null);
return this;
}
private Builder withError(ErrorResponse error) {
this.errorResponse = error;
return this;
}
private Builder withStatus(String status) {
this.status = status;
return this;
}
public Builder withVersion(String version) {
super.setVersion(version);
return this;
}
public Builder withLocation(String location) {
this.location = location;
return this;
}
@Override
public ResponseOperation build() {
return new ResponseOperation(this);
}
}
}
|
myvyang/intellij-community
|
RegExpSupport/src/org/intellij/lang/regexp/psi/RegExpElementVisitor.java
|
<gh_stars>0
/*
* Copyright 2006 <NAME>
*
* 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.intellij.lang.regexp.psi;
import com.intellij.psi.PsiElementVisitor;
import org.intellij.lang.regexp.psi.impl.RegExpOptionsImpl;
public class RegExpElementVisitor extends PsiElementVisitor {
public void visitRegExpElement(RegExpElement element) {
}
public void visitRegExpChar(RegExpChar ch) {
visitRegExpElement(ch);
}
public void visitRegExpCharRange(RegExpCharRange range) {
visitRegExpElement(range);
}
public void visitSimpleClass(RegExpSimpleClass simpleClass) {
visitRegExpElement(simpleClass);
}
public void visitRegExpClass(RegExpClass expClass) {
visitRegExpElement(expClass);
}
public void visitRegExpGroup(RegExpGroup group) {
visitRegExpElement(group);
}
public void visitRegExpOptions(RegExpOptionsImpl options) {
visitRegExpElement(options);
}
public void visitRegExpProperty(RegExpProperty property) {
visitRegExpElement(property);
}
public void visitRegExpBranch(RegExpBranch branch) {
visitRegExpElement(branch);
}
public void visitRegExpPattern(RegExpPattern pattern) {
visitRegExpElement(pattern);
}
public void visitRegExpBackref(RegExpBackref backref) {
visitRegExpElement(backref);
}
public void visitRegExpClosure(RegExpClosure closure) {
visitRegExpElement(closure);
}
public void visitRegExpQuantifier(RegExpQuantifier quantifier) {
visitRegExpElement(quantifier);
}
public void visitRegExpBoundary(RegExpBoundary boundary) {
visitRegExpElement(boundary);
}
public void visitRegExpSetOptions(RegExpSetOptions options) {
visitRegExpElement(options);
}
public void visitRegExpIntersection(RegExpIntersection intersection) {
visitRegExpElement(intersection);
}
public void visitRegExpNamedGroupRef(RegExpNamedGroupRef groupRef) {
visitRegExpElement(groupRef);
}
public void visitRegExpPyCondRef(RegExpPyCondRef condRef) {
visitRegExpElement(condRef);
}
public void visitPosixBracketExpression(RegExpPosixBracketExpression posixBracketExpression) {
visitRegExpElement(posixBracketExpression);
}
}
|
search-cloud/learning-stack
|
learning-algorithm/src/main/java/io/vincent/learning/stack/algorithm/sort/Printer.java
|
package io.vincent.learning.stack.algorithm.sort;
import java.util.List;
/**
* Created by Vincent on 12/6/18.
*
* @author Vincent
* @since 1.0, 12/6/18
*/
public class Printer {
private static final char space = ' ';
private static final char underLine = '_';
private static final char verticalLine = '|';
private static final char backSlash = '\\';
private static final char slash = '/';
/**
* Print List.
*
* @param list list.
* @param <T> type of the element.
*/
static <T extends Comparable<T>> void printList(List<T> list) {
String listString = getListString(list);
System.out.println(listString);
}
private static <T extends Comparable<T>> String getListString(List<T> list) {
StringBuilder sb = new StringBuilder();
for (T t : list) {
sb.append(verticalLine);
sb.append(t);
}
sb.append(verticalLine);
return sb.toString();
}
static <T extends Comparable<T>> void printBubbleSortBalancer(List<T> list, int i, int j) {
int total = (list.size() * 2) + 1 - 4;
int iNumbers = (i * 2) + 1 - 4;
int jNumbers = (j * 2) + 1 - 4;
int underLineNumbers = jNumbers + 1 - iNumbers - 2;
int spaceNumbers = total - jNumbers - 2;
printSeparator(verticalLine, 1);
printSeparator(space, i * 2);
printSeparator(backSlash, 1);
printSeparator(underLine, underLineNumbers);
printSeparator(slash, 1);
printSeparator(space, spaceNumbers);
printSeparator(verticalLine, 1);
System.out.println();
}
static <T extends Comparable<T>> void printInsertionSortAnimation(List<T> list, T current, int j, int bakJ) {
String listString = getListString(list);
System.out.println(listString);
int jNumbers = (j * 2) + 1;
int bjNumbers = (bakJ * 2) + 1;
printSeparator(space, jNumbers + 2);
printSeparator(current, 1);
printSeparator('<', bjNumbers - jNumbers);
}
private static <D> void printSeparator(D separator, int numbers) {
for (int i = 0; i < numbers; i++) {
System.out.print(separator);
}
}
}
|
josephwinston/j2objc
|
jre_emul/android/libcore/luni/src/test/java/libcore/java/lang/reflect/MethodTest.java
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libcore.java.lang.reflect;
import java.lang.reflect.Method;
import junit.framework.TestCase;
public final class MethodTest extends TestCase {
// Check that the VM gives useful detail messages.
public void test_invokeExceptions() throws Exception {
Method m = String.class.getMethod("charAt", int.class);
try {
m.invoke("hello"); // Wrong number of arguments.
fail();
} catch (IllegalArgumentException iae) {
assertEquals("wrong number of arguments; expected 1, got 0", iae.getMessage());
}
try {
m.invoke("hello", "world"); // Wrong type.
fail();
} catch (IllegalArgumentException iae) {
assertEquals("argument 1 should have type int, got java.lang.String", iae.getMessage());
}
try {
m.invoke("hello", (Object) null); // Null for a primitive argument.
fail();
} catch (IllegalArgumentException iae) {
assertEquals("argument 1 should have type int, got null", iae.getMessage());
}
try {
m.invoke(new Integer(5)); // Wrong type for 'this'.
fail();
} catch (IllegalArgumentException iae) {
assertEquals("expected receiver of type java.lang.String, but got java.lang.Integer", iae.getMessage());
}
try {
m.invoke(null); // Null for 'this'.
fail();
} catch (NullPointerException npe) {
assertEquals("expected receiver of type java.lang.String, but got null",
npe.getMessage());
}
}
public void test_getExceptionTypes() throws Exception {
Method method = MethodTestHelper.class.getMethod("m1", new Class[0]);
Class[] exceptions = method.getExceptionTypes();
assertEquals(1, exceptions.length);
assertEquals(IndexOutOfBoundsException.class, exceptions[0]);
// Check that corrupting our array doesn't affect other callers.
exceptions[0] = NullPointerException.class;
exceptions = method.getExceptionTypes();
assertEquals(1, exceptions.length);
assertEquals(IndexOutOfBoundsException.class, exceptions[0]);
}
public void test_getParameterTypes() throws Exception {
Class[] expectedParameters = new Class[] { Object.class };
Method method = MethodTestHelper.class.getMethod("m2", expectedParameters);
Class[] parameters = method.getParameterTypes();
assertEquals(1, parameters.length);
assertEquals(expectedParameters[0], parameters[0]);
// Check that corrupting our array doesn't affect other callers.
parameters[0] = String.class;
parameters = method.getParameterTypes();
assertEquals(1, parameters.length);
assertEquals(expectedParameters[0], parameters[0]);
}
public void testGetMethodWithPrivateMethodAndInterfaceMethod() throws Exception {
assertEquals(InterfaceA.class, Sub.class.getMethod("a").getDeclaringClass());
}
public void testGetMethodReturnsIndirectlyImplementedInterface() throws Exception {
assertEquals(InterfaceA.class, ImplementsC.class.getMethod("a").getDeclaringClass());
assertEquals(InterfaceA.class, ExtendsImplementsC.class.getMethod("a").getDeclaringClass());
}
public void testGetDeclaredMethodReturnsIndirectlyImplementedInterface() throws Exception {
try {
ImplementsC.class.getDeclaredMethod("a").getDeclaringClass();
fail();
} catch (NoSuchMethodException expected) {
}
try {
ExtendsImplementsC.class.getDeclaredMethod("a").getDeclaringClass();
fail();
} catch (NoSuchMethodException expected) {
}
}
public void testGetMethodWithConstructorName() throws Exception {
try {
MethodTestHelper.class.getMethod("<init>");
fail();
} catch (NoSuchMethodException expected) {
}
}
public void testGetMethodWithNullName() throws Exception {
try {
MethodTestHelper.class.getMethod(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testGetMethodWithNullArgumentsArray() throws Exception {
Method m1 = MethodTestHelper.class.getMethod("m1", (Class[]) null);
assertEquals(0, m1.getParameterTypes().length);
}
public void testGetMethodWithNullArgument() throws Exception {
try {
MethodTestHelper.class.getMethod("m2", new Class[] { null });
fail();
} catch (NoSuchMethodException expected) {
}
}
public void testGetMethodReturnsInheritedStaticMethod() throws Exception {
Method b = Sub.class.getMethod("b");
assertEquals(void.class, b.getReturnType());
}
public void testGetDeclaredMethodReturnsPrivateMethods() throws Exception {
Method method = Super.class.getDeclaredMethod("a");
assertEquals(void.class, method.getReturnType());
}
public void testGetDeclaredMethodDoesNotReturnSuperclassMethods() throws Exception {
try {
Sub.class.getDeclaredMethod("a");
fail();
} catch (NoSuchMethodException expected) {
}
}
public void testGetDeclaredMethodDoesNotReturnImplementedInterfaceMethods() throws Exception {
try {
InterfaceB.class.getDeclaredMethod("a");
fail();
} catch (NoSuchMethodException expected) {
}
}
public void testImplementedInterfaceMethodOfAnonymousClass() throws Exception {
Object anonymous = new InterfaceA() {
@Override public void a() {
}
};
Method method = anonymous.getClass().getMethod("a");
assertEquals(anonymous.getClass(), method.getDeclaringClass());
}
public void testPublicMethodOfAnonymousClass() throws Exception {
Object anonymous = new Object() {
public void a() {
}
};
Method method = anonymous.getClass().getMethod("a");
assertEquals(anonymous.getClass(), method.getDeclaringClass());
}
public void testGetMethodDoesNotReturnPrivateMethodOfAnonymousClass() throws Exception {
Object anonymous = new Object() {
private void a() {
}
};
try {
anonymous.getClass().getMethod("a");
fail();
} catch (NoSuchMethodException expected) {
}
}
public void testGetDeclaredMethodReturnsPrivateMethodOfAnonymousClass() throws Exception {
Object anonymous = new Object() {
private void a() {
}
};
Method method = anonymous.getClass().getDeclaredMethod("a");
assertEquals(anonymous.getClass(), method.getDeclaringClass());
}
// iOS: toString returns may be different than in Java.
// public void testMethodToString() throws Exception {
// assertEquals("public final native void java.lang.Object.clone()",
// Object.class.getMethod("clone", new Class[] { }).toString());
// assertEquals("public java.lang.String java.lang.Object.toString()",
// Object.class.getMethod("toString", new Class[] { }).toString());
// assertEquals("public final native void java.lang.Object.wait(long,int)"
// + " throws java.lang.InterruptedException",
// Object.class.getMethod("wait", new Class[] { long.class, int.class }).toString());
// assertEquals("public boolean java.lang.Object.equals(java.lang.Object)",
// Object.class.getMethod("equals", new Class[] { Object.class }).toString());
// assertEquals("public static java.lang.String java.lang.String.valueOf(char[])",
// String.class.getMethod("valueOf", new Class[] { char[].class }).toString());
// assertEquals( "public java.lang.Process java.lang.Runtime.exec(java.lang.String[])"
// + " throws java.io.IOException",
// Runtime.class.getMethod("exec", new Class[] { String[].class }).toString());
// }
public static class MethodTestHelper {
public void m1() throws IndexOutOfBoundsException { }
public void m2(Object o) { }
}
public static class Super {
private void a() {}
public static void b() {}
}
public static interface InterfaceA {
void a();
}
public static abstract class Sub extends Super implements InterfaceA {
}
public static interface InterfaceB extends InterfaceA {}
public static interface InterfaceC extends InterfaceB {}
public static abstract class ImplementsC implements InterfaceC {}
public static abstract class ExtendsImplementsC extends ImplementsC {}
}
|
ColFusion/PentahoKettle
|
CarteService/default/src/main/java/jnacontrib/jna/WINNT.java
|
<filename>CarteService/default/src/main/java/jnacontrib/jna/WINNT.java<gh_stars>0
/*
* WINNT.java
*
* Created on 8. August 2007, 13:41
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package jnacontrib.jna;
/**
*
* @author TB
*/
public interface WINNT
{
public final static int DELETE = 0x00010000;
public final static int READ_CONTROL = 0x00020000;
public final static int WRITE_DAC = 0x00040000;
public final static int WRITE_OWNER = 0x00080000;
public final static int SYNCHRONIZE = 0x00100000;
public final static int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
public final static int STANDARD_RIGHTS_READ = READ_CONTROL;
public final static int STANDARD_RIGHTS_WRITE = READ_CONTROL;
public final static int STANDARD_RIGHTS_EXECUTE = READ_CONTROL;
public final static int STANDARD_RIGHTS_ALL = 0x001F0000;
public final static int SPECIFIC_RIGHTS_ALL = 0x0000FFFF;
public final static int GENERIC_EXECUTE = 0x20000000;
public final static int SERVICE_WIN32_OWN_PROCESS = 0x00000010;
public final static int KEY_QUERY_VALUE = 0x0001;
public final static int KEY_SET_VALUE = 0x0002;
public final static int KEY_CREATE_SUB_KEY = 0x0004;
public final static int KEY_ENUMERATE_SUB_KEYS = 0x0008;
public final static int KEY_NOTIFY = 0x0010;
public final static int KEY_CREATE_LINK = 0x0020;
public final static int KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & (~SYNCHRONIZE));
public final static int KEY_WRITE = ((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (~SYNCHRONIZE));
public final static int REG_NONE = 0; // No
// value
// type
public final static int REG_SZ = 1; // Unicode
// nul
// terminated
// string
public final static int REG_EXPAND_SZ = 2; // Unicode
// nul
// terminated
// string
// (with environment variable references)
public final static int REG_BINARY = 3; // Free
// form
// binary
public final static int REG_DWORD = 4; // 32-bit
// number
public final static int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit
// number
// (same
// as
// REG_DWORD)
public final static int REG_DWORD_BIG_ENDIAN = 5; // 32-bit
// number
public final static int REG_LINK = 6; // Symbolic
// Link
// (unicode)
public final static int REG_MULTI_SZ = 7; // Multiple
// Unicode
// strings
public final static int REG_RESOURCE_LIST = 8; // Resource
// list
// in
// the
// resource
// map
public final static int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource
// list
// in
// the
// hardware
// description
public final static int REG_RESOURCE_REQUIREMENTS_LIST = 10;
public final static int REG_OPTION_RESERVED = 0x00000000; // Parameter
// is
// reserved
public final static int REG_OPTION_NON_VOLATILE = 0x00000000; // Key
// is
// preserved
// when system is rebooted
public final static int REG_OPTION_VOLATILE = 0x00000001; // Key
// is
// not
// preserved
// when system is rebooted
public final static int REG_OPTION_CREATE_LINK = 0x00000002; // Created
// key
// is
// a
// symbolic link
public final static int REG_OPTION_BACKUP_RESTORE = 0x00000004; // open
// for
// backup
// or
// restore
// special access rules
// privilege required
public final static int REG_OPTION_OPEN_LINK = 0x00000008; // Open
// symbolic
// link
/*
* YAJSW additions start here
*/
public final static int GENERIC_READ = 0x80000000;
}
|
Knowledge-Precipitation-Tribe/Distributed-fileserver
|
service/account/main.go
|
<reponame>Knowledge-Precipitation-Tribe/Distributed-fileserver
package main
import (
"Distributed-fileserver/service/account/customLog"
"go.uber.org/zap"
"time"
"github.com/micro/go-micro"
_ "github.com/micro/go-plugins/registry/consul"
_ "github.com/micro/go-plugins/registry/kubernetes"
// k8s "github.com/micro/kubernetes/go/micro"
"Distributed-fileserver/common"
"Distributed-fileserver/service/account/handler"
proto "Distributed-fileserver/service/account/proto"
dbproxy "Distributed-fileserver/service/dbproxy/client"
)
func main() {
service := micro.NewService(
// service := k8s.NewService(
micro.Name("go.micro.service.user"),
micro.RegisterTTL(time.Second*10),
micro.RegisterInterval(time.Second*5),
micro.Flags(common.CustomFlags...),
)
// 初始化service, 解析命令行参数等
service.Init()
// 初始化dbproxy client
dbproxy.Init(service)
proto.RegisterUserServiceHandler(service.Server(), new(handler.User))
if err := service.Run(); err != nil {
customLog.Logger.Error("account main service run失败", zap.Error(err))
}
}
|
zealoussnow/chromium
|
chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/pseudotab/PseudoTab.java
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tasks.pseudotab;
import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.Log;
import org.chromium.base.StreamUtil;
import org.chromium.chrome.browser.flags.CachedFeatureFlags;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.state.CriticalPersistedTabData;
import org.chromium.chrome.browser.tabmodel.TabList;
import org.chromium.chrome.browser.tabmodel.TabModelFilter;
import org.chromium.chrome.browser.tabmodel.TabModelFilterProvider;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabPersistentStore;
import org.chromium.chrome.browser.tabmodel.TabbedModeTabPersistencePolicy;
import org.chromium.chrome.browser.tabpersistence.TabStateDirectory;
import org.chromium.chrome.browser.tasks.tab_management.TabUiFeatureUtilities;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.url.GURL;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.concurrent.GuardedBy;
/**
* Representation of a Tab-like card in the Grid Tab Switcher.
*/
public class PseudoTab {
private static final String TAG = "PseudoTab";
private final Integer mTabId;
private final WeakReference<Tab> mTab;
@GuardedBy("sLock")
private static final Map<Integer, PseudoTab> sAllTabs = new LinkedHashMap<>();
private static final Object sLock = new Object();
private static boolean sReadStateFile;
private static List<PseudoTab> sAllTabsFromStateFile;
private static PseudoTab sActiveTabFromStateFile;
/**
* An interface to get the title to be used for a tab.
*/
public interface TitleProvider {
String getTitle(Context context, PseudoTab tab);
}
/**
* Construct from a tab ID. An earlier instance with the same ID can be returned.
*/
public static PseudoTab fromTabId(int tabId) {
synchronized (sLock) {
PseudoTab cached = sAllTabs.get(tabId);
if (cached != null) return cached;
return new PseudoTab(tabId);
}
}
private PseudoTab(int tabId) {
mTabId = tabId;
mTab = null;
sAllTabs.put(getId(), this);
}
/**
* Construct from a {@link Tab}. An earlier instance with the same {@link Tab} can be returned.
*/
public static PseudoTab fromTab(@NonNull Tab tab) {
synchronized (sLock) {
PseudoTab cached = sAllTabs.get(tab.getId());
if (cached != null && cached.hasRealTab()) {
if (cached.getTab() == tab) {
return cached;
} else {
assert tab.getWebContents() == null || cached.getTab().getWebContents() == null
|| cached.getTab().getWebContents().getTopLevelNativeWindow() == null;
return new PseudoTab(tab);
}
}
// We need to upgrade a pre-native Tab to a post-native Tab.
return new PseudoTab(tab);
}
}
private PseudoTab(@NonNull Tab tab) {
mTabId = tab.getId();
mTab = new WeakReference<>(tab);
sAllTabs.put(getId(), this);
}
/**
* Convert a list of {@link Tab} to a list of {@link PseudoTab}.
* @param tabs A list of {@link Tab}
* @return A list of {@link PseudoTab}
*/
public static List<PseudoTab> getListOfPseudoTab(@Nullable List<Tab> tabs) {
List<PseudoTab> pseudoTabs = null;
if (tabs != null) {
pseudoTabs = new ArrayList<>();
for (Tab tab : tabs) {
pseudoTabs.add(fromTab(tab));
}
}
return pseudoTabs;
}
/**
* Convert a {@link TabList} to a list of {@link PseudoTab}.
* @param tabList A {@link TabList}
* @return A list of {@link PseudoTab}
*/
public static List<PseudoTab> getListOfPseudoTab(@Nullable TabList tabList) {
List<PseudoTab> pseudoTabs = null;
if (tabList != null) {
pseudoTabs = new ArrayList<>();
for (int i = 0; i < tabList.getCount(); i++) {
pseudoTabs.add(fromTab(tabList.getTabAt(i)));
}
}
return pseudoTabs;
}
@Override
public String toString() {
assert mTabId != null;
return "Tab " + mTabId;
}
/**
* @return The ID of the {@link PseudoTab}
*/
public int getId() {
return mTabId;
}
/**
* Get the title of the {@link PseudoTab} through a {@link TitleProvider}.
*
* If the {@link TitleProvider} is {@code null}, fall back to {@link #getTitle()}.
*
* @param context The activity context.
* @param titleProvider The {@link TitleProvider} to provide the title.
* @return The title
*/
public String getTitle(Context context, @Nullable TitleProvider titleProvider) {
if (titleProvider != null) return titleProvider.getTitle(context, this);
return getTitle();
}
/**
* Get the title of the {@link PseudoTab}.
* @return The title
*/
public String getTitle() {
if (mTab != null && mTab.get() != null && mTab.get().isInitialized()) {
return mTab.get().getTitle();
}
assert mTabId != null;
return TabAttributeCache.getTitle(mTabId);
}
/**
* Get the URL of the {@link PseudoTab}.
* @return The URL
*/
public GURL getUrl() {
if (mTab != null && mTab.get() != null && mTab.get().isInitialized()) {
return mTab.get().getUrl();
}
assert mTabId != null;
return TabAttributeCache.getUrl(mTabId);
}
/**
* Get the root ID of the {@link PseudoTab}.
* @return The root ID
*/
public int getRootId() {
if (mTab != null && mTab.get() != null && mTab.get().isInitialized()) {
return CriticalPersistedTabData.from(mTab.get()).getRootId();
}
assert mTabId != null;
return TabAttributeCache.getRootId(mTabId);
}
/**
* @return The timestamp of the {@link PseudoTab}.
*/
public long getTimestampMillis() {
if (mTab != null && mTab.get() != null && mTab.get().isInitialized()) {
return CriticalPersistedTabData.from(mTab.get()).getTimestampMillis();
}
assert mTabId != null;
return TabAttributeCache.getTimestampMillis(mTabId);
}
/**
* @return Whether the {@link PseudoTab} is in the Incognito mode.
*/
public boolean isIncognito() {
if (mTab != null && mTab.get() != null) return mTab.get().isIncognito();
assert mTabId != null;
return false;
}
/**
* @return Whether an underlying real {@link Tab} is available.
*/
public boolean hasRealTab() {
return getTab() != null;
}
/**
* Get the underlying real {@link Tab}. We should avoid using this.
* @return The underlying real {@link Tab}.
*/
@Deprecated
public @Nullable Tab getTab() {
if (mTab != null) return mTab.get();
return null;
}
/**
* Clear the internal static storage as if the app is restarted.
* This should/can be called when emulating restarting in instrumented tests, or between
* Robolectric tests.
*/
@VisibleForTesting
public static void clearForTesting() {
synchronized (sLock) {
sAllTabs.clear();
sReadStateFile = false;
sActiveTabFromStateFile = null;
if (sAllTabsFromStateFile != null) {
sAllTabsFromStateFile.clear();
}
}
}
/**
* Get related tabs of a certain {@link PseudoTab}, through {@link TabModelFilter}s if
* available.
*
* @param context The activity context.
* @param member The {@link PseudoTab} related to
* @param tabModelSelector The {@link TabModelSelector} to query the tab relation
* @return Related {@link PseudoTab}s
*/
public static @NonNull List<PseudoTab> getRelatedTabs(
Context context, PseudoTab member, @NonNull TabModelSelector tabModelSelector) {
synchronized (sLock) {
List<Tab> relatedTabs = getRelatedTabList(tabModelSelector, member.getId());
if (relatedTabs != null) return getListOfPseudoTab(relatedTabs);
List<PseudoTab> related = new ArrayList<>();
int rootId = member.getRootId();
if (rootId == Tab.INVALID_TAB_ID
|| !TabUiFeatureUtilities.isTabGroupsAndroidEnabled(context)) {
related.add(member);
return related;
}
for (Integer key : sAllTabs.keySet()) {
PseudoTab tab = sAllTabs.get(key);
assert tab != null;
if (tab.getRootId() == Tab.INVALID_TAB_ID) continue;
if (tab.getRootId() != rootId) continue;
related.add(tab);
}
assert related.size() > 0;
return related;
}
}
private static @Nullable List<Tab> getRelatedTabList(
@NonNull TabModelSelector tabModelSelector, int tabId) {
if (!tabModelSelector.isTabStateInitialized()) {
assert CachedFeatureFlags.isEnabled(ChromeFeatureList.INSTANT_START);
return null;
}
TabModelFilterProvider provider = tabModelSelector.getTabModelFilterProvider();
List<Tab> related = provider.getTabModelFilter(false).getRelatedTabList(tabId);
if (related.size() > 0) return related;
related = provider.getTabModelFilter(true).getRelatedTabList(tabId);
assert related.size() > 0;
return related;
}
@VisibleForTesting
static int getAllTabsCountForTests() {
synchronized (sLock) {
return sAllTabs.size();
}
}
/**
* @param context The activity context.
*/
@Nullable
public static List<PseudoTab> getAllPseudoTabsFromStateFile(Context context) {
readAllPseudoTabsFromStateFile(context);
return sAllTabsFromStateFile;
}
@Nullable
public static PseudoTab getActiveTabFromStateFile(Context context) {
readAllPseudoTabsFromStateFile(context);
return sActiveTabFromStateFile;
}
private static void readAllPseudoTabsFromStateFile(Context context) {
assert CachedFeatureFlags.isEnabled(ChromeFeatureList.INSTANT_START)
|| CachedFeatureFlags.isEnabled(ChromeFeatureList.PAINT_PREVIEW_SHOW_ON_STARTUP);
if (sReadStateFile) return;
sReadStateFile = true;
long startMs = SystemClock.elapsedRealtime();
File stateFile = new File(TabStateDirectory.getOrCreateTabbedModeStateDirectory(),
TabbedModeTabPersistencePolicy.getStateFileName(0));
if (!stateFile.exists()) {
Log.i(TAG, "State file does not exist.");
return;
}
FileInputStream stream = null;
byte[] data;
try {
stream = new FileInputStream(stateFile);
data = new byte[(int) stateFile.length()];
stream.read(data);
} catch (IOException exception) {
Log.e(TAG, "Could not read state file.", exception);
return;
} finally {
StreamUtil.closeQuietly(stream);
}
Log.i(TAG, "Finished fetching tab list.");
DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(data));
Set<Integer> seenRootId = new HashSet<>();
sAllTabsFromStateFile = new ArrayList<>();
try {
TabPersistentStore.readSavedStateFile(dataStream,
(index, id, url, isIncognito, isStandardActiveIndex, isIncognitoActiveIndex)
-> {
// Skip restoring of non-selected NTP to match the real restoration logic.
if (UrlUtilities.isCanonicalizedNTPUrl(url) && !isStandardActiveIndex) {
return;
} else if (TextUtils.isEmpty(url)) {
// Skip restoring of empty Tabs.
return;
}
PseudoTab tab = PseudoTab.fromTabId(id);
if (isStandardActiveIndex) {
assert sActiveTabFromStateFile == null;
sActiveTabFromStateFile = tab;
}
int rootId = tab.getRootId();
if (TabUiFeatureUtilities.isTabGroupsAndroidEnabled(context)
&& seenRootId.contains(rootId)) {
return;
}
sAllTabsFromStateFile.add(tab);
seenRootId.add(rootId);
},
null);
} catch (IOException exception) {
Log.e(TAG, "Could not read state file.", exception);
return;
}
Log.d(TAG, "All pre-native tabs: " + sAllTabsFromStateFile);
Log.i(TAG, "readAllPseudoTabsFromStateFile() took %dms",
SystemClock.elapsedRealtime() - startMs);
}
}
|
keller-mark/vitessce
|
src/layers/heatmap-constants.js
|
import GL from '@luma.gl/constants';
export const TILE_SIZE = 2048;
export const MIN_ROW_AGG = 1;
export const MAX_ROW_AGG = 16;
export const COLOR_BAR_SIZE = 20;
export const AXIS_LABEL_TEXT_SIZE = 9;
export const AXIS_TITLE_TEXT_SIZE = 15;
export const AXIS_MIN_SIZE = 10;
export const AXIS_MAX_SIZE = 90;
export const AXIS_MARGIN = 3;
export const THEME_TO_TEXT_COLOR = {
dark: [224, 224, 224],
light: [64, 64, 64],
};
export const AXIS_FONT_FAMILY = "-apple-system, 'Helvetica Neue', Arial, sans-serif";
export const PIXELATED_TEXTURE_PARAMETERS = {
// NEAREST for integer data to prevent interpolation.
[GL.TEXTURE_MIN_FILTER]: GL.NEAREST,
[GL.TEXTURE_MAG_FILTER]: GL.NEAREST,
// CLAMP_TO_EDGE to remove tile artifacts.
[GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE,
[GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE,
};
|
timblechmann/nt2
|
modules/extern/cephes/src/cephes_ldouble/monotl.c
|
<filename>modules/extern/cephes/src/cephes_ldouble/monotl.c
/* monotl.c
Floating point function test vectors.
Arguments and function values are synthesized for NPTS points in
the vicinity of each given tabulated test point. The points are
chosen to be near and on either side of the likely function algorithm
domain boundaries. Since the function programs change their methods
at these points, major coding errors or monotonicity failures might be
detected.
August, 1998
<NAME> */
/* Unit of error tolerance in test[i].thresh. */
static long double MACHEPL =
5.42101086242752217003726400434970855712890625E-20L;
/* How many times the above error to allow before printing a complaint.
If TOL < 0, consider absolute error instead of relative error. */
#define TOL 8
/* Number of test points to generate on each side of tabulated point. */
#define NPTS 100
#include <stdio.h>
/* Avoid including math.h. */
long double cephes_frexpl (long double, int *);
long double cephes_ldexpl (long double, int);
/* Functions of one variable. */
long double cephes_expl (long double);
long double cephes_logl (long double);
long double cephes_sinl (long double);
long double cephes_cosl (long double);
long double cephes_tanl (long double);
long double cephes_atanl (long double);
long double cephes_asinl (long double);
long double cephes_acosl (long double);
long double cephes_sinhl (long double);
long double cephes_coshl (long double);
long double cephes_tanhl (long double);
long double cephes_asinhl (long double);
long double cephes_acoshl (long double);
long double cephes_atanhl (long double);
#if 1
long double cephes_lgaml (long double);
long double cephes_gammal (long double);
#define lgammal lgaml
#else
long double lgammal (long double);
long double tgammal (long double);
#define lgammal lgaml
#define gammal tgammal
#endif
long double cephes_fabsl (long double);
long double cephes_floorl (long double);
long double cephes_j0l (long double);
long double cephes_y0l (long double);
long double cephes_j1l (long double);
long double cephes_y1l (long double);
/* Data structure of the test. */
struct oneargument
{
char *name; /* Name of the function. */
long double (*func) (long double); /* Function call. */
long double arg1; /* Function argument, assumed exact. */
long double answer1; /* Exact number, close to function value. */
long double answer2; /* answer1 + answer2 has extended precision. */
long double derivative; /* dy/dx evaluated at x = arg1. */
/* Error report threshold. 2 => 1 ulp approximately
if thresh < 0 then consider absolute error instead of relative error. */
int thresh;
};
struct oneargument test1[] =
{
{"exp", expl, 1.0L, 2.7182769775390625L,
4.85091998273536028747e-6L, 2.71828182845904523536L, TOL},
{"exp", expl, -1.0L, 3.678741455078125e-1L,
5.29566362982159552377e-6L, 3.678794411714423215955e-1L, TOL},
{"exp", expl, 0.5L, 1.648712158203125L,
9.1124970031468486507878e-6L, 1.64872127070012814684865L, TOL},
{"exp", expl, -0.5L, 6.065216064453125e-1L,
9.0532673209236037995e-6L, 6.0653065971263342360e-1L, TOL},
{"exp", expl, 2.0L, 7.3890533447265625L,
2.75420408772723042746e-6L, 7.38905609893065022723L, TOL},
{"exp", expl, -2.0L, 1.353302001953125e-1L,
5.08304130019189399949e-6L, 1.3533528323661269189e-1L, TOL},
{"log", logl, 1.41421356237309492343L, 3.465728759765625e-1L,
7.1430341006605745676897e-7L, 7.0710678118654758708668e-1L, TOL},
{"log", logl, 7.07106781186547461715e-1L, -3.46588134765625e-1L,
1.45444856522566402246e-5L, 1.41421356237309517417L, TOL},
{"sin", sinl, 7.85398163397448278999e-1L, 7.0709228515625e-1L,
1.4496030297502751942956e-5L, 7.071067811865475460497e-1L, TOL},
{"sin", sinl, -7.85398163397448501044e-1L, -7.071075439453125e-1L,
7.62758764840238811175e-7L, 7.07106781186547389040e-1L, TOL},
{"sin", sinl, 1.570796326794896558L, 9.999847412109375e-1L,
1.52587890625e-5L, 6.12323399573676588613e-17L, TOL},
{"sin", sinl, -1.57079632679489678004L, -1.0L,
1.29302922820150306903e-32L, -1.60812264967663649223e-16L, TOL},
{"sin", sinl, 4.712388980384689674L, -1.0L,
1.68722975549458979398e-32L, -1.83697019872102976584e-16L, TOL},
{"sin", sinl, -4.71238898038468989604L, 9.999847412109375e-1L,
1.52587890625e-5L, 3.83475850529283315008e-17L, TOL},
{"cos", cosl, 3.92699081698724139500E-1L, 9.23873901367187500000E-1L,
5.63114409926198633370E-6L, -3.82683432365089757586E-1L, TOL},
{"cos", cosl, 7.85398163397448278999E-1L, 7.07092285156250000000E-1L,
1.44960302975460497458E-5L, -7.07106781186547502752E-1L, TOL},
{"cos", cosl, 1.17809724509617241850E0L, 3.82675170898437500000E-1L,
8.26146665231415693919E-6L, -9.23879532511286738554E-1L, TOL},
{"cos", cosl, 1.96349540849362069750E0L, -3.82690429687500000000E-1L,
6.99732241029898567203E-6L, -9.23879532511286785419E-1L, TOL},
{"cos", cosl, 2.35619449019234483700E0L, -7.07107543945312500000E-1L,
7.62758765040545859856E-7L, -7.07106781186547589348E-1L, TOL},
{"cos", cosl, 2.74889357189106897650E0L, -9.23889160156250000000E-1L,
9.62764496328487887036E-6L, -3.82683432365089870728E-1L, TOL},
{"cos", cosl, 3.14159265358979311600E0L, -1.00000000000000000000E0L,
7.49879891330928797323E-33L, -1.22464679914735317723E-16L, TOL},
{"tan", tanl, 7.85398163397448278999E-1L, 9.999847412109375e-1L,
1.52587890624387676600E-5L, 1.99999999999999987754E0L, TOL},
{"tan", tanl, 1.17809724509617241850E0L, 2.41419982910156250000E0L,
1.37332715322352112604E-5L, 6.82842712474618858345E0L, TOL},
{"tan", tanl, 1.96349540849362069750E0L, -2.41421508789062500000E0L,
1.52551752942854759743E-6L, 6.82842712474619262118E0L, TOL},
{"tan", tanl, 2.35619449019234483700E0L, -1.00001525878906250000E0L,
1.52587890623163029801E-5L, 2.00000000000000036739E0L, TOL},
{"tan", tanl, 2.74889357189106897650E0L, -4.14215087890625000000E-1L,
1.52551752982565655126E-6L, 1.17157287525381000640E0L, TOL},
{"atan", atanl, 4.14213562373094923430E-1L, 3.92684936523437500000E-1L,
1.41451752865477964149E-5L, 8.53553390593273837869E-1L, TOL},
{"atan", atanl, 1.0L, 7.85385131835937500000E-1L,
1.30315615108096156608E-5L, 0.5L, TOL},
{"atan", atanl, 2.41421356237309492343E0L, 1.17808532714843750000E0L,
1.19179477349460632350E-5L, 1.46446609406726250782E-1L, TOL},
{"atan", atanl, -2.41421356237309514547E0L, -1.17810058593750000000E0L,
3.34084132752141908545E-6L, 1.46446609406726227789E-1L, TOL},
{"atan", atanl, -1.0L, -7.85400390625000000000E-1L,
2.22722755169038433915E-6L, 0.5L, TOL},
{"atan", atanl, -4.14213562373095145475E-1L, -3.92700195312500000000E-1L,
1.11361377576267665972E-6L, 8.53553390593273703853E-1L, TOL},
{"asin", asinl, 3.82683432365089615246E-1L, 3.92684936523437500000E-1L,
1.41451752864854321970E-5L, 1.08239220029239389286E0L, TOL},
{"asin", asinl, 0.5L, 5.23590087890625000000E-1L,
8.68770767387307710723E-6L, 1.15470053837925152902E0L, TOL},
{"asin", asinl, 7.07106781186547461715E-1L, 7.85385131835937500000E-1L,
1.30315615107209645016E-5L, 1.41421356237309492343E0L, TOL},
{"asin", asinl, 9.23879532511286738483E-1L, 1.17808532714843750000E0L,
1.19179477349183147612E-5L, 2.61312592975275276483E0L, TOL},
{"asin", asinl, -0.5L, -5.23605346679687500000E-1L,
6.57108138862692289277E-6L, 1.15470053837925152902E0L, TOL},
{"asin", asinl, 1.16415321826934814453125e-10L,
1.16415321826934814453125e-10L, 2.629536350736706018055e-31L,
1.0000000000000000000067762L, TOL},
{"asin", asinl, 1.0000000000000000000183779E-10L,
9.9999999979890480394928431E-11L, 2.0109519607076028264987890E-20L,
1.0L, TOL},
{"asin", asinl, 1.0000000000000000000007074E-8L,
9.9999999999948220585910263E-9L, 5.1781080827147808155022014E-21L,
1.0L, TOL},
{"asin", asinl, 0.97499847412109375L, 1.346710205078125L,
3.969526822009922560999e-6L, 4.500216008585875735254L, TOL},
{"acos", acosl, 1.95090322016128192573E-1L, 1.37443542480468750000E0L,
1.13611408471185777914E-5L, -1.01959115820831832232E0L, TOL},
{"acos", acosl, 3.82683432365089615246E-1L, 1.17808532714843750000E0L,
1.19179477351337991247E-5L, -1.08239220029239389286E0L, TOL},
{"acos", acosl, 0.5L, 1.04719543457031250000E0L,
2.11662628524615421446E-6L, -1.15470053837925152902E0L, TOL},
{"acos", acosl, 7.07106781186547461715E-1L, 7.85385131835937500000E-1L,
1.30315615108982668201E-5L, -1.41421356237309492343E0L, TOL},
{"acos", acosl, 9.23879532511286738483E-1L, 3.92684936523437500000E-1L,
1.41451752867009165605E-5L, -2.61312592975275276483E0L, TOL},
{"acos", acosl, 9.80785280403230430579E-1L, 1.96334838867187500000E-1L,
1.47019821746724723933E-5L, -5.12583089548300990774E0L, TOL},
{"acos", acosl, -0.5L, 2.09439086914062500000E0L,
4.23325257049230842892E-6L, -1.15470053837925152902E0L, TOL},
{"sinh", sinhl, 1.0L, 1.17518615722656250000E0L,
1.50364172389568823819E-5L, 1.54308063481524377848E0L, TOL},
{"sinh", sinhl, 7.09089565712818057364E2L, 4.49423283712885057274E307L,
1.70878916528708958045E289L, 4.49423283712885057274E307L, TOL},
{"sinh", sinhl, 2.22044604925031308085E-16L, 0.00000000000000000000E0L,
2.22044604925031308085E-16L, 1.00000000000000000000E0L, TOL},
{"sinh", sinhl, 3.7252902984619140625e-9L, 3.7252902984619140625e-9L,
8.616464714094038285889380656847999229E-27L,
1.00000000000000000693889L, TOL},
{"sinh", sinhl, 2.3283064365386962890625e-10L, 2.3283064365386962890625e-10L,
2.103629080589364814436978072135626630E-30,
1.000000000000000000027105L, TOL},
{"cosh", coshl, 7.09089565712818057364E2L, 4.49423283712885057274E307L,
1.70878916528708958045E289L, 4.49423283712885057274E307L, TOL},
{"cosh", coshl, 1.0L, 1.54307556152343750000E0L,
5.07329180627847790562E-6L, 1.17520119364380145688E0L, TOL},
{"cosh", coshl, 0.5L, 1.12762451171875000000E0L,
1.45348763078522622516E-6L, 5.21095305493747361622E-1L, TOL},
{"tanh", tanhl, 0.5L, 4.62112426757812500000E-1L,
4.73050219725850231848E-6L, 7.86447732965927410150E-1L, TOL},
{"tanh", tanhl, 5.49306144334054780032E-1L, 4.99984741210937500000E-1L,
1.52587890624507506378E-5L, 7.50000000000000049249E-1L, TOL},
{"tanh", tanhl, 0.625L, 5.54595947265625000000E-1L,
3.77508375729399903910E-6L, 6.92419147969988069631E-1L, TOL},
{"asinh", asinhl, 0.5L, 4.81201171875000000000E-1L,
1.06531846034474977589E-5L, 8.94427190999915878564E-1L, TOL},
{"asinh", asinhl, 1.0L, 8.81362915039062500000E-1L,
1.06719804805252326093E-5L, 7.07106781186547524401E-1L, TOL},
{"asinh", asinhl, 2.0L, 1.44363403320312500000E0L,
1.44197568534249327674E-6L, 4.47213595499957939282E-1L, TOL},
{"acosh", acoshl, 2.0L, 1.31695556640625000000E0L,
2.33051856670862504635E-6L, 5.77350269189625764509E-1L, TOL},
{"acosh", acoshl, 1.5L, 9.62417602539062500000E-1L,
6.04758014439499551783E-6L, 8.94427190999915878564E-1L, TOL},
{"acosh", acoshl, 1.03125L, 2.49343872070312500000E-1L,
9.62177257298785143908E-6L, 3.96911150685467059809E0L, TOL},
{"atanh", atanhl, 0.5L, 5.49301147460937500000E-1L,
4.99687311734569762262E-6L, 1.33333333333333333333E0L, TOL},
{"j0", j0l, 8.0L, 1.71646118164062500000E-1L,
4.68897349140609086941E-6L, -2.34636346853914624381E-1, -4},
{"j0", j0l, 4.54541015625L, -3.09783935546875000000E-1L,
7.07472668157686463367E-6L, 2.42993657373627558460E-1L, -4},
{"j0", j0l, 2.85711669921875L, -2.07901000976562500000E-1L,
1.15237285263902751582E-5L, -3.90402225324501311651E-1L, -4},
{"j0", j0l, 2.0L, 2.23876953125000000000E-1L,
1.38260162356680518275E-5L, -5.76724807756873387202E-1L, -4},
{"j0", j0l, 1.16415321826934814453125e-10L, 9.99984741210937500000E-1L,
1.52587890624999966119E-5L, 9.99999999999999999997E-1L, -4},
{"j0", j0l, -2.0L, 2.23876953125000000000E-1L,
1.38260162356680518275E-5L, 5.76724807756873387202E-1L, -4},
{"y0", y0l, 8.0L, 2.23510742187500000000E-1L,
1.07472000662205273234E-5L, 1.58060461731247494256E-1L, -4},
{"y0", y0l, 4.54541015625L, -2.08114624023437500000E-1L,
1.45018823856668874574E-5L, -2.88887645307401250876E-1L, -4},
{"y0", y0l, 2.85711669921875L, 4.20303344726562500000E-1L,
1.32781607563122276008E-5L, -2.82488638474982469213E-1, -4},
{"y0", y0l, 2.0L, 5.10360717773437500000E-1L,
1.49548763076195966066E-5L, 1.07032431540937546888E-1L, -4},
{"y0", y0l, 1.16415321826934814453125e-10L, -1.46357574462890625000E1L,
3.54110537011061127637E-6L, 5.46852220461145271913E9L, -4},
{"j1", j1l, 8.0L, 2.34634399414062500000E-1L,
1.94743985212438127665E-6L,1.42321263780814578043E-1, -4},
{"j1", j1l, 4.54541015625L, -2.42996215820312500000E-1L,
2.55844668494153980076E-6L, -2.56317734136211337012E-1, -4},
{"j1", j1l, 2.85711669921875L, 3.90396118164062500000E-1L,
6.10716043881165077013E-6L, -3.44531507106757980441E-1L, -4},
{"j1", j1l, 2.0L, 5.76721191406250000000E-1L,
3.61635062338720244824E-6L, -6.44716247372010255494E-2L, -4},
{"j1", j1l, 1.16415321826934814453125e-10L,
5.820677273504770710133016109466552734375e-11L,
8.881784197001251337312921818461805735896e-16L,
4.99999999999999999997E-1L, -4},
{"j1", j1l, -2.0L, -5.76721191406250000000E-1L,
-3.61635062338720244824E-6L, -6.44716247372010255494E-2L, -4},
{"y1", y1l, 8.0L, -1.58065795898437500000E-1L,
5.33416719000574444473E-6L, 2.43279047103972157309E-1L, -4},
{"y1", y1l, 4.54541015625L, 2.88879394531250000000E-1L,
8.25077615125087585195E-6L, -2.71656024771791736625E-1L, -4},
{"y1", y1l, 2.85711669921875L, 2.82485961914062500000E-1,
2.67656091996921314433E-6L, 3.21444694221532719737E-1, -4},
{"y1", y1l, 2.0L, -1.07040405273437500000E-1L,
7.97373249995311162923E-6L, 5.63891888420213893041E-1, -4},
{"y1", y1l, 1.16415321826934814453125e-10L, -5.46852220500000000000E9L,
3.88547280871200700671E-1L, 4.69742480525120196168E19L, -4},
{"gamma", gammal, 1.0L, 1.0L,
0.0L, -5.772156649015328606e-1L, TOL},
{"gamma", gammal, 2.0L, 1.0L,
0.0L, 4.2278433509846713939e-1L, TOL},
{"gamma", gammal, 3.0L, 2.0L,
0.0L, 1.845568670196934279L, TOL},
{"gamma", gammal, 4.0L, 6.0L,
0.0L, 7.536706010590802836L, TOL},
{"lgamma", lgammal, 8.0L, 8.525146484375L,
1.48766904143001655310E-5, 2.01564147795560999654E0L, TOL},
{"lgamma", lgammal, 8.99993896484375e-1L, 6.6375732421875e-2L,
5.11505711292524166220E-6L, -7.54938684259372234258E-1, -TOL},
{"lgamma", lgammal, 7.31597900390625e-1L, 2.2369384765625e-1L,
5.21506341809849792422E-6L,-1.13355566660398608343E0L, -TOL},
{"lgamma", lgammal, 2.31639862060546875e-1L, 1.3686676025390625L,
1.12609441752996145670E-5L, -4.56670961813812679012E0, -TOL},
{"lgamma", lgammal, 1.73162841796875L, -8.88214111328125e-2L,
3.36207740803753034508E-6L, 2.33339034686200586920E-1L, -TOL},
{"lgamma", lgammal, 1.23162841796875L,-9.3902587890625e-2L,
1.28765089229009648104E-5L, -2.49677345775751390414E-1L, -TOL},
{"lgamma", lgammal, 7.3786976294838206464e19L, 3.301798506038663053312e21L,
-1.656137564136932662487046269677E5L, 4.57477139169563904215E1L, TOL},
{"lgamma", lgammal, 1.0L, 0.0L,
0.0L, -5.77215664901532860607E-1L, -TOL},
{"lgamma", lgammal, 2.0L, 0.0L,
0.0L, 4.22784335098467139393E-1L, -TOL},
{"lgamma", lgammal, 1.08420217248550443401E-19L,4.36682586669921875e1L,
1.37082843669932230418E-5L, -9.22337203685477580858E18L, TOL},
{"lgamma", lgammal, -0.5L, 1.2655029296875L,
9.19379714539648894580E-6L, 3.64899739785765205590E-2L, TOL},
{"lgamma", lgammal, -1.5L, 8.6004638671875e-1L,
6.28657731014510932682E-7L, 7.03156640645243187226E-1L, TOL},
{"lgamma", lgammal, -2.5L, -5.6243896484375E-2L,
1.79986700949327405470E-7, 1.10315664064524318723E0L, -TOL},
{"lgamma", lgammal, -3.5L, -1.30902099609375L,
1.43111007079536392848E-5L, 1.38887092635952890151E0L, TOL},
{"null", NULL, 0.0L, 0.0L, 0.0L, 1},
};
/* These take care of extra-precise floating point register problems. */
volatile long double volat1;
volatile long double volat2;
/* Return the next nearest floating point value to X
in the direction of UPDOWN (+1 or -1).
(Might fail if X is denormalized.) */
long double
nextval (x, updown)
long double x;
int updown;
{
long double m;
int i;
volat1 = x;
m = 0.25L * MACHEPL * volat1 * updown;
volat2 = volat1 + m;
if (volat2 != volat1)
printf ("successor failed\n");
for (i = 2; i < 10; i++)
{
volat2 = volat1 + i * m;
if (volat1 != volat2)
return volat2;
}
printf ("nextval failed\n");
return volat1;
}
int
main ()
{
long double (*fun1) (long double);
int i, j, errs, tests, err_thresh;
long double x, x0, dy, err;
errs = 0;
tests = 0;
i = 0;
for (;;)
{
/* Function call reference. */
fun1 = test1[i].func;
if (fun1 == NULL)
break;
/* Function argument. */
volat1 = test1[i].arg1;
/* x0 is the given argument, x scans from slightly below to above x0. */
x0 = volat1;
x = volat1;
for (j = 0; j <= NPTS; j++)
{
/* delta x */
volat1 = x - x0;
/* delta y */
dy = volat1 * test1[i].derivative;
/* y + delta y */
dy = test1[i].answer2 + dy;
volat1 = test1[i].answer1 + dy;
/* Run the function under test. */
volat2 = (*(fun1)) (x);
if (volat2 != volat1)
{
/* Estimate difference between program result
and extended precision function value. */
err = volat2 - test1[i].answer1;
err = err - dy;
/* Compare difference with reporting threshold. */
err_thresh = test1[i].thresh;
if (err_thresh >= 0)
err = err / volat1; /* relative error */
else
{
err_thresh = -err_thresh; /* absolute error */
/* ...but relative error if function value > 1 */
if (cephes_fabsl(volat1) > 1.0L)
err = err / volat1;
}
if (cephes_fabsl (err) > (err_thresh * MACHEPL))
{
printf ("%d %s(%.19Le) = %.19Le, rel err = %.3Le\n",
j, test1[i].name, x, volat2, err);
errs += 1;
}
}
x = nextval (x, 1);
tests += 1;
}
x = x0;
x = nextval (x, -1);
for (j = 1; j < NPTS; j++)
{
volat1 = x - x0;
dy = volat1 * test1[i].derivative;
dy = test1[i].answer2 + dy;
volat1 = test1[i].answer1 + dy;
volat2 = (*(fun1)) (x);
if (volat2 != volat1)
{
err = volat2 - test1[i].answer1;
err = err - dy;
err_thresh = test1[i].thresh;
if (err_thresh >= 0)
err = err / volat1; /* relative error */
else
{
err_thresh = -err_thresh;
if (cephes_fabsl(volat1) > 1.0L)
err = err / volat1;
}
if (cephes_fabsl (err) > (err_thresh * MACHEPL))
{
printf ("%d %s(%.19Le) = %.19Le, rel err = %.3Le\n",
j, test1[i].name, x, volat2, err);
errs += 1;
}
}
x = nextval (x, -1);
tests += 1;
}
i += 1;
}
printf ("%d errors in %d tests\n", errs, tests);
exit (0);
}
|
icclab/monasca-common
|
java/monasca-common-model/src/test/java/monasca/common/model/ServicesTest.java
|
<reponame>icclab/monasca-common<filename>java/monasca-common-model/src/test/java/monasca/common/model/ServicesTest.java
package monasca.common.model;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
@Test
public class ServicesTest {
public void shouldValidateObjectStoreMetricName() {
assertTrue(Services.isValidMetricName("hpcs.object-store", "project_write_bytes"));
}
}
|
rkolyan/Algorithm-s-Analyses
|
aa_6/io.h
|
#ifndef IO_H
#define IO_H
#include <stdio.h>
#include "parameters.h"
#include "way.h"
error_t print_way(way_t *way);
error_t input_matrix_from_file(double ***matrix, int *count, FILE *file);
error_t input_parameters(parameters_t *parameters);
error_t input_integer(int *number, const char *name, char is_positive);
error_t input_float(double *number, const char *name, char is_positive);
#endif
|
RudiBoshoff/test-first-teaching
|
learn_ruby/screen_scrape/bbc_files/bbccom_capable.js
|
/*
bbc.com core javascript
version: $Id: bbccom_test.js,v 1.3 2008/05/19 15:22:28 daffel01 Exp $
*/
BBC.adverts.isCapable(); // comment this out to make all ads go away
|
fhornain/patternfly-react-seed_1
|
node_modules/@patternfly/react-icons/dist/esm/icons/smoking-icon.d.js
|
<filename>node_modules/@patternfly/react-icons/dist/esm/icons/smoking-icon.d.js
//# sourceMappingURL=smoking-icon.d.js.map
|
dotnetweekly/dnw-api
|
data/tags.js
|
<reponame>dotnetweekly/dnw-api
const tags = [
'.net',
'.net-core',
'.net-standard',
'akka.net',
'android',
'angular',
'asp.net',
'asp.net-core',
'asp.net-mvc',
'azure',
'azure-application-insights',
'babel',
'bing-maps',
'blazor',
'blockchain',
'build-2017',
'c#',
'caching',
'conference',
'contribution',
'ddd',
'debugging',
'docker',
'documentdb',
'domain-driven-development',
'edge',
'ef',
'elastic-search',
'entity-framework',
'events',
'f#',
'flow',
'git',
'github',
'glimpse',
'iis',
'interview',
'ios',
'iot',
'javascript',
'kibana',
'kubernetes',
'kudu',
'linux',
'local-storage',
'machine-learning',
'microservices',
'msbuild',
'node.js',
'open-source',
'performance',
'power-bi',
'powerapps',
'raspberry',
'raspberry-pi-3',
'sms',
'sql-server',
'startups',
'swagger',
'testing',
'tools',
'twilio',
'video',
'visual-studio',
'visual-studio-2017',
'vs',
'vs-2017',
'webforms',
'websockets',
'windows-10',
'windows-apps',
'windows-services',
'wpf',
'xamarin'
];
module.exports = tags;
|
caibinglong1987/ucserver
|
src/main/java/com/roamtech/uc/util/RxBus.java
|
package com.roamtech.uc.util;
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
import java.lang.reflect.Type;
import java.util.*;
/**
* Created by admin03 on 2016/8/17.
*/
public class RxBus {
private static RxBus instance;
private Map<Class<?>,Vector<Subject>> subjectMap = new HashMap<Class<?>,Vector<Subject>>();
private RxBus() {
}
public static synchronized RxBus getInstance() {
if (null == instance) {
instance = new RxBus();
}
return instance;
}
public synchronized <T> Observable<T> register(Class<?> type) {
Subject<T, T> subject = PublishSubject.create();
Vector<Subject> listeners = subjectMap.get(type);
if(listeners == null) {
listeners = new Vector<Subject>();
}
listeners.add(subject);
subjectMap.put(type,listeners);
return subject;
}
public synchronized void unregister(Class<?> type,Subject subject) {
Vector<Subject> listeners = subjectMap.get(type);
if(listeners != null) {
listeners.remove(subject);
}
}
public void post(Object content) {
synchronized (this) {
Vector<Subject> listeners;
if(content instanceof List) {
listeners = subjectMap.get(((List)content).get(0).getClass());
} else {
listeners = subjectMap.get(content.getClass());
}
if(listeners != null) {
for (Subject subject : listeners) {
if (subject != null) {
subject.onNext(content);
}
}
}
}
}
}
|
walki/codewar-solutions
|
javascript/7kyu/alphabetical-addition.js
|
<gh_stars>0
function addLetters(...letters) {
return letters.length === 0 ? 'z' : valueToLetter( letters.reduce( (acc, curr) => letterToValue( curr ) + acc, 0) );
}
function letterToValue(letter) {
return letter.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
}
function valueToLetter( value ) {
return String.fromCharCode( ((value - 1) % 26) + 'a'.charCodeAt(0));
}
|
fengjixuchui/napoca
|
napoca/introspection/glue_layer/intromsrhook.c
|
<filename>napoca/introspection/glue_layer/intromsrhook.c
/*
* Copyright (c) 2020 Bitdefender
* SPDX-License-Identifier: Apache-2.0
*/
/// @addtogroup introcallhv
///@{
/** @file intromsrhook.c
* @brief INTROMSRHOOK - NAPOCA hypervisor glue layer, MSR hook support
*
*/
#include "napoca.h"
#include "introstatus.h"
#include "introspection/glue_layer/intromsrhook.h"
#include "guests/intro.h"
#include "guests/guests.h"
NTSTATUS
GuestIntNapRegisterMsrHandler(
_In_ PVOID Guest, // Guest handle.
_In_ PFUNC_IntMSRViolationCallback Callback // Callback that will be called whenever a MSR violation takes place.
)
{
GUEST *guest;
if (Guest == NULL)
{
return CX_STATUS_INVALID_PARAMETER_1;
}
if (Callback == NULL)
{
return CX_STATUS_INVALID_PARAMETER_2;
}
guest = Guest;
if (guest->Intro.RawIntroMsrCallback != NULL) return CX_STATUS_ALREADY_INITIALIZED;
ValidateIntroCallbacksLock(&guest->Intro.IntroCallbacksLock);
guest->Intro.RawIntroMsrCallback = Callback;
return CX_STATUS_SUCCESS;
}
NTSTATUS
GuestIntNapUnregisterMsrHandler(
_In_ PVOID Guest // Guest handle.
)
{
GUEST *guest;
if (Guest == NULL)
{
return CX_STATUS_INVALID_PARAMETER_1;
}
guest = Guest;
if (guest->Intro.RawIntroMsrCallback == NULL) return CX_STATUS_NOT_INITIALIZED_HINT;
ValidateIntroCallbacksLock(&guest->Intro.IntroCallbacksLock);
guest->Intro.RawIntroMsrCallback = NULL;
return CX_STATUS_SUCCESS;
}
NTSTATUS
GuestIntNapEnableMsrExit(
_In_ PVOID Guest, // Guest handle.
_In_ DWORD Msr, // The MSR we want to intercept.
_Out_ BOOLEAN* OldValue // TRUE if the MSR was already intercepted, FALSE otherwise.
)
{
if (Guest == NULL)
{
return CX_STATUS_INVALID_PARAMETER_1;
}
GUEST *guest = Guest;
if (OldValue == NULL)
{
return CX_STATUS_INVALID_PARAMETER_3;
}
// Acquire global spinlock
HvAcquireSpinLock(&guest->MsrHookLockGlb);
// Update MSR bitmap
if ((Msr >= 0xC0000000) && (Msr <= 0xC0001FFF))
{
Msr = Msr - 0xC0000000;
*OldValue = (guest->MsrBitmap[384 + (Msr >> 6)] & BIT_AT(Msr & 0x3f)) != 0;
guest->MsrBitmap[384 + (Msr >> 6)] |= BIT_AT(Msr & 0x3f); // msr / 64, msr % 64
}
else
{
*OldValue = (guest->MsrBitmap[256 + (Msr >> 6)] & BIT_AT(Msr & 0x3f)) != 0;
guest->MsrBitmap[256 + (Msr >> 6)] |= BIT_AT(Msr & 0x3f); // msr / 64, msr % 64
}
// Release global spinlock
HvReleaseSpinLock(&guest->MsrHookLockGlb);
return CX_STATUS_SUCCESS;
}
NTSTATUS
GuestIntNapDisableMsrExit(
_In_ PVOID Guest, // Guest handle.
_In_ DWORD Msr, // The MSR we want to disable interceptions on.
_Out_ BOOLEAN* OldValue // TRUE if interceptions were active on this MSR, FALSE otherwise.
)
{
if (Guest == NULL)
{
return CX_STATUS_INVALID_PARAMETER_1;
}
if (OldValue == NULL)
{
return CX_STATUS_INVALID_PARAMETER_3;
}
GUEST *guest = Guest;
// Acquire global spinlock
HvAcquireSpinLock(&guest->MsrHookLockGlb);
// Update MSR bitmap
if ((Msr >= 0xC0000000) && (Msr <= 0xC0001FFF))
{
Msr = Msr - 0xC0000000;
*OldValue = (guest->MsrBitmap[384 + (Msr >> 6)] & BIT_AT(Msr & 0x3f)) != 0;
guest->MsrBitmap[384 + (Msr >> 6)] &= ~BIT_AT(Msr & 0x3f); // msr / 64, msr % 64
}
else
{
*OldValue = (guest->MsrBitmap[256 + (Msr >> 6)] & BIT_AT(Msr & 0x3f)) != 0;
guest->MsrBitmap[256 + (Msr >> 6)] &= ~BIT_AT(Msr & 0x3f); // msr / 64, msr % 64
}
// Release global spinlock
HvReleaseSpinLock(&guest->MsrHookLockGlb);
return CX_STATUS_SUCCESS;
}
///@}
|
WarlockD/quake-stm32
|
quake_framebuffer/quake_framebuffer/d_modech.cpp
|
<reponame>WarlockD/quake-stm32<gh_stars>1-10
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// d_modech.c: called when mode has just changed
#include "icommon.h"
#include "d_local.h"
int d_vrectx, d_vrecty, d_vrectright_particle, d_vrectbottom_particle;
int d_y_aspect_shift, d_pix_min, d_pix_max, d_pix_shift;
int d_scantable[MAXHEIGHT];
short *zspantable[MAXHEIGHT];
/*
================
D_Patch
================
*/
void D_Patch (void)
{
#if id386
static qboolean protectset8 = false;
if (!protectset8)
{
Sys_MakeCodeWriteable ((int)D_PolysetAff8Start,
(int)D_PolysetAff8End - (int)D_PolysetAff8Start);
protectset8 = true;
}
#endif // id386
}
/*
================
D_ViewChanged
================
*/
void D_ViewChanged (void)
{
int rowbytes;
if (r_dowarp)
rowbytes = WARP_WIDTH;
else
rowbytes = vid.rowbytes;
scale_for_mip = xscale;
if (yscale > xscale)
scale_for_mip = yscale;
d_zrowbytes = vid.width * 2;
d_zwidth = vid.width;
d_pix_min = r_refdef.vrect.width / 320;
if (d_pix_min < 1)
d_pix_min = 1;
d_pix_max = (int)((float)r_refdef.vrect.width / (320.0f / 4.0f) + 0.5f);
d_pix_shift = 8 - (int)((float)r_refdef.vrect.width / 320.0f + 0.5f);
if (d_pix_max < 1)
d_pix_max = 1;
if (pixelAspect > 1.4)
d_y_aspect_shift = 1;
else
d_y_aspect_shift = 0;
d_vrectx = r_refdef.vrect.x;
d_vrecty = r_refdef.vrect.y;
d_vrectright_particle = r_refdef.vrectright - d_pix_max;
d_vrectbottom_particle =
r_refdef.vrectbottom - (d_pix_max << d_y_aspect_shift);
{
int i;
for (i=0 ; i<vid.height; i++)
{
d_scantable[i] = i*rowbytes;
zspantable[i] = d_pzbuffer + i*d_zwidth;
}
}
D_Patch ();
}
|
gcodebackups/cortex-vfx
|
include/IECore/PlaneImplicitSurfaceFunction.h
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2011, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * 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.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IE_CORE_PLANEIMPLICITSURFACEFUNCTION_H
#define IE_CORE_PLANEIMPLICITSURFACEFUNCTION_H
#include "IECore/ImplicitSurfaceFunction.h"
#include "IECore/VectorOps.h"
namespace IECore
{
/// An implicit surface describing a plane
/// \ingroup implicitGroup
template<typename P, typename V>
class PlaneImplicitSurfaceFunction : public ImplicitSurfaceFunction<P, V>
{
public:
typedef P Point;
typedef VectorTraits<P> PointTraits;
typedef typename VectorTraits<P>::BaseType PointBaseType;
typedef V Value;
typedef VectorTraits<V> ValueTraits;
typedef typename VectorTraits<V>::BaseType ValueBaseType;
IE_CORE_DECLAREMEMBERPTR2( PlaneImplicitSurfaceFunction<P, V> );
/// Construct an implicit plane from a normal and a distance from the origin
PlaneImplicitSurfaceFunction( const Point &normal, PointBaseType distance ) : m_normal( normal ), m_distance( distance )
{
vecNormalize( m_normal );
}
/// Construct an implicit plane from a normal and a point on the plane
PlaneImplicitSurfaceFunction( const Point &normal, const Point &origin ) : m_normal( normal )
{
vecNormalize( m_normal );
m_distance = -vecDot( m_normal, origin );
}
Value operator()( const Point &p )
{
return vecDot( m_normal, p ) + m_distance;
}
virtual Value getValue( const Point &p )
{
return this->operator()(p);
}
protected:
Point m_normal;
PointBaseType m_distance;
};
typedef PlaneImplicitSurfaceFunction<Imath::V3f, float> PlaneImplicitSurfaceFunctionV3ff;
typedef PlaneImplicitSurfaceFunction<Imath::V3f, double> PlaneImplicitSurfaceFunctionV3fd;
typedef PlaneImplicitSurfaceFunction<Imath::V3d, float> PlaneImplicitSurfaceFunctionV3df;
typedef PlaneImplicitSurfaceFunction<Imath::V3d, double> PlaneImplicitSurfaceFunctionV3dd;
} // namespace IECore
#endif // IE_CORE_PLANEIMPLICITSURFACEFUNCTION_H
|
kkcookies99/UAST
|
Dataset/Leetcode/train/101/334.js
|
<filename>Dataset/Leetcode/train/101/334.js
var XXX = function(root) {
if (!root) return false
if (root && !root.left && !root.right) return true
let root1 = root.left, root2 = root.right
if (!root1 || !root2) return false
let temp1 = [root1], temp2 = [root2]
while (temp1.length && temp2.length) {
let t1 = temp1.shift()
let t2 = temp2.shift()
if (t1.val != t2.val) {
return false
}
if (t1.left && t2.right) {
temp1.push(t1.left)
temp2.push(t2.right)
} else {
if ((t1.left && !t2.right) || (!t1.left && t2.right)) {
return false
}
}
if (t1.right && t2.left) {
temp1.push(t1.right)
temp2.push(t2.left)
} else {
if ((t1.right && !t2.left) || (!t1.right && t2.left)) {
return false
}
}
}
return true
};
|
lechium/tvOS10Headers
|
System/Library/Frameworks/MediaPlayer.framework/MPModelStorePlaybackItemsResponse.h
|
/*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:05:33 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <MediaPlayer/MPModelResponse.h>
#import <libobjc.A.dylib/MPModelStoreEquivalencyMapping.h>
@class NSMutableDictionary, MPStoreLibraryPersonalizationResponse, NSString;
@interface MPModelStorePlaybackItemsResponse : MPModelResponse <MPModelStoreEquivalencyMapping> {
NSMutableDictionary* _localAdamIDToEquivalencySourceAdamIDMap;
BOOL _finalResponse;
MPStoreLibraryPersonalizationResponse* _personalizationResponse;
MPModelStorePlaybackItemsResponse* _updatedResponse;
}
@property (nonatomic,readonly) MPStoreLibraryPersonalizationResponse * _personalizationResponse; //@synthesize personalizationResponse=_personalizationResponse - In the implementation block
@property (getter=_updatedResponse,nonatomic,readonly) MPModelStorePlaybackItemsResponse * _updatedResponse; //@synthesize updatedResponse=_updatedResponse - In the implementation block
@property (assign,getter=isFinalResponse,nonatomic) BOOL finalResponse; //@synthesize finalResponse=_finalResponse - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(MPModelStorePlaybackItemsResponse *)_updatedResponse;
-(id)initWithRequest:(id)arg1 personalizationResponse:(id)arg2 ;
-(BOOL)isFinalResponse;
-(void)setFinalResponse:(BOOL)arg1 ;
-(void)_setEquivalencySourceStoreAdamID:(long long)arg1 forLocalStoreAdamID:(long long)arg2 ;
-(void)_invalidateWithUpdatedResponse:(id)arg1 ;
-(id)equivalencySourceStoreAdamIDForLocalStoreAdamID:(long long)arg1 ;
-(void)_allowsExplicitContentDidChangeNotification:(id)arg1 ;
-(void)_personalizationResponseDidInvalidateNotification:(id)arg1 ;
-(MPStoreLibraryPersonalizationResponse *)_personalizationResponse;
@end
|
nodule/pkgcloud
|
nodes/createServer/node.js
|
output = [client, 'createServer']
|
johnsonm325/compliance-frontend
|
src/PresentationalComponents/TabSwitcher/TabSwitcher.js
|
import React from 'react';
import { useLocation, useHistory } from 'react-router-dom';
import propTypes from 'prop-types';
import { Tabs } from '@patternfly/react-core';
import { useAnchor } from 'Utilities/Router';
// Plain tab component without any styling
export const ContentTab = ({ children }) => children;
const findTab = (tabs, key) => tabs.find((tab) => tab.props.eventKey === key);
const useAnchorLevels = (defaultAnchor, level) => {
const anchor = useAnchor(defaultAnchor);
const levels = anchor.split('|');
const currentAnchor = levels[level] || defaultAnchor;
return {
levels,
currentAnchor,
};
};
// Shows always only one tab, either the current or if not available the default
const TabSwitcher = ({ children, activeKey: currentAnchor, defaultTab }) => {
const getDefaultTab = () =>
defaultTab ? findTab(children, defaultTab) : children[0];
const currentTab = findTab(children, currentAnchor);
return currentTab ? [currentTab] : [getDefaultTab()];
};
TabSwitcher.propTypes = {
activeTab: propTypes.number,
children: propTypes.node,
};
// Routed Plain switcher that can be used with PatternFly tabs
export const RoutedTabSwitcher = ({ children, defaultTab, level }) => {
const { currentAnchor } = useAnchorLevels(defaultTab, level);
return <TabSwitcher activeKey={currentAnchor}>{children}</TabSwitcher>;
};
RoutedTabSwitcher.propTypes = {
children: propTypes.node,
defaultTab: propTypes.string,
level: propTypes.number,
};
RoutedTabSwitcher.defaultProps = {
level: 0,
};
// Allows to use full PatternFly tabs and switch them using the URL hash
// It can be used with filled tabs (EditPolicyForm) or just tab "buttons" (PolicyDetails)
export const RoutedTabs = ({
children,
defaultTab,
level,
ouiaId,
...props
}) => {
const { push } = useHistory();
const { pathname, state } = useLocation();
const { currentAnchor, levels } = useAnchorLevels(defaultTab, level);
const handleTabSelect = (e, eventKey) => {
e.preventDefault();
const tabToActivate = eventKey.replace('#', '');
let tabAnchor = levels;
tabAnchor[level] = tabToActivate;
push({
state,
to: pathname,
hash: tabAnchor.slice(0, level + 1).join('|'),
});
};
const tabAvailable = children
.map(({ props: { eventKey } }) => eventKey)
.find((tabAnchor) => tabAnchor === currentAnchor);
return (
<Tabs
{...props}
ouiaId={ouiaId}
onSelect={handleTabSelect}
activeKey={tabAvailable ? currentAnchor : defaultTab}
>
{children}
</Tabs>
);
};
RoutedTabs.defaultProps = {
level: 0,
};
RoutedTabs.propTypes = {
children: propTypes.node,
defaultTab: propTypes.string,
level: propTypes.number,
ouiaId: propTypes.string,
};
export default TabSwitcher;
|
calmsacibis995/minix
|
usr.bin/infocmp/infocmp.c
|
<gh_stars>0
/* $NetBSD: infocmp.c,v 1.8 2013/10/01 09:01:49 roy Exp $ */
/*
* Copyright (c) 2009, 2010 The NetBSD Foundation, Inc.
*
* This code is derived from software contributed to The NetBSD Foundation
* by <NAME>.
*
* 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.
*
* 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 AUTHOR 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.
*/
#include <sys/cdefs.h>
__RCSID("$NetBSD: infocmp.c,v 1.8 2013/10/01 09:01:49 roy Exp $");
#include <sys/ioctl.h>
#include <ctype.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <term_private.h>
#include <term.h>
#include <unistd.h>
#define SW 8
typedef struct tient {
char type;
const char *id;
signed char flag;
short num;
const char *str;
} TIENT;
static size_t cols;
static int aflag, cflag, nflag, qflag, xflag;
static size_t
outstr(FILE *f, const char *str)
{
unsigned char ch;
size_t r, l;
r = 0;
l = strlen(str);
while ((ch = (unsigned char)(*str++)) != '\0') {
switch (ch) {
case 128:
ch = '0';
break;
case '\033':
ch = 'E';
break;
case '\014':
ch = 'f';
break;
case '^': /* FALLTHROUGH */
case ',': /* escape these */
break;
case ' ':
ch = 's';
break;
default:
if (ch == '\177') {
if (f != NULL)
fputc('^', f);
ch = '?';
r++;
} else if (iscntrl(ch) &&
ch < 128 &&
ch != '\\' &&
(l < 4 || isdigit((unsigned char)*str)))
{
if (f != NULL)
fputc('^', f);
ch += '@';
r++;
} else if (!isprint(ch)) {
if (f != NULL)
fprintf(f, "\\%03o", ch);
r += 4;
continue;
}
goto prnt;
}
if (f != NULL)
fputc('\\', f);
r++;
prnt:
if (f != NULL)
fputc(ch, f);
r++;
}
return r;
}
static int
ent_compare(const void *a, const void *b)
{
const TIENT *ta, *tb;
ta = (const TIENT *)a;
tb = (const TIENT *)b;
return strcmp(ta->id, tb->id);
}
static void
setdb(char *db)
{
size_t len;
len = strlen(db);
if (len > 3 &&
db[len - 3] == '.' &&
db[len - 2] == 'd' &&
db[len - 1] == 'b')
db[len - 3] = '\0';
setenv("TERMINFO", db, 1);
}
static void
print_ent(const TIENT *ents, size_t nents)
{
size_t col, i, l;
char nbuf[64];
if (nents == 0)
return;
col = SW;
printf("\t");
for (i = 0; i < nents; i++) {
if (*ents[i].id == '.' && aflag == 0)
continue;
switch (ents[i].type) {
case 'f':
if (ents[i].flag == ABSENT_BOOLEAN)
continue;
l = strlen(ents[i].id) + 2;
if (ents[i].flag == CANCELLED_BOOLEAN)
l++;
break;
case 'n':
if (ents[i].num == ABSENT_NUMERIC)
continue;
if (VALID_NUMERIC(ents[i].num))
l = snprintf(nbuf, sizeof(nbuf), "%s#%d,",
ents[i].id, ents[i].num);
else
l = snprintf(nbuf, sizeof(nbuf), "%s@,",
ents[i].id);
break;
case 's':
if (ents[i].str == ABSENT_STRING)
continue;
if (VALID_STRING(ents[i].str))
l = strlen(ents[i].id) +
outstr(NULL, ents[i].str) + 7;
else
l = strlen(ents[i].id) + 3;
break;
default:
errx(1, "invalid type");
}
if (col != SW) {
if (col + l > cols) {
printf("\n\t");
col = SW;
} else
col += printf(" ");
}
switch (ents[i].type) {
case 'f':
col += printf("%s", ents[i].id);
if (ents[i].flag == ABSENT_BOOLEAN ||
ents[i].flag == CANCELLED_BOOLEAN)
col += printf("@");
col += printf(",");
break;
case 'n':
col += printf("%s", nbuf);
break;
case 's':
col += printf("%s", ents[i].id);
if (VALID_STRING(ents[i].str)) {
col += printf("=");
col += outstr(stdout, ents[i].str);
} else
col += printf("@");
col += printf(",");
break;
}
}
printf("\n");
}
static size_t
load_ents(TIENT *ents, TERMINAL *t, char type)
{
size_t i, n, max;
TERMUSERDEF *ud;
switch (type) {
case 'f':
max = TIFLAGMAX;
break;
case 'n':
max = TINUMMAX;
break;
default:
max = TISTRMAX;
}
n = 0;
for (i = 0; i <= max; i++) {
switch (type) {
case 'f':
if (t->flags[i] == 1 ||
(aflag && t->flags[i] == CANCELLED_BOOLEAN))
{
ents[n].id = _ti_flagid(i);
ents[n].type = 'f';
ents[n++].flag = t->flags[i];
}
break;
case 'n':
if (VALID_NUMERIC(t->nums[i]) ||
(aflag && t->nums[i] == CANCELLED_NUMERIC))
{
ents[n].id = _ti_numid(i);
ents[n].type = 'n';
ents[n++].num = t->nums[i];
}
break;
default:
if (VALID_STRING(t->strs[i]) ||
(aflag && t->strs[i] == CANCELLED_STRING))
{
ents[n].id = _ti_strid(i);
ents[n].type = 's';
ents[n++].str = t->strs[i];
}
break;
}
}
if (xflag != 0 && t->_nuserdefs != 0) {
for (i = 0; i < t->_nuserdefs; i++) {
ud = &t->_userdefs[i];
if (ud->type == type) {
switch (type) {
case 'f':
if (!aflag &&
!VALID_BOOLEAN(ud->flag))
continue;
break;
case 'n':
if (!aflag &&
!VALID_NUMERIC(ud->num))
continue;
break;
case 's':
if (!aflag &&
!VALID_STRING(ud->str))
continue;
break;
}
ents[n].id = ud->id;
ents[n].type = ud->type;
ents[n].flag = ud->flag;
ents[n].num = ud->num;
ents[n++].str = ud->str;
}
}
}
qsort(ents, n, sizeof(TIENT), ent_compare);
return n;
}
static void
cprint_ent(TIENT *ent)
{
if (ent == NULL) {
if (qflag == 0)
printf("NULL");
else
printf("-");
}
switch (ent->type) {
case 'f':
if (VALID_BOOLEAN(ent->flag))
printf(ent->flag == 1 ? "T" : "F");
else if (qflag == 0)
printf("F");
else if (ent->flag == CANCELLED_BOOLEAN)
printf("@");
else
printf("-");
break;
case 'n':
if (VALID_NUMERIC(ent->num))
printf("%d", ent->num);
else if (qflag == 0)
printf("NULL");
else if (ent->num == CANCELLED_NUMERIC)
printf("@");
else
printf("-");
break;
case 's':
if (VALID_STRING(ent->str)) {
printf("'");
outstr(stdout, ent->str);
printf("'");
} else if (qflag == 0)
printf("NULL");
else if (ent->str == CANCELLED_STRING)
printf("@");
else
printf("-");
break;
}
}
static void
compare_ents(TIENT *ents1, size_t n1, TIENT *ents2, size_t n2)
{
size_t i1, i2;
TIENT *e1, *e2, ee;
int c;
i1 = i2 = 0;
ee.type = 'f';
ee.flag = ABSENT_BOOLEAN;
ee.num = ABSENT_NUMERIC;
ee.str = ABSENT_STRING;
while (i1 != n1 || i2 != n2) {
if (i1 == n1)
c = 1;
else if (i2 == n2)
c = -1;
else
c = strcmp(ents1[i1].id, ents2[i2].id);
if (c == 0) {
e1 = &ents1[i1++];
e2 = &ents2[i2++];
} else if (c < 0) {
e1 = &ents1[i1++];
e2 = ⅇ
ee.id = e1->id;
ee.type = e1->type;
} else {
e1 = ⅇ
e2 = &ents2[i2++];
ee.id = e2->id;
ee.type = e2->type;
}
switch (e1->type) {
case 'f':
if (cflag != 0) {
if (e1->flag == e2->flag)
printf("\t%s\n", ents1[i1].id);
continue;
}
if (e1->flag == e2->flag)
continue;
break;
case 'n':
if (cflag != 0) {
if (e1->num == e2->num)
printf("\t%s#%d\n",
ents1[i1].id, ents1[i1].num);
continue;
}
if (e1->num == e2->num)
continue;
break;
case 's':
if (cflag != 0) {
if (VALID_STRING(e1->str) &&
VALID_STRING(e2->str) &&
strcmp(e1->str, e2->str) == 0) {
printf("\t%s=", ents1[i1].id);
outstr(stdout, ents1[i1].str);
printf("\n");
}
continue;
}
if (VALID_STRING(e1->str) &&
VALID_STRING(e2->str) &&
strcmp(e1->str, e2->str) == 0)
continue;
break;
}
printf("\t%s: ", e1->id);
cprint_ent(e1);
if (e1->type == 'f')
printf(":");
else
printf(", ");
cprint_ent(e2);
printf(".\n");
}
}
static TERMINAL *
load_term(const char *name)
{
TERMINAL *t;
t = calloc(1, sizeof(*t));
if (t == NULL)
err(1, "calloc");
if (name == NULL)
name = getenv("TERM");
if (name == NULL)
name = "dumb";
if (_ti_getterm(t, name, 1) == 1)
return t;
if (_ti_database == NULL)
errx(1, "no terminal definition found in internal database");
else
errx(1, "no terminal definition found in %s.db", _ti_database);
}
static void
show_missing(TERMINAL *t1, TERMINAL *t2, char type)
{
ssize_t i, max;
const char *id;
switch (type) {
case 'f':
max = TIFLAGMAX;
break;
case 'n':
max = TINUMMAX;
break;
default:
max = TISTRMAX;
}
for (i = 0; i <= max; i++) {
switch (type) {
case 'f':
if (t1->flags[i] != ABSENT_BOOLEAN ||
t2->flags[i] != ABSENT_BOOLEAN)
continue;
id = _ti_flagid(i);
break;
case 'n':
if (t1->nums[i] != ABSENT_NUMERIC ||
t2->nums[i] != ABSENT_NUMERIC)
continue;
id = _ti_numid(i);
break;
default:
if (t1->strs[i] != ABSENT_STRING ||
t2->strs[i] != ABSENT_STRING)
continue;
id = _ti_strid(i);
break;
}
printf("\t!%s.\n", id);
}
}
static TERMUSERDEF *
find_userdef(TERMINAL *term, const char *id)
{
size_t i;
for (i = 0; i < term->_nuserdefs; i++)
if (strcmp(term->_userdefs[i].id, id) == 0)
return &term->_userdefs[i];
return NULL;
}
static void
use_terms(TERMINAL *term, size_t nuse, char **uterms)
{
TERMINAL **terms;
TERMUSERDEF *ud, *tud;
size_t i, j, agree, absent, data;
terms = malloc(sizeof(**terms) * nuse);
if (terms == NULL)
err(1, "malloc");
for (i = 0; i < nuse; i++) {
if (strcmp(term->name, *uterms) == 0)
errx(1, "cannot use same terminal");
for (j = 0; j < i; j++)
if (strcmp(terms[j]->name, *uterms) == 0)
errx(1, "cannot use same terminal");
terms[i] = load_term(*uterms++);
}
for (i = 0; i < TIFLAGMAX + 1; i++) {
agree = absent = data = 0;
for (j = 0; j < nuse; j++) {
if (terms[j]->flags[i] == ABSENT_BOOLEAN ||
terms[j]->flags[i] == CANCELLED_BOOLEAN)
absent++;
else {
data++;
if (term->flags[i] == terms[j]->flags[i])
agree++;
}
}
if (data == 0)
continue;
if (agree > 0 && agree + absent == nuse)
term->flags[i] = ABSENT_BOOLEAN;
else if (term->flags[i] == ABSENT_BOOLEAN)
term->flags[i] = CANCELLED_BOOLEAN;
}
for (i = 0; i < TINUMMAX + 1; i++) {
agree = absent = data = 0;
for (j = 0; j < nuse; j++) {
if (terms[j]->nums[i] == ABSENT_NUMERIC ||
terms[j]->nums[i] == CANCELLED_NUMERIC)
absent++;
else {
data++;
if (term->nums[i] == terms[j]->nums[i])
agree++;
}
}
if (data == 0)
continue;
if (agree > 0 && agree + absent == nuse)
term->nums[i] = ABSENT_NUMERIC;
else if (term->nums[i] == ABSENT_NUMERIC)
term->nums[i] = CANCELLED_NUMERIC;
}
for (i = 0; i < TISTRMAX + 1; i++) {
agree = absent = data = 0;
for (j = 0; j < nuse; j++) {
if (terms[j]->strs[i] == ABSENT_STRING ||
terms[j]->strs[i] == CANCELLED_STRING)
absent++;
else {
data++;
if (VALID_STRING(term->strs[i]) &&
strcmp(term->strs[i],
terms[j]->strs[i]) == 0)
agree++;
}
}
if (data == 0)
continue;
if (agree > 0 && agree + absent == nuse)
term->strs[i] = ABSENT_STRING;
else if (term->strs[i] == ABSENT_STRING)
term->strs[i] = CANCELLED_STRING;
}
/* User defined caps are more tricky.
First we set any to absent that agree. */
for (i = 0; i < term->_nuserdefs; i++) {
agree = absent = data = 0;
ud = &term->_userdefs[i];
for (j = 0; j < nuse; j++) {
tud = find_userdef(terms[j], ud->id);
if (tud == NULL)
absent++;
else {
data++;
switch (ud->type) {
case 'f':
if (tud->type == 'f' &&
tud->flag == ud->flag)
agree++;
break;
case 'n':
if (tud->type == 'n' &&
tud->num == ud->num)
agree++;
break;
case 's':
if (tud->type == 's' &&
VALID_STRING(tud->str) &&
VALID_STRING(ud->str) &&
strcmp(ud->str, tud->str) == 0)
agree++;
break;
}
}
}
if (data == 0)
continue;
if (agree > 0 && agree + absent == nuse) {
ud->flag = ABSENT_BOOLEAN;
ud->num = ABSENT_NUMERIC;
ud->str = ABSENT_STRING;
}
}
/* Now add any that we don't have as cancelled */
for (i = 0; i < nuse; i++) {
for (j = 0; j < terms[i]->_nuserdefs; j++) {
ud = find_userdef(term, terms[i]->_userdefs[j].id);
if (ud != NULL)
continue; /* We have handled this */
term->_userdefs = realloc(term->_userdefs,
sizeof(*term->_userdefs) * (term->_nuserdefs + 1));
if (term->_userdefs == NULL)
err(1, "malloc");
tud = &term->_userdefs[term->_nuserdefs++];
tud->id = terms[i]->_userdefs[j].id;
tud->type = terms[i]->_userdefs[j].flag;
tud->flag = CANCELLED_BOOLEAN;
tud->num = CANCELLED_NUMERIC;
tud->str = CANCELLED_STRING;
}
}
}
int
main(int argc, char **argv)
{
char *term, *Barg;
int ch, uflag;
TERMINAL *t, *t2;
size_t n, n2;
struct winsize ws;
TIENT ents[TISTRMAX + 1], ents2[TISTRMAX + 1];
cols = 80; /* default */
term = getenv("COLUMNS");
if (term != NULL)
cols = strtoul(term, NULL, 10);
else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0)
cols = ws.ws_col;
uflag = xflag = 0;
Barg = NULL;
while ((ch = getopt(argc, argv, "1A:B:acnquw:x")) != -1)
switch (ch) {
case '1':
cols = 1;
break;
case 'A':
setdb(optarg);
break;
case 'B':
Barg = optarg;
break;
case 'a':
aflag = 1;
break;
case 'c':
cflag = 1;
break;
case 'n':
nflag = 1;
break;
case 'q':
qflag = 1;
break;
case 'u':
uflag = 1;
aflag = 1;
break;
case 'w':
cols = strtoul(optarg, NULL, 10);
break;
case 'x':
xflag = 1;
break;
case '?':
default:
fprintf(stderr,
"usage: %s [-1acnqux] [-A database] [-B database] "
"[-w cols] [term]\n",
getprogname());
return EXIT_FAILURE;
}
cols--;
if (optind + 1 < argc)
aflag = 1;
if (optind < argc)
term = argv[optind++];
else
term = NULL;
t = load_term(term);
if (uflag != 0)
use_terms(t, argc - optind, argv + optind);
if ((optind + 1 != argc && nflag == 0) || uflag != 0) {
if (uflag == 0) {
printf("# Reconstructed from ");
if (_ti_database == NULL)
printf("internal database\n");
else
printf("%s%s\n", _ti_database,
*_ti_database == '/' ? ".cdb" : "");
}
printf("%s", t->name);
if (t->_alias != NULL && *t->_alias != '\0')
printf("|%s", t->_alias);
if (t->desc != NULL && *t->desc != '\0')
printf("|%s", t->desc);
printf(",\n");
n = load_ents(ents, t, 'f');
print_ent(ents, n);
n = load_ents(ents, t, 'n');
print_ent(ents, n);
n = load_ents(ents, t, 's');
print_ent(ents, n);
if (uflag != 0) {
printf("\t");
n = SW;
for (; optind < argc; optind++) {
n2 = 5 + strlen(argv[optind]);
if (n != SW) {
if (n + n2 > cols) {
printf("\n\t");
n = SW;
} else
n += printf(" ");
}
n += printf("use=%s,", argv[optind]);
}
printf("\n");
}
return EXIT_SUCCESS;
}
if (Barg == NULL)
unsetenv("TERMINFO");
else
setdb(Barg);
t2 = load_term(argv[optind++]);
printf("comparing %s to %s.\n", t->name, t2->name);
if (qflag == 0)
printf(" comparing booleans.\n");
if (nflag == 0) {
n = load_ents(ents, t, 'f');
n2 = load_ents(ents2, t2, 'f');
compare_ents(ents, n, ents2, n2);
} else
show_missing(t, t2, 'f');
if (qflag == 0)
printf(" comparing numbers.\n");
if (nflag == 0) {
n = load_ents(ents, t, 'n');
n2 = load_ents(ents2, t2, 'n');
compare_ents(ents, n, ents2, n2);
} else
show_missing(t, t2, 'n');
if (qflag == 0)
printf(" comparing strings.\n");
if (nflag == 0) {
n = load_ents(ents, t, 's');
n2 = load_ents(ents2, t2, 's');
compare_ents(ents, n, ents2, n2);
} else
show_missing(t, t2, 's');
return EXIT_SUCCESS;
}
|
pythonpeixun/algo-1
|
trees/splay/splay.c
|
#include "splay.h"
struct SplayTreeNode
{
ET Element;
Splay Left;
Splay Right;
};
Splay
makeEmpty(Splay T)
{
if (T != NULL)
{
makeEmpty(T->Left);
makeEmpty(T->Right);
free(T);
}
numRotations = 0;
return NULL;
}
static Position
zigLeft(Splay T)
{
Position tmp = T->Left->Right;
Position elem = T->Left;
elem->Right = T;
T->Left = tmp;
numRotations++;
return elem;
}
static Position
zigRight(Splay T)
{
Position tmp = T->Right->Left;
Position elem = T->Right;
elem->Left = T;
T->Right = tmp;
numRotations++;
return elem;
}
static Position
zigzigLeft(Splay T)
{
T = zigLeft(T);
T = zigLeft(T);
return T;
}
static Position
zigzigRight(Splay T)
{
T = zigRight(T);
T = zigRight(T);
return T;
}
static Position
zigzagLeft(Splay T)
{
T->Left = zigRight(T->Left);
T = zigLeft(T);
return T;
}
static Position
zigzagRight(Splay T)
{
T->Right = zigLeft(T->Right);
T = zigRight(T);
return T;
}
/*
* This routine brings the elem to the root if find. If the elem is not in the tree,
* bring the last accessed item to the root. Returns the root of the newly modified tree.
*/
// Case refers to: http://www.cs.cmu.edu/afs/cs/academic/class/15859-f05/www/documents/splay-trees.txt
static Position
splaying(ET elem, Splay T)
{
if (T == NULL || T->Element == elem)
return T;
if (elem < T->Element) // elem in the left subtree
{
if (T->Left == NULL) // elem is not in the tree
return T;
if (elem < T->Left->Element) // Zig-Zig case (left)
{
T->Left->Left = find(elem, T->Left->Left); // recursively bring the key as root of left-left
T = zigzigLeft(T);
}
else if (elem > T->Left->Element) // Zig-Zag case (left)
{
T->Left->Right = find(elem, T->Left->Right);
T = zigzagLeft(T);
}
else // Zig case (left)
{
T->Left = find(elem, T->Left);
T = zigLeft(T);
}
return T;
}
else // elem in the right subtree
{
if (T->Right == NULL)
return T;
if (elem > T->Right->Element) // Zig-Zig case (right)
{
T->Right->Right = find(elem, T->Right->Right);
T = zigzigRight(T);
}
else if (elem < T->Right->Element) // Zig-Zag case (right)
{
T->Right->Left = find(elem, T->Right->Left);
T = zigzagRight(T);
}
else // Zig case (right)
{
T->Right = find(elem, T->Right);
T = zigRight(T);
}
return T;
}
}
Position
find(ET elem, Splay T)
{
return splaying(elem, T);
}
Position
findMin(Splay T)
{
if (T == NULL)
return NULL;
else if (T->Left == NULL)
{
T = find(T->Element, T);
return T;
}
else
return findMin(T->Left);
}
Position
findMax(Splay T)
{
if (T != NULL)
while (T->Right != NULL)
T = T->Right;
T = splaying(T->Element, T);
return T;
}
static Position
newNode(ET elem)
{
Position T = malloc(sizeof(struct SplayTreeNode));
T->Left = T->Right = NULL;
T->Element = elem;
return T;
}
// Split way to implement: http://courses.cs.washington.edu/courses/cse326/01au/lectures/SplayTrees.ppt
Splay
insert(ET elem, Splay T)
{
if (T == NULL) // If tree is empty
{
T = newNode(elem);
return T;
}
T = splaying(elem, T);
if (T->Element == elem) // if elem is already present, then return
return T;
Position newT = newNode(elem);
if (elem < T->Element)
{
newT->Right = T;
newT->Left = T->Left; // we can do this b/c the result of splaying is the parent node of where we should insert.
T->Left = NULL;
}
else
{
newT->Left = T;
newT->Right = T->Right;
T->Right = NULL;
}
return newT;
}
static Splay
BSTinsert(ET elem, Splay T)
{
if (T == NULL)
{
T = malloc(sizeof(struct SplayTreeNode));
T->Left = T->Right = NULL;
T->Element = elem;
}
else if (elem < T->Element)
T->Left = BSTinsert(elem, T->Left);
else if (elem > T->Element)
T->Right = BSTinsert(elem, T->Right);
return T;
}
// do ordinary binary tree insertion, and then simply splay the item to the root.
Splay
insert2(ET elem, Splay T)
{
T = BSTinsert(elem, T);
return splaying(elem, T);
}
// We can perform deletion by accessing the node to be deleted.
// This put the node at the root. If it is deleted, we get two
// subtrees T_L and T_R (left and right). If we find the largest
// element in T_L (which is easy), then this element is rotated to
// the root of T_L and T_L will now have a root with no right child.
// We can finish the deletion by making T_R the right child.
Splay
delete(ET elem, Splay T)
{
T = find(elem, T);
Position LeftSubTree = T->Left;
Position RightSubTree = T->Right;
free(T);
T = findMax(LeftSubTree);
T->Right = RightSubTree;
return T;
}
static Position
BSTfindMin(Splay T)
{
if (T != NULL)
while(T->Left != NULL)
T = T->Left;
return T;
}
// We do normal deletion as BST, then we
// splay the parent node of the deletion point to the root
Splay
delete2(ET elem, Splay T)
{
Position tmp;
if (T == NULL)
fatal("No such element in splay tree");
if (elem < T->Element)
{
T->Left = delete2(elem, T->Left);
T = zigLeft(T);
}
else if (elem > T->Element)
{
T->Right = delete2(elem, T->Right);
T = zigRight(T);
}
else if (T->Left != NULL && T->Right != NULL)
{
tmp = BSTfindMin(T->Right);
T->Element = tmp->Element;
T->Right = delete2(T->Element, T->Right);
}
else
{
tmp = T;
if (T->Left == NULL)
T = T->Right;
else if (T->Right == NULL)
T = T->Left;
free(tmp);
}
return T;
}
ET
retrieve(Position T)
{
if (T != NULL)
return T->Element;
return 0;
}
int
getNumRotations()
{
return numRotations;
}
Splay
initializeBST(ET* array, int arrayLength)
{
Splay T = NULL;
int i;
for(i = 0; i < arrayLength; i++)
T = BSTinsert(array[i], T);
return T;
}
static void
bst_print_dot_aux(Splay T, FILE* stream)
{
if (T != NULL)
{
if (T->Left != NULL)
{
fprintf(stream, "%d->%d;\n", T->Element, T->Left->Element);
bst_print_dot_aux(T->Left, stream);
}
if (T->Right != NULL)
{
fprintf(stream, "%d->%d;\n", T->Element, T->Right->Element);
bst_print_dot_aux(T->Right, stream);
}
}
}
void
bst_print_dot(Splay T, FILE* stream)
{
fprintf(stream, "digraph SplayTree \{\n");
bst_print_dot_aux(T, stream);
fprintf(stream,"}\n");
}
|
Ortheore/BizHawk
|
waterbox/ares64/ares/ares/n64/controller/gamepad/mbc/mbc.hpp
|
<filename>waterbox/ares64/ares/ares/n64/controller/gamepad/mbc/mbc.hpp
struct Mbc {
explicit Mbc(Memory::Readable& rom_, Memory::Writable& ram_) : rom(rom_), ram(ram_) {}
virtual auto reset() -> void {};
virtual auto read(u16 address) -> u8 { return 0xFF; };
virtual auto write(u16 address, u8 data) -> void {};
protected:
Memory::Readable& rom;
Memory::Writable& ram;
};
#include "mbc1.hpp"
#include "mbc3.hpp"
#include "mbc5.hpp"
|
rusticpenguin/opensphere
|
src/os/histo/result.js
|
goog.provide('os.histo.Result');
/**
* @typedef {{
* key: (string|number),
* value: !os.histo.Bin.<T>
* }}
*/
os.histo.Result;
|
emil-wcislo/sbql4j8
|
sbql4j8/src/test/openjdk/tools/javap/4870651/Test.java
|
/*
* Copyright (c) 2008, Oracle and/or its affiliates. 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.
*
* 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.*;
abstract class Test<T,E extends Exception & Comparable<T>,U extends Comparable> {
T t;
Test(T t) { }
<G> Test(G g, int i) { }
Test(String... args) { }
Test(int i, Object[]... args) { }
abstract void v1(String... args);
abstract void v2(int i, String[]... args);
abstract void a1(int x);
abstract void a2(int[] x);
abstract void a3(T x);
abstract void a4(T[] x);
abstract int r1();
abstract int[] r2();
abstract T r3();
abstract T[] r4();
abstract <G> void ga1(int x);
abstract <G> void ga2(int[] x);
abstract <G> void ga3(G x);
abstract <G> void ga4(G[] x);
abstract <G> int gr1();
abstract <G> int[] gr2();
abstract <G> G gr3();
abstract <G> G[] gr4();
abstract <G extends Exception> void ge() throws G;
abstract void w(List<?> l);
abstract void we(List<? extends T> l);
abstract void ws(List<? super T> l);
abstract void t1() throws Error;
abstract void t2() throws E;
abstract void t3() throws E,Error;
abstract void i1(Test<T, E, Comparable> x);
abstract void i3(Test<T, E, Comparable>.Inner<String> x);
class Inner<Q> { }
class Inner2<Q> extends Inner<Q> { }
class Simple { }
enum Enum { e1, e2, e3 }
}
|
JakobBruenker/ghc
|
rts/ProfHeapInternal.h
|
<reponame>JakobBruenker/ghc<filename>rts/ProfHeapInternal.h
/* -----------------------------------------------------------------------------
*
* (c) The GHC Team, 2019
*
* Internal definitions for subordinate heap profilers to consume
*
* ---------------------------------------------------------------------------*/
#pragma once
#include "Hash.h"
#include "Arena.h"
#include "BeginPrivate.h"
/* -----------------------------------------------------------------------------
* Counters
*
* For most heap profiles each closure identity gets a simple count
* of live words in the heap at each census. However, if we're
* selecting by biography, then we have to keep the various
* lag/drag/void counters for each identity.
* -------------------------------------------------------------------------- */
typedef struct _counter {
const void *identity;
union {
ssize_t resid;
struct {
// Total sizes of:
ssize_t prim; // 'inherently used' closures
ssize_t not_used; // 'never used' closures
ssize_t used; // 'used at least once' closures
ssize_t void_total; // 'destroyed without being used' closures
ssize_t drag_total; // 'used at least once and waiting to die'
} ldv;
} c;
struct _counter *next;
} counter;
typedef struct {
double time; // the time in MUT time when the census is made
StgWord64 rtime; // The eventlog time the census was made. This is used
// for the LDV profiling events because they are all
// emitted at the end of compilation so we need to know
// when the sample actually took place.
HashTable * hash;
counter * ctrs;
Arena * arena;
// for LDV profiling, when just displaying by LDV
ssize_t prim;
ssize_t not_used;
ssize_t used;
ssize_t void_total;
ssize_t drag_total;
} Census;
void initLDVCtr(counter *ctr);
counter* heapInsertNewCounter(Census *census, StgWord identity);
#include "EndPrivate.h"
|
bruceyee07/leetcode-medium
|
48. Rotate Image/other.java
|
<gh_stars>0
/**
* https://leetcode.com/problems/rotate-image/
* https://leetcode.com/problems/rotate-image/discuss/18879/AC-Java-in-place-solution-with-explanation-Easy-to-understand.
*/
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = temp;
}
}
}
}
The idea was firstly transpose the matrix and then flip it symmetrically. For instance,
1 2 3
4 5 6
7 8 9
after transpose, it will be swap(matrix[i][j], matrix[j][i])
1 4 7
2 5 8
3 6 9
Then flip the matrix horizontally. (swap(matrix[i][j], matrix[i][matrix.length-1-j])
7 4 1
8 5 2
9 6 3
|
iSergio/ol4gwt
|
ol4gwt-main/src/main/java/org/openlayers/ol/source/Source.java
|
<reponame>iSergio/ol4gwt<gh_stars>1-10
/*
* Copyright 2017 iserge.
*
* 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.openlayers.ol.source;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsType;
import org.openlayers.ol.Attribution;
import org.openlayers.ol.Object;
import org.openlayers.ol.proj.Projection;
import org.openlayers.ol.source.options.SourceOptions;
import org.openlayers.olx.LogoOptions;
/**
* Abstract base class; normally only used for creating subclasses and not instantiated in apps.
* Base class for {@link org.openlayers.ol.layer.Layer} sources.
*
* A generic change event is triggered when the state of the source changes.
* @author <NAME> aka iSergio <<EMAIL>>
*/
@JsType(isNative = true, namespace = "ol.source", name = "Source")
public abstract class Source extends Object {
@JsConstructor
protected Source() {}
@JsConstructor
protected Source(SourceOptions options) {}
/**
* Get the attributions of the source.
* @return Attributions.
*/
@JsMethod
public native Attribution[] getAttributions();
/**
* Get the logo of the source.
* @return Logo.
*/
@JsMethod
public native String getLogo();
/**
* Get the logo of the source.
* @return Logo.
*/
@JsMethod
public native LogoOptions getLogoOptions();
/**
* Get the projection of the source.
* @return Projection.
*/
@JsMethod
public native Projection getProjection();
/**
* Get the state of the source, see ol.source.State for possible states.
* @return State.
*/
@JsMethod
public native String getState();
/**
* Refreshes the source and finally dispatches a 'change' event.
*/
@JsMethod
public native void refresh();
/**
* Set the attributions of the source.
* @param attributions Attributions. Can be passed as string, Array<string>, ol.Attribution, Array<ol.Attribution> or undefined.
*/
@JsMethod
public native void setAttributions(Attribution[] attributions);
}
|
gauravssnl/Data-Structures-and-Algorithms
|
java/stacks/ArrayStack.java
|
package stacks;
import java.util.Arrays;
public class ArrayStack<E> implements Stack<E> {
public static final int CAPACITY = 1000; // default array capacity
private E[] data; // generic array used for storage
private int t = -1; // index of the top element in the stack
// construct stack with default capacity
public ArrayStack() {
this(CAPACITY);
}
// construct stack with given capacity
public ArrayStack(int capacity) {
data = (E[]) new Object[capacity]; // safe cast; compiler may give warning
}
@Override
public int size() {
return t + 1; // intial value of t is -1 and size is 0
}
@Override
public boolean isEmpty() {
return t == -1;
}
@Override
public void push(E e) throws IllegalArgumentException {
if (size() == data.length)
throw new IllegalArgumentException("Stack is full");
data[++t] = e; // increment t before saving new item
}
@Override
public E top() {
if (isEmpty())
return null;
return data[t]; // top element is at index t
}
@Override
public E pop() {
if (isEmpty())
return null;
E answer = top();
data[t] = null; // dereference to help garbage collection
t--;
return answer;
}
@Override
public String toString() {
// need to slice the original data with the data contained in it
return "ArrayStack [data=" + Arrays.toString(Arrays.copyOf(data, size())) + ", top Index=" + t + "]";
}
}
|
OrionDevelopment/Multi-Platform-Template
|
Platforms/Forge/src/main/java/mod/modid/forge/platform/entity/ForgeEntityInformationManager.java
|
<filename>Platforms/Forge/src/main/java/mod/modid/forge/platform/entity/ForgeEntityInformationManager.java
package mod.modid.forge.platform.entity;
import mod.modid.platforms.core.entity.IEntityInformationManager;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.ForgeMod;
public class ForgeEntityInformationManager implements IEntityInformationManager
{
private static final ForgeEntityInformationManager INSTANCE = new ForgeEntityInformationManager();
public static ForgeEntityInformationManager getInstance()
{
return INSTANCE;
}
private ForgeEntityInformationManager()
{
}
@Override
public double getReachDistance(final Player player)
{
final AttributeInstance reachAttribute = player.getAttribute(ForgeMod.REACH_DISTANCE.get());
if (reachAttribute == null)
{
return player.isCreative() ? 5f : 4.5f;
}
final double reachAttributeValue = reachAttribute.getValue();
return player.isCreative() ? reachAttributeValue : reachAttributeValue - 0.5D;
}
}
|
mtsar/mtsar
|
src/main/java/mtsar/views/DashboardView.java
|
<gh_stars>10-100
/*
* Copyright 2015 <NAME>
*
* 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 mtsar.views;
import io.dropwizard.views.View;
import mtsar.MechanicalTsarVersion;
import mtsar.api.Stage;
import mtsar.api.sql.AnswerDAO;
import mtsar.api.sql.TaskDAO;
import mtsar.api.sql.WorkerDAO;
import java.util.Map;
import static java.util.Objects.requireNonNull;
public class DashboardView extends View {
private final MechanicalTsarVersion version;
private final Map<String, Stage> stages;
private final TaskDAO taskDAO;
private final WorkerDAO workerDAO;
private final AnswerDAO answerDAO;
public DashboardView(MechanicalTsarVersion version, Map<String, Stage> stages, TaskDAO taskDAO, WorkerDAO workerDAO, AnswerDAO answerDAO) {
super("dashboard.mustache");
this.version = requireNonNull(version);
this.stages = requireNonNull(stages);
this.taskDAO = requireNonNull(taskDAO);
this.workerDAO = requireNonNull(workerDAO);
this.answerDAO = requireNonNull(answerDAO);
}
@SuppressWarnings({"unused", "SameReturnValue"})
public String getTitle() {
return "Dashboard";
}
@SuppressWarnings("unused")
public String getVersion() {
return version.getVersion();
}
@SuppressWarnings("unused")
public String getJvm() {
return System.getProperty("java.runtime.version");
}
@SuppressWarnings("unused")
public int getStageCount() {
return stages.size();
}
@SuppressWarnings("unused")
public int getWorkerCount() {
return stages.values().stream().
map(stage -> workerDAO.count(stage.getId())).
reduce(0, (r, e) -> r + e);
}
@SuppressWarnings("unused")
public int getTaskCount() {
return stages.values().stream().
map(stage -> taskDAO.count(stage.getId())).
reduce(0, (r, e) -> r + e);
}
@SuppressWarnings("unused")
public int getAnswerCount() {
return stages.values().stream().
map(stage -> answerDAO.count(stage.getId())).
reduce(0, (r, e) -> r + e);
}
}
|
supervueman/vn-cms
|
server/core/modules/profile/controller/changePassword.js
|
const Model = require('../../user/model');
const bcrypt = require('bcrypt');
module.exports = async (req, res) => {
// Находим профиль
const profile = await Model.findByPk(req.id);
if (!profile) {
logger('error', 'profile', 404, 'changePassword.js');
sendRes({ res, status: 404 });
}
// Сверяем пароли
const isCompare = await bcrypt.compare(
req.body.oldPassword,
profile.password
);
if (!isCompare) {
logger('error', 'profile', 401, 'changePassword.js');
sendRes({ res, status: 401 });
} else {
const hashPw = await bcrypt.hash(req.body.newPassword, 12);
await profile.update({
password: <PASSWORD>
});
sendRes({ res, status: 200 });
}
};
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/CoreChineseEngine/CIMInputController.h
|
<gh_stars>10-100
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "IMKCandidateBasedInputController.h"
#import "CIMMenuControllerDataSource.h"
@class CIMBaseEngine, IMKKeyboardInputController, NSString;
@interface CIMInputController : IMKCandidateBasedInputController <CIMMenuControllerDataSource>
{
IMKKeyboardInputController *_keyboardInputController;
Class _engineClass;
CIMBaseEngine *_inputModeEngine;
}
@property(retain, nonatomic) CIMBaseEngine *inputModeEngine; // @synthesize inputModeEngine=_inputModeEngine;
@property(retain, nonatomic) Class engineClass; // @synthesize engineClass=_engineClass;
@property(retain, nonatomic) IMKKeyboardInputController *keyboardInputController; // @synthesize keyboardInputController=_keyboardInputController;
- (void).cxx_destruct;
- (void)radarButtonPressed;
- (void)setInputMode:(id)arg1 client:(id)arg2;
- (void)menuItemAction:(id)arg1;
@property(readonly) unsigned long long scriptType;
- (id)inlineText;
- (void)didSelectSortingMode:(id)arg1 candidateController:(id)arg2;
- (void)candidateSelectionChanged:(id)arg1 candidateController:(id)arg2;
- (void)candidateSelected:(id)arg1 candidateController:(id)arg2;
@property(readonly, nonatomic) BOOL windowIsHorizontal;
- (unsigned long long)optionsForMenuController:(id)arg1;
- (id)selectedStringForMenuController:(id)arg1;
- (BOOL)selectionShouldBeReflectedInTouchBar;
- (void)didHideCandidates:(id)arg1;
- (id)makeScrubbingCandidateController;
- (void)updateCandidateController:(id)arg1;
- (id)makeCandidateController;
- (BOOL)mouseMovedOnCharacterIndex:(unsigned long long)arg1 coordinate:(struct CGPoint)arg2 withModifier:(unsigned long long)arg3 client:(id)arg4;
- (BOOL)mouseUpOnCharacterIndex:(unsigned long long)arg1 coordinate:(struct CGPoint)arg2 withModifier:(unsigned long long)arg3 client:(id)arg4;
- (BOOL)mouseDownOnCharacterIndex:(unsigned long long)arg1 coordinate:(struct CGPoint)arg2 withModifier:(unsigned long long)arg3 continueTracking:(char *)arg4 client:(id)arg5;
- (unsigned long long)recognizedEvents:(id)arg1;
- (void)setValue:(id)arg1 forTag:(long long)arg2 client:(id)arg3;
- (void)deactivateServer:(id)arg1;
- (void)activateServer:(id)arg1;
- (id)candidates:(id)arg1;
- (void)commitComposition:(id)arg1;
- (BOOL)handleEvent:(id)arg1 client:(id)arg2;
- (BOOL)inputText:(id)arg1 client:(id)arg2;
- (BOOL)didCommandBySelector:(SEL)arg1 client:(id)arg2;
- (BOOL)isUsingSortingBar;
- (id)informationView;
- (BOOL)automaticallyRestrictLayoutToPrimaryCandidateControllerLayout;
- (void)inputControllerWillClose;
- (id)menu;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
FrKaram/alfresco-android-app
|
platform/foundation/src/main/java/org/alfresco/mobile/android/api/model/config/impl/ActionHelper.java
|
<gh_stars>10-100
/*******************************************************************************
* Copyright (C) 005-014 Alfresco Software Limited.
*
* This file is part of the Alfresco Mobile SDK.
*
* Licensed under the Apache License, Version .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-.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.alfresco.mobile.android.api.model.config.impl;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.alfresco.mobile.android.api.model.config.ActionConfig;
import org.alfresco.mobile.android.api.model.config.ConfigConstants;
import org.alfresco.mobile.android.api.model.config.ConfigConstants.ActionConfigType;
import org.alfresco.mobile.android.api.model.config.ConfigScope;
import org.alfresco.mobile.android.api.model.config.GroupConfig;
import org.alfresco.mobile.android.api.model.config.ViewGroupConfig;
import org.apache.chemistry.opencmis.commons.impl.JSONConverter;
/**
* @author <NAME>
*/
public class ActionHelper extends HelperConfig
{
private LinkedHashMap<String, Object> jsonActionConfigGroups;
private LinkedHashMap<String, ActionConfig> actionConfigIndex;
private LinkedHashMap<String, ActionConfig> actionIdIndex;
// ///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
// ///////////////////////////////////////////////////////////////////////////
ActionHelper(ConfigurationImpl context, StringHelper localHelper)
{
super(context, localHelper);
}
ActionHelper(ConfigurationImpl context, StringHelper localHelper,
LinkedHashMap<String, ActionConfig> ActionConfigIndex)
{
super(context, localHelper);
this.actionConfigIndex = ActionConfigIndex;
}
// ///////////////////////////////////////////////////////////////////////////
// INIT
// ///////////////////////////////////////////////////////////////////////////
void addActions(Map<String, Object> views)
{
actionConfigIndex = new LinkedHashMap<>(views.size());
actionIdIndex = new LinkedHashMap<>(views.size());
ActionConfig actionConfig;
for (Entry<String, Object> entry : views.entrySet())
{
actionConfig = parse(JSONConverter.getMap(entry.getValue()), entry.getKey());
if (actionConfig == null)
{
continue;
}
actionConfigIndex.put(actionConfig.getType(), actionConfig);
actionIdIndex.put(actionConfig.getIdentifier(), actionConfig);
}
}
void addActionGroups(List<Object> viewsGroup)
{
jsonActionConfigGroups = new LinkedHashMap<>(viewsGroup.size());
String viewGroupId;
for (Object object : viewsGroup)
{
viewGroupId = JSONConverter.getString(JSONConverter.getMap(object), ConfigConstants.ID_VALUE);
if (viewGroupId == null)
{
continue;
}
jsonActionConfigGroups.put(viewGroupId, object);
}
}
// ///////////////////////////////////////////////////////////////////////////
// METHODS
// ///////////////////////////////////////////////////////////////////////////
public boolean hasActionConfig()
{
return ((jsonActionConfigGroups != null && !jsonActionConfigGroups.isEmpty())
|| (actionConfigIndex != null && !actionConfigIndex.isEmpty()));
}
public ActionConfig getActionByType(String id)
{
return getActionByType(id, null);
}
public ActionConfig getActionByType(String id, ConfigScope scope)
{
return retrieveConfig(id, scope);
}
protected ActionConfig retrieveConfig(String id, ConfigScope scope)
{
ActionConfigImpl config = null;
if (jsonActionConfigGroups != null && jsonActionConfigGroups.containsKey(id))
{
config = (ActionConfigImpl) parse(JSONConverter.getMap(jsonActionConfigGroups.get(id)), id);
}
else if (actionConfigIndex != null && actionConfigIndex.containsKey(id))
{
config = (ActionConfigImpl) actionConfigIndex.get(id);
}
else if (actionIdIndex != null && actionIdIndex.containsKey(id))
{
config = (ActionConfigImpl) actionIdIndex.get(id);
}
else
{
return null;
}
// Evaluate
if (getEvaluatorHelper() == null)
{
return (config.getEvaluator() == null) ? config : null;
}
else
{
if (!getEvaluatorHelper().evaluate(config.getEvaluator(), scope)) { return null; }
if (config instanceof ActionGroupConfigImpl && ((ActionGroupConfigImpl) config).getItems() != null
&& ((ActionGroupConfigImpl) config).getItems().size() > 0)
{
((ActionGroupConfigImpl) config)
.setChildren(evaluateChildren(((ActionGroupConfigImpl) config).getItems()));
}
}
return config;
}
@SuppressWarnings("unchecked")
private ArrayList<ActionConfig> evaluateChildren(List<ActionConfig> listConfig)
{
if (listConfig == null) { return new ArrayList<>(0); }
ArrayList<ActionConfig> evaluatedViews = new ArrayList<>(listConfig.size());
boolean addViewAsChild = true;
for (ActionConfig ActionConfig : listConfig)
{
if (getEvaluatorHelper() == null)
{
addViewAsChild = (((ActionConfigImpl) ActionConfig).getEvaluator() == null);
}
else if (!getEvaluatorHelper().evaluate(((ActionConfigImpl) ActionConfig).getEvaluator(), null))
{
addViewAsChild = false;
}
if (addViewAsChild)
{
evaluatedViews.add(ActionConfig);
if (ActionConfig instanceof ViewGroupConfig
&& ((GroupConfig<ActionConfig>) ActionConfig).getItems() != null
&& ((GroupConfig<ActionConfig>) ActionConfig).getItems().size() > 0)
{
((ActionGroupConfigImpl) ActionConfig)
.setChildren(evaluateChildren(((ActionGroupConfigImpl) ActionConfig).getItems()));
}
}
addViewAsChild = true;
}
return evaluatedViews;
}
// ///////////////////////////////////////////////////////////////////////////
// V1.0
// ///////////////////////////////////////////////////////////////////////////
protected ActionConfig parse(Object object)
{
if (object instanceof Map)
{
Map<String, Object> viewMap = JSONConverter.getMap(object);
if (viewMap.containsKey(ConfigConstants.ITEM_TYPE_VALUE))
{
ActionConfigType type = ActionConfigType
.fromValue(JSONConverter.getString(viewMap, ConfigConstants.ITEM_TYPE_VALUE));
if (type == null)
{
type = ActionConfigType.ACTION;
}
switch (type)
{
case ACTION_ID:
// View is defined inside the views registry
return getActionByType(JSONConverter.getString(viewMap, ActionConfigType.ACTION_ID.value()));
case ACTION_GROUP_ID:
// View is defined inside the view group registry
return getActionByType(
JSONConverter.getString(viewMap, ActionConfigType.ACTION_GROUP_ID.value()));
case ACTION:
default:
// inline definition
return parse(
JSONConverter.getMap(JSONConverter.getMap(object).get(ConfigConstants.VIEW_VALUE)));
}
}
else
{
return parse(JSONConverter.getMap(object), null);
}
}
else if (object instanceof String)
{
return getActionByType((String) object);
}
else
{
return null;
}
}
protected ActionConfig parse(Map<String, Object> json, String identifier)
{
ItemConfigData data = new ItemConfigData(identifier, json, getConfiguration());
// Enable
Boolean isEnable = true;
if (json.containsKey(ConfigConstants.ENABLE_VALUE))
{
isEnable = JSONConverter.getBoolean(json, ConfigConstants.ENABLE_VALUE);
}
if (isEnable == null)
{
isEnable = true;
}
// Check if it's a group view
LinkedHashMap<String, ActionConfig> childrenIndex = null;
if (json.containsKey(ConfigConstants.ITEMS_VALUE))
{
List<Object> childrenObject = JSONConverter.getList(json.get(ConfigConstants.ITEMS_VALUE));
LinkedHashMap<String, ActionConfig> childrenActionConfig = new LinkedHashMap<>(childrenObject.size());
ActionConfig ActionConfig = null;
for (Object child : childrenObject)
{
ActionConfig = parse(child);
if (ActionConfig == null)
{
continue;
}
childrenActionConfig.put(ActionConfig.getType(), ActionConfig);
}
childrenIndex = childrenActionConfig;
return new ActionGroupConfigImpl(data.identifier, data.iconIdentifier, data.label, data.description,
data.type, data.properties, childrenIndex, data.evaluatorId);
}
else
{
return new ActionConfigImpl(data.identifier, data.iconIdentifier, data.label, data.description, data.type,
data.properties, isEnable, data.evaluatorId);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.