text
stringlengths 4
6.14k
|
|---|
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved.
#pragma once
#include "AutoFilterDescriptor.h"
namespace autowiring {
/// <summary>
/// A single subscription counter entry
/// </summary>
struct SatCounter:
AutoFilterDescriptor
{
SatCounter(void) = default;
SatCounter(const AutoFilterDescriptor& source):
AutoFilterDescriptor(source),
remaining(m_requiredCount)
{}
SatCounter(const SatCounter& source):
AutoFilterDescriptor(static_cast<const AutoFilterDescriptor&>(source)),
remaining(source.remaining)
{}
// Forward and backward linked list pointers
SatCounter* flink = nullptr;
SatCounter* blink = nullptr;
// The number of inputs remaining to this counter:
size_t remaining = 0;
/// <summary>
/// Conditionally decrements AutoFilter argument satisfaction.
/// </summary>
/// <returns>True if this decrement yielded satisfaction of all arguments</returns>
bool Decrement(void) {
return remaining && !--remaining;
}
/// <summary>
/// Conditionally increments AutoFilter argument satisfaction.
/// </summary>
void Increment(void) {
++remaining;
}
};
}
namespace std {
template<>
struct hash<autowiring::SatCounter>
{
size_t operator()(const autowiring::SatCounter& satCounter) const {
return (size_t)satCounter.GetAutoFilter().ptr();
}
};
}
|
/*
* Copyright [1999-2017] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* 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.
*/
#ifndef __INTRONSUPPORTINGEVIDENCE_H__
#define __INTRONSUPPORTINGEVIDENCE_H__
#include "DataModelTypes.h"
#include "SeqFeature.h"
#define INTRONSUPPORTINGEVIDENCEFUNCS_DATA(CLASSTYPE) \
SEQFEATUREFUNCS_DATA(CLASSTYPE)
SEQFEATUREFUNC_TYPES(IntronSupportingEvidence)
typedef struct IntronSupportingEvidenceFuncsStruct {
INTRONSUPPORTINGEVIDENCEFUNCS_DATA(IntronSupportingEvidence)
} IntronSupportingEvidenceFuncs;
#define INTRONSUPPORTINGEVIDENCE_DATA \
SEQFEATURE_DATA \
char isSpliceCanonical; \
char * hitName; \
ECOSTRING scoreType;
#define FUNCSTRUCTTYPE IntronSupportingEvidenceFuncs
struct IntronSupportingEvidenceStruct {
INTRONSUPPORTINGEVIDENCE_DATA
};
#undef FUNCSTRUCTTYPE
IntronSupportingEvidence *IntronSupportingEvidence_new(void);
Intron *IntronSupportingEvidence_getIntron(IntronSupportingEvidence *ise, Transcript *transcript);
void IntronSupportingEvidence_setValuesFromIntron(IntronSupportingEvidence *ise, Intron *intron);
int IntronSupportingEvidence_hasLinkedTranscripts(IntronSupportingEvidence *ise);
Exon *IntronSupportingEvidence_findPreviousExon(IntronSupportingEvidence *ise, Transcript *transcript);
Exon *IntronSupportingEvidence_findNextExon(IntronSupportingEvidence *ise, Transcript *transcript);
#define IntronSupportingEvidence_isStored(ise, db) Storable_isStored(&((ise)->st), (db))
ECOSTRING IntronSupportingEvidence_setScoreType(IntronSupportingEvidence *ise, char *scoreType);
#define IntronSupportingEvidence_getScoreType(ise) (ise)->scoreType
char *IntronSupportingEvidence_setHitName(IntronSupportingEvidence *ise, char *str);
#define IntronSupportingEvidence_getHitName(ise) (ise)->hitName
#define IntronSupportingEvidence_setIsSpliceCanonical(ise,flag) (ise)->isSpliceCanonical = (flag)
#define IntronSupportingEvidence_getIsSpliceCanonical(ise) (ise)->isSpliceCanonical
#define IntronSupportingEvidence_setStart(ise,start) SeqFeature_setStart((ise),(start))
#define IntronSupportingEvidence_getStart(ise) SeqFeature_getStart((ise))
#define IntronSupportingEvidence_setEnd(ise,end) SeqFeature_setEnd((ise),(end))
#define IntronSupportingEvidence_getEnd(ise) SeqFeature_getEnd((ise))
#define IntronSupportingEvidence_setStrand(ise,strand) SeqFeature_setStrand((ise),(strand))
#define IntronSupportingEvidence_getStrand(ise) SeqFeature_getStrand((ise))
#define IntronSupportingEvidence_setDbID(ise,dbID) SeqFeature_setDbID((ise),(dbID))
#define IntronSupportingEvidence_getDbID(ise) SeqFeature_getDbID((ise))
#define IntronSupportingEvidence_setAnalysis(ise,anal) SeqFeature_setAnalysis((ise),(anal))
#define IntronSupportingEvidence_getAnalysis(ise) SeqFeature_getAnalysis((ise))
#define IntronSupportingEvidence_setAdaptor(ise,adaptor) SeqFeature_setAdaptor((ise),(adaptor))
#define IntronSupportingEvidence_getAdaptor(ise) SeqFeature_getAdaptor((ise))
#define IntronSupportingEvidence_setSlice(ise,contig) SeqFeature_setSlice((ise),(contig))
#define IntronSupportingEvidence_getSlice(ise) SeqFeature_getSlice((ise))
#define IntronSupportingEvidence_setScore(ise,score) SeqFeature_setScore((ise),(score))
#define IntronSupportingEvidence_getScore(ise) SeqFeature_getScore((ise))
#define IntronSupportingEvidence_free(ise) SeqFeature_free((ise))
void IntronSupportingEvidence_freeImpl(IntronSupportingEvidence *ise);
#define IntronSupportingEvidence_getSeqRegionStart(ise) SeqFeature_getSeqRegionStart((SeqFeature *)(ise))
#define IntronSupportingEvidence_getSeqRegionEnd(ise) SeqFeature_getSeqRegionEnd((SeqFeature *)(ise))
#define IntronSupportingEvidence_getSeqRegionStrand(ise) SeqFeature_getSeqRegionStrand((SeqFeature *)(ise))
IntronSupportingEvidence *IntronSupportingEvidence_shallowCopyImpl(IntronSupportingEvidence *ise);
#define IntronSupportingEvidence_shallowCopy(ise) SeqFeature_shallowCopy((ise))
#ifdef __INTRONSUPPORTINGEVIDENCE_MAIN__
IntronSupportingEvidenceFuncs
intronSupportingEvidenceFuncs = {
IntronSupportingEvidence_freeImpl, // free
IntronSupportingEvidence_shallowCopyImpl, // shallowCopy
NULL, // deepCopy
NULL, // getStart
NULL, // setStart
NULL, // getEnd
NULL // setEnd
};
#else
extern IntronSupportingEvidenceFuncs intronSupportingEvidenceFuncs;
#endif
#endif
|
#ifndef LAYER_H_INCLUDED
#define LAYER_H_INCLUDED
#include "basicresource.h"
#include "Drawable.h"
class Layer : public Drawable
{
private:
void transformation() override;
void onDraw() override;
void postDraw() override;
public:
Layer():
Drawable()
{
//
}
};
#endif // LAYER_H_INCLUDED
|
/*
** Copyright (c) 2007, DNA Pty Ltd and contributors
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
** THE SOFTWARE.
*/
#include "libxatmi.h"
int tpdiscon(int cd)
{
write(2, "tpdiscon not supported\n", 23);
tperrno = TPEPROTO;
return -1;
}
|
#import "RLDTableViewModelProtocol.h"
#pragma mark - RLDTableViewGenericEventHandler protocol
@protocol RLDTableViewGenericEventHandler <NSObject>
// Suitability checking
+ (BOOL)canHandleTableView:(UITableView *)tableView viewModel:(id<RLDTableViewReusableViewModel>)viewModel view:(UIView *)view;
// Collaborators
- (void)setTableView:(UITableView *)tableView;
- (void)setViewModel:(id<RLDTableViewReusableViewModel>)viewModel;
- (void)setView:(UIView *)view;
@optional
// Display customization
- (void)willReuseView;
- (void)willDisplayView;
- (void)didEndDisplayingView;
@end
#pragma mark - RLDTableViewCellEventHandler protocol
@protocol RLDTableViewCellEventHandler <RLDTableViewGenericEventHandler>
@optional
// Accessories (disclosures)
- (void)accessoryButtonTapped;
// Selection
- (BOOL)shouldHighlightView;
- (void)didHighlightView;
- (void)didUnhighlightView;
- (void)willSelectView;
- (void)willDeselectView;
- (void)didSelectView;
- (void)didDeselectView;
// Editing
- (void)willBeginEditing;
- (void)didEndEditing;
- (NSArray *)editActions;
// Copy and Paste
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender;
- (void)performAction:(SEL)action withSender:(id)sender;
@end
#pragma mark - RLDTableViewSectionAccessoryViewEventHandler protocol
@protocol RLDTableViewSectionAccessoryViewEventHandler <RLDTableViewGenericEventHandler>
@end
#pragma mark - RLDTableViewEventHandlerProvider protocol
@protocol RLDTableViewEventHandlerProvider <NSObject>
- (id<RLDTableViewGenericEventHandler>)eventHandlerWithTableView:(UITableView *)tableView viewModel:(id<RLDTableViewReusableViewModel>)viewModel view:(UIView *)view;
@end
|
/*
* Copyright (c) 2018 <Carlos Chacón>
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef _GAME_OBJECT_DEBUG_DEFS_H
#define _GAME_OBJECT_DEBUG_DEFS_H
/**********************
* System Includes *
***********************/
/*************************
* 3rd Party Includes *
**************************/
/***************************
* Game Engine Includes *
****************************/
/**************
* Defines *
***************/
/// <summary>
/// Name for Basic Colro Material in Visualizer
/// </summary>
#define AE_GOD_V_BASIC_COLOR_MAT_NAME "AE GOD V Basic Color Material"
/// <summary>
/// Name for Basic Line Material in Visualizer
/// </summary>
#define AE_GOD_V_BASIC_LINE_MAT_NAME "AE GOD V Basic Line Material"
/// <summary>
/// Name for Diffuse Texture Basic Material in Visualizer
/// </summary>
#define AE_GOD_V_DIFFUSE_TEXTURE_BASIC_MAT_NAME "AE GOD V Diffuse Texture Basic Material"
/// <summary>
/// Name for Directional Light Icon Texture
/// </summary>
#define AE_GOD_DIRECTIONAL_LIGHT_ICON_TEXTURE_NAME "AE Directional Light Icon"
/// <summary>
/// Name for Omni Light Icon Texture
/// </summary>
#define AE_GOD_OMNI_LIGHT_ICON_TEXTURE_NAME "AE Omni Light Icon"
/// <summary>
/// Name for Spot Light Icon Texture
/// </summary>
#define AE_GOD_SPOT_LIGHT_ICON_TEXTURE_NAME "AE Spot Light Icon"
/// <summary>
/// Name for Camera Icon Texture
/// </summary>
#define AE_GOD_CAMERA_ICON_TEXTURE_NAME "AE Camera Icon"
/// <summary>
/// File path for Directional Light Icon Texture
/// </summary>
#define AE_GOD_DIRECTIONAL_LIGHT_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\DirLightIcon.dds"
/// <summary>
/// File path for Omni Light Icon Texture
/// </summary>
#define AE_GOD_OMNI_LIGHT_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\OmniLightIcon.dds"
/// <summary>
/// File path for Spot Light Icon Texture
/// </summary>
#define AE_GOD_SPOT_LIGHT_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\SpotLightIcon.dds"
/// <summary>
/// File path for Camera Icon Texture
/// </summary>
#define AE_GOD_CAMERA_ICON_PATH AE_Base_FS_PATH "Data\\Textures\\VideoCameraIcon.dds"
/// <summary>
/// Scale Amount for Light Icons
/// </summary>
#define AE_LIGHT_ICONS_DEFAULT_SCALE_AMOUNT 0.5f
/// <summary>
/// Scale Amount for Directional Light Shape
/// </summary>
#define AE_LIGHT_SHAPE_DIR_DEFAULT_SCALE_AMOUNT 2.0f
/************
* Using *
*************/
/********************
* Forward Decls *
*********************/
/****************
* Constants *
*****************/
/******************
* Struct Decl *
*******************/
struct GameObjectsDebugVisualizerConfig sealed : AEObject
{
bool m_CameraIconDrawEnabled = true;
bool m_LightIconDrawEnabled = true;
bool m_GameObjectDebugRenderEnabled = true;
float m_LightIconScale = AE_LIGHT_ICONS_DEFAULT_SCALE_AMOUNT;
float m_DirectionalLightShapeScale = AE_LIGHT_SHAPE_DIR_DEFAULT_SCALE_AMOUNT;
GameObjectsDebugVisualizerConfig()
{
}
};
#endif
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
#ifndef MY_HOSTNAME_H
#define MY_HOSTNAME_H
#include "stream.h"
#include <string>
#include <set>
class CondorError;
bool init_network_interfaces( CondorError * errorStack );
/* Find local addresses that match a given NETWORK_INTERFACE
*
* Prefers public addresses. Strongly prefers "up" addresses.
*
* interface_param_name - Optional, but recommended, exclusively used
* in log messages. Probably "NETWORK_INTERFACE" or "PRIVATE_NETWORK_INTERFACE"
* interface_pattern - Required. The value of the param. Something like
* "*" or "192.168.0.23"
* ipv4 - best ipv4 address found. May be empty if no ipv4 addresses are found
* that match the interface pattern.
* ipv6 - best ipv6 address found. May be empty if no ipv6 addresses are found
* that match the interface pattern.
* ipbest - If you absolutely need a single result, this is our best bet.
* But really, just don't do that. Should be one of ipv4 or ipv6.
*/
bool network_interface_to_ip(
char const *interface_param_name,
char const *interface_pattern,
std::string & ipv4,
std::string & ipv6,
std::string & ipbest);
#endif /* MY_HOSTNAME_H */
|
//
// DZYSquareCell.h
// budejie
//
// Created by dzy on 16/1/7.
// Copyright © 2016年 董震宇. All rights reserved.
//
#import <UIKit/UIKit.h>
@class DZYSquareModel;
@interface DZYSquareCell : UICollectionViewCell
/** 方块模型 */
@property (nonatomic, strong) DZYSquareModel *squareModel;
@end
|
// Copyright 2015 Thomas Trapp
//
// 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.
#ifndef HTMLEXT_FILE_H_INCLUDED
#define HTMLEXT_FILE_H_INCLUDED
#include <string>
#include <stdexcept>
namespace htmlext {
/// Custom exception type for file errors.
class FileError : public std::runtime_error
{
public:
explicit FileError(const std::string& msg) noexcept;
};
/// Read file at path to buffer. Throws FileError on failure.
/// Can read regular files as well as named pipes.
std::string ReadFileOrThrow(const std::string& path);
} // namespace htmlext
#endif // HTMLEXT_FILE_H_INCLUDED
|
/*_ generic.hpp Tue Jul 5 1988 Modified by: Walter Bright */
#ifndef __GENERIC_H
#define __GENERIC_H 1
/* Name concatenator functions */
#define name2(n1,n2) n1 ## n2
#define name3(n1,n2,n3) n1 ## n2 ## n3
#define name4(n1,n2,n3,n4) n1 ## n2 ## n3 ## n4
typedef int (*GPT) (int,char *);
extern int genericerror(int,char *);
#define set_handler(generic,type,x) set_##type##generic##_handler(x)
#define errorhandler(generic,type) type##generic##handler
#define callerror(generic,type,a,b) (*errorhandler(generic,type))(a,b)
#define declare(a,type) a##declare(type)
#define implement(a,type) a##implement(type)
#define declare2(a,type1,type2) a##declare2(type1,type2)
#define implement2(a,type1,type2) a##implement2(type1,type2)
#endif /* __GENERIC_H */
|
/*
Copyright (c) 2012, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
// define function pointer
typedef off64_t (*llamaos_lseek64_t) (int, off64_t, int);
// function pointer variable
static llamaos_lseek64_t llamaos_lseek64 = 0;
// function called by llamaOS to register pointer
void register_llamaos_lseek64 (llamaos_lseek64_t func)
{
llamaos_lseek64 = func;
}
/* Seek to OFFSET on FD, starting from WHENCE. */
off64_t __libc_lseek64 (int fd, off64_t offset, int whence)
{
if (0 != llamaos_lseek64)
{
if (fd < 0)
{
__set_errno (EBADF);
return -1;
}
switch (whence)
{
case SEEK_SET:
case SEEK_CUR:
case SEEK_END:
break;
default:
__set_errno (EINVAL);
return -1;
}
return llamaos_lseek64 (fd, offset, whence);
}
__set_errno (ENOSYS);
return -1;
}
weak_alias (__libc_lseek64, __lseek64)
weak_alias (__libc_lseek64, lseek64)
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "vm_strings.h"
#include <assert.h>
String *String_alloc(size_t length) {
String *p = (String *)calloc(1, sizeof(String) + (length+1) * sizeof(char));
p->length = length;
return p;
}
String *String_new(char *orig) {
String *s = String_alloc(strlen(orig));
strcpy(s->str, orig);
return s;
}
String *String_dup(String *orig) {
String *s = String_alloc(orig->length);
strcpy(s->str, orig->str);
return s;
}
String *String_from_char(char c) {
char buf[2] = {c, '\0'};
return String_new(buf);
}
String *String_from_int(int value) {
char buf[50];
sprintf(buf,"%d",value);
return String_new(buf);
}
int String_len(String *s) {
if (s == NULL) {
fprintf(stderr, "len() cannot be applied to NULL string object\n");
return -1;
}
return (int)s->length;
}
String *String_add(String *s, String *t) {
if ( s == NULL && t == NULL) {
fprintf(stderr, "Addition Operator cannot be applied to two NULL string objects\n");
return NIL_STRING;
}
if ( s == NULL ) return t; // don't REF/DEREF as we might free our return value
if ( t == NULL ) return s;
size_t n = strlen(s->str) + strlen(t->str);
String *u = String_alloc(n);
strcpy(u->str, s->str);
strcat(u->str, t->str);
return u;
}
bool String_eq(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) == 0;
}
bool String_neq(String *s, String *t) {
return !String_eq(s,t);
}
bool String_gt(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) > 0;
}
bool String_ge(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) >= 0;
}
bool String_lt(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) < 0;
}
bool String_le(String *s, String *t) {
assert(s);
assert(t);
return strcmp(s->str, t->str) <= 0;
}
|
#ifndef AOS_COMMON_STL_MUTEX_H_
#define AOS_COMMON_STL_MUTEX_H_
#include <mutex>
#include "aos/linux_code/ipc_lib/aos_sync.h"
#include "aos/common/logging/logging.h"
#include "aos/common/type_traits.h"
#include "aos/common/macros.h"
namespace aos {
// A mutex with the same API and semantics as ::std::mutex, with the addition of
// methods for checking if the previous owner died and a constexpr default
// constructor.
// Definitely safe to put in SHM.
// This uses the pthread_mutex semantics for owner-died: once somebody dies with
// the lock held, anybody else who takes it will see true for owner_died() until
// one of them calls consistent(). It is an error to call unlock() when
// owner_died() returns true.
class stl_mutex {
public:
constexpr stl_mutex() : native_handle_() {}
void lock() {
const int ret = mutex_grab(&native_handle_);
switch (ret) {
case 0:
break;
case 1:
owner_died_ = true;
break;
default:
LOG(FATAL, "mutex_grab(%p) failed with %d\n", &native_handle_, ret);
}
}
bool try_lock() {
const int ret = mutex_trylock(&native_handle_);
switch (ret) {
case 0:
return true;
case 1:
owner_died_ = true;
return true;
case 4:
return false;
default:
LOG(FATAL, "mutex_trylock(%p) failed with %d\n", &native_handle_, ret);
}
}
void unlock() {
CHECK(!owner_died_);
mutex_unlock(&native_handle_);
}
typedef aos_mutex *native_handle_type;
native_handle_type native_handle() { return &native_handle_; }
bool owner_died() const { return owner_died_; }
void consistent() { owner_died_ = false; }
private:
aos_mutex native_handle_;
bool owner_died_ = false;
DISALLOW_COPY_AND_ASSIGN(stl_mutex);
};
// A mutex with the same API and semantics as ::std::recursive_mutex, with the
// addition of methods for checking if the previous owner died and a constexpr
// default constructor.
// Definitely safe to put in SHM.
// This uses the pthread_mutex semantics for owner-died: once somebody dies with
// the lock held, anybody else who takes it will see true for owner_died() until
// one of them calls consistent(). It is an error to call unlock() or lock()
// again when owner_died() returns true.
class stl_recursive_mutex {
public:
constexpr stl_recursive_mutex() {}
void lock() {
if (mutex_islocked(mutex_.native_handle())) {
CHECK(!owner_died());
++recursive_locks_;
} else {
mutex_.lock();
if (mutex_.owner_died()) {
recursive_locks_ = 0;
} else {
CHECK_EQ(0, recursive_locks_);
}
}
}
bool try_lock() {
if (mutex_islocked(mutex_.native_handle())) {
CHECK(!owner_died());
++recursive_locks_;
return true;
} else {
if (mutex_.try_lock()) {
if (mutex_.owner_died()) {
recursive_locks_ = 0;
} else {
CHECK_EQ(0, recursive_locks_);
}
return true;
} else {
return false;
}
}
}
void unlock() {
if (recursive_locks_ == 0) {
mutex_.unlock();
} else {
--recursive_locks_;
}
}
typedef stl_mutex::native_handle_type native_handle_type;
native_handle_type native_handle() { return mutex_.native_handle(); }
bool owner_died() const { return mutex_.owner_died(); }
void consistent() { mutex_.consistent(); }
private:
stl_mutex mutex_;
int recursive_locks_ = 0;
DISALLOW_COPY_AND_ASSIGN(stl_recursive_mutex);
};
// Convenient typedefs for various types of locking objects.
typedef ::std::lock_guard<stl_mutex> mutex_lock_guard;
typedef ::std::lock_guard<stl_recursive_mutex> recursive_lock_guard;
typedef ::std::unique_lock<stl_mutex> mutex_unique_lock;
typedef ::std::unique_lock<stl_recursive_mutex> recursive_unique_lock;
} // namespace aos
#endif // AOS_COMMON_STL_MUTEX_H_
|
#pragma once
//-----------------------------------------------------------------------------------------------------
/*
NAMESPACE::CLASS
DESC
Copyright 2015 - See license file LICENSE.txt
*/
//-----------------------------------------------------------------------------------------------------
namespace ASL
{
struct Expr
{
public:
/// constructor
Expr();
/// destructor
virtual ~Expr();
private:
};
} // namespace ASL
|
/*
* Software written by Jared Bruni https://github.com/lostjared
This software is dedicated to all the people that experience mental illness.
Website: http://lostsidedead.com
YouTube: http://youtube.com/LostSideDead
Instagram: http://instagram.com/lostsidedead
Twitter: http://twitter.com/jaredbruni
Facebook: http://facebook.com/LostSideDead0x
You can use this program free of charge and redistrubute it online as long
as you do not charge anything for this program. This program is meant to be
100% free.
BSD 2-Clause License
Copyright (c) 2020, Jared Bruni
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import<Foundation/Foundation.h>
#import<Cocoa/Cocoa.h>
extern NSMutableArray *search_results;
@interface SearchController : NSObject<NSTableViewDataSource, NSTableViewDelegate> {
}
@end
|
/*
* Copyright (c) 2013 Ambroz Bizjak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 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 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.
*/
#ifndef AMBROLIB_STRUCT_IF_H
#define AMBROLIB_STRUCT_IF_H
namespace APrinter {
#define AMBRO_STRUCT_IF(name, condition) \
template <bool name##__IfEnable, typename name##__IfDummy = void> \
struct name##__impl {}; \
using name = name##__impl<(condition)>; \
template <typename name##__IfDummy> \
struct name##__impl <true, name##__IfDummy>
#define AMBRO_STRUCT_ELSE(name) \
; template <typename name##__IfDummy> \
struct name##__impl <false, name##__IfDummy>
#define APRINTER_STRUCT_IF_TEMPLATE(name) \
template <bool name##__IfEnable, typename name##__IfDummy = void> \
struct name {}; \
template <typename name##__IfDummy> \
struct name <true, name##__IfDummy>
}
#endif
|
/* Copyright (c) Citrix Systems 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <ntddk.h>
#include <xen.h>
#include <util.h>
#include "hypercall.h"
#include "dbg_print.h"
#include "assert.h"
#define MAXIMUM_HYPERCALL_PFN_COUNT 2
#pragma code_seg("hypercall")
__declspec(allocate("hypercall"))
static UCHAR __Section[(MAXIMUM_HYPERCALL_PFN_COUNT + 1) * PAGE_SIZE];
static ULONG XenBaseLeaf = 0x40000000;
static USHORT XenMajorVersion;
static USHORT XenMinorVersion;
static PFN_NUMBER HypercallPfn[MAXIMUM_HYPERCALL_PFN_COUNT];
static ULONG HypercallPfnCount;
typedef UCHAR HYPERCALL_GATE[32];
typedef HYPERCALL_GATE *PHYPERCALL_GATE;
PHYPERCALL_GATE Hypercall;
NTSTATUS
HypercallInitialize(
VOID
)
{
ULONG EAX = 'DEAD';
ULONG EBX = 'DEAD';
ULONG ECX = 'DEAD';
ULONG EDX = 'DEAD';
ULONG Index;
ULONG HypercallMsr;
NTSTATUS status;
status = STATUS_UNSUCCESSFUL;
for (;;) {
CHAR Signature[13] = {0};
__CpuId(XenBaseLeaf, &EAX, &EBX, &ECX, &EDX);
*((PULONG)(Signature + 0)) = EBX;
*((PULONG)(Signature + 4)) = ECX;
*((PULONG)(Signature + 8)) = EDX;
if (strcmp(Signature, "XenVMMXenVMM") == 0 &&
EAX >= XenBaseLeaf + 2)
break;
XenBaseLeaf += 0x100;
if (XenBaseLeaf > 0x40000100)
goto fail1;
}
__CpuId(XenBaseLeaf + 1, &EAX, NULL, NULL, NULL);
XenMajorVersion = (USHORT)(EAX >> 16);
XenMinorVersion = (USHORT)(EAX & 0xFFFF);
Info("XEN %d.%d\n", XenMajorVersion, XenMinorVersion);
Info("INTERFACE 0x%08x\n", __XEN_INTERFACE_VERSION__);
if ((ULONG_PTR)__Section & (PAGE_SIZE - 1))
Hypercall = (PVOID)(((ULONG_PTR)__Section + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1));
else
Hypercall = (PVOID)__Section;
ASSERT3U(((ULONG_PTR)Hypercall & (PAGE_SIZE - 1)), ==, 0);
for (Index = 0; Index < MAXIMUM_HYPERCALL_PFN_COUNT; Index++) {
PHYSICAL_ADDRESS PhysicalAddress;
PhysicalAddress = MmGetPhysicalAddress((PUCHAR)Hypercall + (Index << PAGE_SHIFT));
HypercallPfn[Index] = (PFN_NUMBER)(PhysicalAddress.QuadPart >> PAGE_SHIFT);
}
__CpuId(XenBaseLeaf + 2, &EAX, &EBX, NULL, NULL);
HypercallPfnCount = EAX;
ASSERT(HypercallPfnCount <= MAXIMUM_HYPERCALL_PFN_COUNT);
HypercallMsr = EBX;
for (Index = 0; Index < HypercallPfnCount; Index++) {
Info("HypercallPfn[%d]: %p\n", Index, (PVOID)HypercallPfn[Index]);
__writemsr(HypercallMsr, (ULONG64)HypercallPfn[Index] << PAGE_SHIFT);
}
return STATUS_SUCCESS;
fail1:
Error("fail1 (%08x)", status);
return status;
}
extern uintptr_t __stdcall hypercall_gate_2(uint32_t ord, uintptr_t arg1, uintptr_t arg2);
ULONG_PTR
__Hypercall2(
ULONG Ordinal,
ULONG_PTR Argument1,
ULONG_PTR Argument2
)
{
return hypercall_gate_2(Ordinal, Argument1, Argument2);
}
extern uintptr_t __stdcall hypercall_gate_3(uint32_t ord, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3);
ULONG_PTR
__Hypercall3(
ULONG Ordinal,
ULONG_PTR Argument1,
ULONG_PTR Argument2,
ULONG_PTR Argument3
)
{
return hypercall_gate_3(Ordinal, Argument1, Argument2, Argument3);
}
VOID
HypercallTeardown(
VOID
)
{
ULONG Index;
Hypercall = NULL;
for (Index = 0; Index < MAXIMUM_HYPERCALL_PFN_COUNT; Index++)
HypercallPfn[Index] = 0;
HypercallPfnCount = 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#define BUFF_SIZE 1024
int main(int argc, const char *argv[])
{
int i = 0;
char buff[BUFF_SIZE];
ssize_t msg_len = 0;
int srv_fd = -1;
int cli_fd = -1;
int epoll_fd = -1;
struct sockaddr_in srv_addr;
struct sockaddr_in cli_addr;
socklen_t cli_addr_len;
struct epoll_event e, es[2];
memset(&srv_addr, 0, sizeof(srv_addr));
memset(&cli_addr, 0, sizeof(cli_addr));
memset(&e, 0, sizeof(e));
srv_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (srv_fd < 0) {
printf("Cannot create socket\n");
return 1;
}
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
srv_addr.sin_port = htons(5555);
if (bind(srv_fd, (struct sockaddr*) &srv_addr, sizeof(srv_addr)) < 0) {
printf("Cannot bind socket\n");
close(srv_fd);
return 1;
}
if (listen(srv_fd, 1) < 0) {
printf("Cannot listen\n");
close(srv_fd);
return 1;
}
epoll_fd = epoll_create(2);
if (epoll_fd < 0) {
printf("Cannot create epoll\n");
close(srv_fd);
return 1;
}
e.events = EPOLLIN;
e.data.fd = srv_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, srv_fd, &e) < 0) {
printf("Cannot add server socket to epoll\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
for(;;) {
i = epoll_wait(epoll_fd, es, 2, -1);
if (i < 0) {
printf("Cannot wait for events\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
for (--i; i > -1; --i) {
if (es[i].data.fd == srv_fd) {
cli_fd = accept(srv_fd, (struct sockaddr*) &cli_addr, &cli_addr_len);
if (cli_fd < 0) {
printf("Cannot accept client\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
e.data.fd = cli_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, cli_fd, &e) < 0) {
printf("Cannot accept client\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
}
if (es[i].data.fd == cli_fd) {
if (es[i].events & EPOLLIN) {
msg_len = read(cli_fd, buff, BUFF_SIZE);
if (msg_len > 0) {
write(cli_fd, buff, msg_len);
}
close(cli_fd);
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, cli_fd, &e);
cli_fd = -1;
}
}
}
}
return 0;
}
|
/*
* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
*
* Find the sum of all the primes below two million.
*/
#include <stdio.h>
#include <stdint.h>
#include "euler.h"
#define PROBLEM 10
int
main(int argc, char **argv)
{
uint64_t sum = 0, number = 0;
do {
number++;
if(is_prime(number)) {
sum += number;
}
} while(number != 2000000);
printf("%llu\n", sum);
return(0);
}
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2016 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 IVW_GLFWEXCEPTION_H
#define IVW_GLFWEXCEPTION_H
#include <modules/glfw/glfwmoduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/exception.h>
namespace inviwo {
/**
* \class GLFWException
*/
class IVW_MODULE_GLFW_API GLFWException : public Exception {
public:
GLFWException(const std::string& message = "", ExceptionContext context = ExceptionContext());
virtual ~GLFWException() throw() {}
};
class IVW_MODULE_GLFW_API GLFWInitException : public ModuleInitException {
public:
GLFWInitException(const std::string& message = "",
ExceptionContext context = ExceptionContext());
virtual ~GLFWInitException() throw() {}
};
} // namespace
#endif // IVW_GLFWEXCEPTION_H
|
/*
* Copyright (c) 2016, Linaro Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <types_ext.h>
#include <drivers/ps2mouse.h>
#include <drivers/serial.h>
#include <string.h>
#include <keep.h>
#include <trace.h>
#define PS2_CMD_RESET 0xff
#define PS2_CMD_ACK 0xfa
#define PS2_CMD_ENABLE_DATA_REPORTING 0xf4
#define PS2_BAT_OK 0xaa
#define PS2_MOUSE_ID 0x00
#define PS2_BYTE0_Y_OVERFLOW (1 << 7)
#define PS2_BYTE0_X_OVERFLOW (1 << 6)
#define PS2_BYTE0_Y_SIGN (1 << 5)
#define PS2_BYTE0_X_SIGN (1 << 4)
#define PS2_BYTE0_ALWAYS_ONE (1 << 3)
#define PS2_BYTE0_MIDDLE_DOWN (1 << 2)
#define PS2_BYTE0_RIGHT_DOWN (1 << 1)
#define PS2_BYTE0_LEFT_DOWN (1 << 0)
static void call_callback(struct ps2mouse_data *d, uint8_t byte1,
uint8_t byte2, uint8_t byte3)
{
uint8_t button;
int16_t xdelta;
int16_t ydelta;
button = byte1 & (PS2_BYTE0_MIDDLE_DOWN | PS2_BYTE0_RIGHT_DOWN |
PS2_BYTE0_LEFT_DOWN);
if (byte1 & PS2_BYTE0_X_OVERFLOW) {
xdelta = byte1 & PS2_BYTE0_X_SIGN ? -255 : 255;
} else {
xdelta = byte2;
if (byte1 & PS2_BYTE0_X_SIGN)
xdelta |= 0xff00; /* sign extend */
}
if (byte1 & PS2_BYTE0_Y_OVERFLOW) {
ydelta = byte1 & PS2_BYTE0_Y_SIGN ? -255 : 255;
} else {
ydelta = byte3;
if (byte1 & PS2_BYTE0_Y_SIGN)
ydelta |= 0xff00; /* sign extend */
}
d->callback(d->callback_data, button, xdelta, -ydelta);
}
static void psm_consume(struct ps2mouse_data *d, uint8_t b)
{
switch (d->state) {
case PS2MS_RESET:
if (b != PS2_CMD_ACK)
goto reset;
d->state = PS2MS_INIT;
return;
case PS2MS_INIT:
if (b != PS2_BAT_OK)
goto reset;
d->state = PS2MS_INIT2;
return;
case PS2MS_INIT2:
if (b != PS2_MOUSE_ID) {
EMSG("Unexpected byte 0x%x in state %d", b, d->state);
d->state = PS2MS_INACTIVE;
return;
}
d->state = PS2MS_INIT3;
d->serial->ops->putc(d->serial, PS2_CMD_ENABLE_DATA_REPORTING);
return;
case PS2MS_INIT3:
d->state = PS2MS_ACTIVE1;
return;
case PS2MS_ACTIVE1:
if (!(b & PS2_BYTE0_ALWAYS_ONE))
goto reset;
d->bytes[0] = b;
d->state = PS2MS_ACTIVE2;
return;
case PS2MS_ACTIVE2:
d->bytes[1] = b;
d->state = PS2MS_ACTIVE3;
return;
case PS2MS_ACTIVE3:
d->state = PS2MS_ACTIVE1;
call_callback(d, d->bytes[0], d->bytes[1], b);
return;
default:
EMSG("Unexpected byte 0x%x in state %d", b, d->state);
return;
}
reset:
EMSG("Unexpected byte 0x%x in state %d, resetting", b, d->state);
d->state = PS2MS_RESET;
d->serial->ops->putc(d->serial, PS2_CMD_RESET);
}
static enum itr_return ps2mouse_itr_cb(struct itr_handler *h)
{
struct ps2mouse_data *d = h->data;
if (!d->serial->ops->have_rx_data(d->serial))
return ITRR_NONE;
while (true) {
psm_consume(d, d->serial->ops->getchar(d->serial));
if (!d->serial->ops->have_rx_data(d->serial))
return ITRR_HANDLED;
}
}
KEEP_PAGER(ps2mouse_itr_cb);
void ps2mouse_init(struct ps2mouse_data *d, struct serial_chip *serial,
size_t serial_it, ps2mouse_callback cb, void *cb_data)
{
memset(d, 0, sizeof(*d));
d->serial = serial;
d->state = PS2MS_RESET;
d->itr_handler.it = serial_it;
d->itr_handler.flags = ITRF_TRIGGER_LEVEL;
d->itr_handler.handler = ps2mouse_itr_cb;
d->itr_handler.data = d;
d->callback = cb;
d->callback_data = cb_data;
itr_add(&d->itr_handler);
itr_enable(&d->itr_handler);
d->serial->ops->putc(d->serial, PS2_CMD_RESET);
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "UnrealEd.h"
#include "SoundMod.h"
DECLARE_LOG_CATEGORY_EXTERN(LogSoundModImporter, Verbose, All);
#include "SoundModImporterClasses.h"
|
/**
* @file
* @brief test for access of http://embox.googlecode.com/files/ext2_users.img
*
* @author Anton Kozlov
* @date 18.02.2013
*/
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <security/smac/smac.h>
#include <fs/vfs.h>
#include <fs/fsop.h>
#include <fs/flags.h>
#include <kernel/task.h>
#include <sys/xattr.h>
#include <embox/test.h>
#include <kernel/task/resource/security.h>
EMBOX_TEST_SUITE("smac tests with classic modes allows all access");
TEST_SETUP_SUITE(setup_suite);
TEST_TEARDOWN(clear_id);
TEST_TEARDOWN_SUITE(teardown_suite);
#define FS_NAME "ext2"
#define FS_DEV "/dev/hda"
#define FS_DIR "/tmp"
#define FILE_H "/tmp/file_high"
#define FILE_L "/tmp/file_low"
#define HIGH "high_label"
#define LOW "low_label"
static const char *high_static = HIGH;
static const char *low_static = LOW;
static const char *smac_star = "*";
#define SMAC_BACKUP_LEN 1024
static char buf[SMAC_BACKUP_LEN];
static struct smac_env *backup;
static struct smac_env test_env = {
.n = 2,
.entries = {
{HIGH, LOW, FS_MAY_READ },
{LOW, HIGH, FS_MAY_WRITE},
},
};
static mode_t root_backup_mode;
static int setup_suite(void) {
int res;
if (0 != (res = smac_getenv(buf, SMAC_BACKUP_LEN, &backup))) {
return res;
}
if (0 != (res = smac_setenv(&test_env))) {
return res;
}
root_backup_mode = vfs_get_root()->mode;
vfs_get_root()->mode = S_IFDIR | 0777;
if ((res = mount(FS_DEV, FS_DIR, FS_NAME))) {
return res;
}
return 0;
}
static int teardown_suite(void) {
// int res;
vfs_get_root()->mode = root_backup_mode;
return smac_setenv(backup);
}
static int clear_id(void) {
struct smac_task *smac_task = (struct smac_task *) task_self_resource_security();
strcpy(smac_task->label, "smac_admin");
return 0;
}
TEST_CASE("Low subject shouldn't read high object") {
int fd;
smac_labelset(low_static);
test_assert_equal(-1, fd = open(FILE_H, O_RDWR));
test_assert_equal(EACCES, errno);
test_assert_equal(-1, fd = open(FILE_H, O_RDONLY));
test_assert_equal(EACCES, errno);
}
TEST_CASE("High subject shouldn't write low object") {
int fd;
smac_labelset(high_static);
test_assert_equal(-1, fd = open(FILE_L, O_RDWR));
test_assert_equal(EACCES, errno);
test_assert_equal(-1, fd = open(FILE_L, O_WRONLY));
test_assert_equal(EACCES, errno);
}
TEST_CASE("High subject should be able r/w high object") {
int fd;
smac_labelset(high_static);
test_assert_not_equal(-1, fd = open(FILE_H, O_RDWR));
close(fd);
}
TEST_CASE("Low subject should be able r/w low object") {
int fd;
smac_labelset(low_static);
test_assert_not_equal(-1, fd = open(FILE_L, O_RDWR));
close(fd);
}
TEST_CASE("High subject shouldn't be able change high object label") {
smac_labelset(high_static);
test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_equal(EACCES, errno);
}
TEST_CASE("Low subject shouldn't be able change high object label") {
smac_labelset(low_static);
test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_equal(EACCES, errno);
}
TEST_CASE("smac admin should be able change high object label") {
smac_labelset(smac_admin);
test_assert_zero(setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_zero(setxattr(FILE_H, smac_xattrkey, high_static,
strlen(high_static), 0));
}
|
/***** includes *****/
#include "lfds720_stack_np_internal.h"
/***** private prototypes *****/
static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss,
struct lfds720_misc_validation_info *vi,
enum lfds720_misc_validity *lfds720_stack_np_validity );
/****************************************************************************/
void lfds720_stack_np_query( struct lfds720_stack_np_state *ss,
enum lfds720_stack_np_query query_type,
void *query_input,
void *query_output )
{
LFDS720_PAL_ASSERT( ss != NULL );
// TRD : query_type can be any value in its range
LFDS720_MISC_BARRIER_LOAD;
switch( query_type )
{
case LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT:
{
ptrdiff_t
se;
LFDS720_PAL_ASSERT( query_input == NULL );
LFDS720_PAL_ASSERT( query_output != NULL );
*(lfds720_pal_uint_t *) query_output = 0;
// TRD : count the elements on the stack_np
se = ss->top[LFDS720_MISC_OFFSET];
while( se != 0 )
{
( *(lfds720_pal_uint_t *) query_output )++;
se = LFDS720_MISC_OFFSET_TO_POINTER( ss, se, struct lfds720_stack_np_element )->next;
}
}
break;
case LFDS720_STACK_NP_QUERY_SINGLETHREADED_VALIDATE:
// TRD : query_input can be NULL
LFDS720_PAL_ASSERT( query_output != NULL );
lfds720_stack_np_internal_stack_np_validate( ss, (struct lfds720_misc_validation_info *) query_input, (enum lfds720_misc_validity *) query_output );
break;
}
return;
}
/****************************************************************************/
static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss,
struct lfds720_misc_validation_info *vi,
enum lfds720_misc_validity *lfds720_stack_np_validity )
{
lfds720_pal_uint_t
number_elements = 0;
ptrdiff_t
se_slow,
se_fast;
LFDS720_PAL_ASSERT( ss != NULL );
// TRD : vi can be NULL
LFDS720_PAL_ASSERT( lfds720_stack_np_validity != NULL );
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_VALID;
se_slow = se_fast = ss->top[LFDS720_MISC_OFFSET];
/* TRD : first, check for a loop
we have two pointers
both of which start at the top of the stack_np
we enter a loop
and on each iteration
we advance one pointer by one element
and the other by two
we exit the loop when both pointers are NULL
(have reached the end of the stack_np)
or
if we fast pointer 'sees' the slow pointer
which means we have a loop
*/
if( se_slow != 0 )
do
{
// se_slow = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_slow ) )->next;
se_slow = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_slow, struct lfds720_stack_np_element )->next;
if( se_fast != 0 )
// se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next;
se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next;
if( se_fast != 0 )
// se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next;
se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next;
}
while( se_slow != 0 and se_fast != se_slow );
if( se_fast != 0 and se_slow != 0 and se_fast == se_slow )
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_LOOP;
/* TRD : now check for expected number of elements
vi can be NULL, in which case we do not check
we know we don't have a loop from our earlier check
*/
if( *lfds720_stack_np_validity == LFDS720_MISC_VALIDITY_VALID and vi != NULL )
{
lfds720_stack_np_query( ss, LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT, NULL, (void *) &number_elements );
if( number_elements < vi->min_elements )
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_MISSING_ELEMENTS;
if( number_elements > vi->max_elements )
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_ADDITIONAL_ELEMENTS;
}
return;
}
|
#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
#define FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
#include "aos/common/controls/polytope.h"
#ifdef INCLUDE_971_INFRASTRUCTURE
#include "frc971/control_loops/drivetrain/drivetrain.q.h"
#endif //INCLUDE_971_INFRASTRUCTURE
#include "frc971/control_loops/state_feedback_loop.h"
#include "frc971/control_loops/drivetrain/drivetrain_config.h"
namespace frc971 {
namespace control_loops {
namespace drivetrain {
class PolyDrivetrain {
public:
enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN };
PolyDrivetrain(const DrivetrainConfig &dt_config);
int controller_index() const { return loop_->controller_index(); }
bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; }
// Computes the speed of the motor given the hall effect position and the
// speed of the robot.
double MotorSpeed(const constants::ShifterHallEffect &hall_effect,
double shifter_position, double velocity);
// Computes the states of the shifters for the left and right drivetrain sides
// given a requested state.
void UpdateGears(Gear requested_gear);
// Computes the next state of a shifter given the current state and the
// requested state.
Gear UpdateSingleGear(Gear requested_gear, Gear current_gear);
void SetGoal(double wheel, double throttle, bool quickturn, bool highgear);
#ifdef INCLUDE_971_INFRASTRUCTURE
void SetPosition(
const ::frc971::control_loops::DrivetrainQueue::Position *position);
#else //INCLUDE_971_INFRASTRUCTURE
void SetPosition(
const DrivetrainPosition *position);
#endif //INCLUDE_971_INFRASTRUCTURE
double FilterVelocity(double throttle);
double MaxVelocity();
void Update();
#ifdef INCLUDE_971_INFRASTRUCTURE
void SendMotors(::frc971::control_loops::DrivetrainQueue::Output *output);
#else //INCLUDE_971_INFRASTRUCTURE
void SendMotors(DrivetrainOutput *output);
#endif //INCLUDE_971_INFRASTRUCTURE
private:
StateFeedbackLoop<7, 2, 3> kf_;
const ::aos::controls::HPolytope<2> U_Poly_;
::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
const double ttrust_;
double wheel_;
double throttle_;
bool quickturn_;
int stale_count_;
double position_time_delta_;
Gear left_gear_;
Gear right_gear_;
#ifdef INCLUDE_971_INFRASTRUCTURE
::frc971::control_loops::DrivetrainQueue::Position last_position_;
::frc971::control_loops::DrivetrainQueue::Position position_;
#else //INCLUDE_971_INFRASTRUCTURE
DrivetrainPosition last_position_;
DrivetrainPosition position_;
#endif //INCLUDE_971_INFRASTRUCTURE
int counter_;
DrivetrainConfig dt_config_;
};
} // namespace drivetrain
} // namespace control_loops
} // namespace frc971
#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
|
/*
* cuda_common.h
*
* Created on: Jul 14, 2014
* Author: shu
*/
#pragma once
#include <cstdio>
#include <stdint.h>
#define CUDA_CHECK_RETURN(value) { \
cudaError_t _m_cudaStat = value; \
if (_m_cudaStat != cudaSuccess) { \
fprintf(stderr, "Error %s at line %d in file %s\n", \
cudaGetErrorString(_m_cudaStat), __LINE__, __FILE__); \
exit(1); \
} }
namespace cuda_common {
typedef struct {
uint32_t query_position;
uint32_t database_position;
} Coordinate;
enum Direction {
kFoward, kReverse,
};
static const size_t kMaxLoadLength = 4;
}
|
/* @LICENSE(MUSLC_MIT) */
#include "pthread_impl.h"
int pthread_detach(pthread_t t)
{
/* Cannot detach a thread that's already exiting */
if (a_swap(t->exitlock, 1))
return pthread_join(t, 0);
t->detached = 2;
__unlock(t->exitlock);
return 0;
}
|
/* Copyright (c) 2016-2017, Artem Kashkanov
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
#ifndef IMAGE_H_
#define IMAGE_H_
#include <cstdlib>
#include <vector>
#include <fstream>
#include <iostream>
#include "bfutils.h"
#include "cmd.h"
#include <string.h>
class Section{
public:
Section(std::vector<Cmd> &SectionCmd, uint16_t MemoryBase, uint16_t MemorySize);
Section(std::vector<uint16_t> &SectionData,
uint16_t MemoryBase, uint16_t MemorySize);
Section(std::fstream &File);
~Section();
uint8_t GetType(){return Hdr.type;};
uint16_t GetFileBase(){return Hdr.FileBase;};
uint16_t GetMemoryBase(){return Hdr.MemoryBase;};
uint16_t GetFileSize(){return Hdr.FileSize;};
uint16_t GetMemorySize(){return Hdr.MemorySize;};
void WriteHeader(std::fstream &File);
void WriteData(std::fstream &File);
uint16_t *GetData(){return Data;};
bool Error(){return err;};
private:
bool err;
BfSection_t Hdr;
uint16_t *Data;
};
class Image{
public:
Image(std::fstream &File, bool hex);
Image(uint8_t _machine);
~Image();
void AddSection(Section §ion);
uint8_t GetSectionNum(void){return Hdr.SectionNum;};
Section &GetSection(uint8_t section){return Sections[section];};
void SetIpEntry(ADDRESS_TYPE Ptr){Hdr.IpEntry = Ptr;};
void SetApEntry(ADDRESS_TYPE Ptr){Hdr.ApEntry = Ptr;};
ADDRESS_TYPE GetIpEntry(){return Hdr.IpEntry;};
ADDRESS_TYPE GetApEntry(){return Hdr.ApEntry;};
bool ReadHex(std::fstream &File);
void Write(std::fstream &File);
bool Error(){return err;};
private:
bool m_hex;
bool err;
BfHeader_t Hdr;
std::vector<Section> Sections;
};
#endif //IMAGE_H_
|
// Set color based on frequency and brightness
void setColor(int peak_index, int brightness) {
if (peak_index == 0) {
// signal was weak, turn lights off
red = 0;
green = 0;
blue = 0;
} else if (peak_index > 30) {
red = current_palette[29].red;
green = current_palette[29].green;
blue = current_palette[29].blue;
} else {
red = current_palette[peak_index - 1].red;
green = current_palette[peak_index - 1].green;
blue = current_palette[peak_index - 1].blue;
}
strip_color = strip.Color(
round((red / 100.0) * brightness),
round((green / 100.0) * brightness),
round((blue / 100.0) * brightness)
);
if (DEBUG) {
Serial.print((red / 100.0) * brightness);
Serial.print("\t");
Serial.print((green / 100.0) * brightness);
Serial.print("\t");
Serial.println((blue / 100.0) * brightness);
}
for (int i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, strip_color);
}
strip.show();
}
void changeColorPalette() {
// re-populate colors for color_palette from new palette choice
if (palette_choice != new_palette_choice - 1) {
palette_choice = new_palette_choice - 1;
for (int i = 0; i < 30; i++) {
current_palette[i].red = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].red)
);
current_palette[i].green = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].green)
);
current_palette[i].blue = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].blue)
);
}
}
}
|
/*******
*
* FILE INFO:
* project: RTP_lib
* file: Types.h
* started on: 03/26/03
* started by: Cedric Lacroix <lacroix_cedric@yahoo.com>
*
*
* TODO:
*
* BUGS:
*
* UPDATE INFO:
* updated on: 05/13/03
* updated by: Cedric Lacroix <lacroix_cedric@yahoo.com>
*
*******/
#ifndef TYPES_H
#define TYPES_H
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
typedef unsigned char u_int8;
typedef unsigned short u_int16;
typedef unsigned long u_int32;
typedef unsigned int context;
/**
** Declaration for unix
**/
#ifdef UNIX
#ifndef _WIN32
typedef int SOCKET;
#endif
typedef struct sockaddr SOCKADDR;
typedef struct sockaddr_in SOCKADDR_IN;
#endif /* UNIX */
#endif /* TYPES_H */
|
/* Copyright (c) 2013, Anthony Cornehl
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "check/twinshadow.h"
#include "twinshadow/string.h"
char *buf_strstrip;
START_TEST(strstrip_removes_preceding_and_trailing_whitespace)
{
ts_strstrip(buf_strstrip);
ck_assert_str_eq(buf_strstrip, "one two three");
}
END_TEST
void
setup_strstrip_test(void) {
buf_strstrip = strdup(" one two three ");
}
void
teardown_strstrip_test(void) {
free(buf_strstrip);
}
TCase *
tcase_strstrip(void) {
TCase *tc = tcase_create("strstrip");
tcase_add_checked_fixture(tc, setup_strstrip_test, teardown_strstrip_test);
tcase_add_test(tc, strstrip_removes_preceding_and_trailing_whitespace);
return tc;
}
CHECK_MAIN_STANDALONE(strstrip);
|
#ifndef _CONVOUTPUT_SPH_H_
#define _CONVOUTPUT_SPH_H_
/*
###################################################################################
#
# CDMlib - Cartesian Data Management library
#
# Copyright (c) 2013-2017 Advanced Institute for Computational Science (AICS), RIKEN.
# All rights reserved.
#
# Copyright (c) 2016-2017 Research Institute for Information Technology (RIIT), Kyushu University.
# All rights reserved.
#
###################################################################################
*/
/**
* @file convOutput_SPH.h
* @brief convOutput_SPH Class Header
* @author aics
* @date 2013/11/7
*/
#include "convOutput.h"
class convOutput_SPH : public convOutput {
public:
/** コンストラクタ */
convOutput_SPH();
/** デストラクタ */
~convOutput_SPH();
public:
/**
* @brief 出力ファイルをオープンする
* @param [in] prefix ファイル接頭文字
* @param [in] step ステップ数
* @param [in] id ランク番号
* @param [in] mio 出力時の分割指定 true = local / false = gather(default)
*/
cdm_FILE* OutputFile_Open(
const std::string prefix,
const unsigned step,
const int id,
const bool mio);
/**
* @brief sphファイルのheaderの書き込み
* @param[in] step ステップ数
* @param[in] dim 変数の個数
* @param[in] d_type データ型タイプ
* @param[in] imax x方向ボクセルサイズ
* @param[in] jmax y方向ボクセルサイズ
* @param[in] kmax z方向ボクセルサイズ
* @param[in] time 時間
* @param[in] org 原点座標
* @param[in] pit ピッチ
* @param[in] prefix ファイル接頭文字
* @param[in] pFile 出力ファイルポインタ
*/
bool
WriteHeaderRecord(int step,
int dim,
CDM::E_CDM_DTYPE d_type,
int imax,
int jmax,
int kmax,
double time,
double* org,
double* pit,
const std::string prefix,
cdm_FILE *pFile);
/**
* @brief マーカーの書き込み
* @param[in] dmy マーカー
* @param[in] pFile 出力ファイルポインタ
* @param[in] out plot3d用
*/
bool
WriteDataMarker(int dmy, cdm_FILE* pFile, bool out);
protected:
};
#endif // _CONVOUTPUT_SPH_H_
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_IMAGE_IMAGE_UTIL_H_
#define UI_GFX_IMAGE_IMAGE_UTIL_H_
#include <vector>
#include "base/basictypes.h"
#include "ui/gfx/gfx_export.h"
namespace gfx {
class Image;
}
namespace gfx {
// Creates an image from the given JPEG-encoded input. If there was an error
// creating the image, returns an IsEmpty() Image.
UI_EXPORT Image ImageFrom1xJPEGEncodedData(const unsigned char* input,
size_t input_size);
// Fills the |dst| vector with JPEG-encoded bytes of the 1x representation of
// the given image.
// Returns true if the image has a 1x representation and the 1x representation
// was encoded successfully.
// |quality| determines the compression level, 0 == lowest, 100 == highest.
// Returns true if the Image was encoded successfully.
UI_EXPORT bool JPEG1xEncodedDataFromImage(const Image& image,
int quality,
std::vector<unsigned char>* dst);
} // namespace gfx
#endif // UI_GFX_IMAGE_IMAGE_UTIL_H_
|
/*
* Copyright (c) 2006, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* wrapper pow(x,y) return x**y
*/
#include "fdlibm.h"
#ifdef __STDC__
double pow(double x, double y) /* wrapper pow */
#else
double pow(x,y) /* wrapper pow */
double x,y;
#endif
{
#ifdef _IEEE_LIBM
return __ieee754_pow(x,y);
#else
double z;
z=__ieee754_pow(x,y);
if(_LIB_VERSION == _IEEE_|| isnan(y)) return z;
if(isnan(x)) {
if(y==0.0)
return __kernel_standard(x,y,42); /* pow(NaN,0.0) */
else
return z;
}
if(x==0.0){
if(y==0.0)
return __kernel_standard(x,y,20); /* pow(0.0,0.0) */
if(finite(y)&&y<0.0)
return __kernel_standard(x,y,23); /* pow(0.0,negative) */
return z;
}
if(!finite(z)) {
if(finite(x)&&finite(y)) {
if(isnan(z))
return __kernel_standard(x,y,24); /* pow neg**non-int */
else
return __kernel_standard(x,y,21); /* pow overflow */
}
}
if(z==0.0&&finite(x)&&finite(y))
return __kernel_standard(x,y,22); /* pow underflow */
return z;
#endif
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_HTTP_HTTP_STREAM_PARSER_H_
#define NET_HTTP_HTTP_STREAM_PARSER_H_
#include <string>
#include "base/basictypes.h"
#include "net/base/io_buffer.h"
#include "net/base/load_log.h"
#include "net/base/upload_data_stream.h"
#include "net/http/http_chunked_decoder.h"
#include "net/http/http_response_info.h"
#include "net/socket/client_socket_handle.h"
namespace net {
class ClientSocketHandle;
class HttpRequestInfo;
class HttpStreamParser {
public:
// Any data in |read_buffer| will be used before reading from the socket
// and any data left over after parsing the stream will be put into
// |read_buffer|. The left over data will start at offset 0 and the
// buffer's offset will be set to the first free byte. |read_buffer| may
// have its capacity changed.
HttpStreamParser(ClientSocketHandle* connection,
GrowableIOBuffer* read_buffer,
LoadLog* load_log);
~HttpStreamParser() {}
// These functions implement the interface described in HttpStream with
// some additional functionality
int SendRequest(const HttpRequestInfo* request, const std::string& headers,
UploadDataStream* request_body, HttpResponseInfo* response,
CompletionCallback* callback);
int ReadResponseHeaders(CompletionCallback* callback);
int ReadResponseBody(IOBuffer* buf, int buf_len,
CompletionCallback* callback);
uint64 GetUploadProgress() const;
HttpResponseInfo* GetResponseInfo();
bool IsResponseBodyComplete() const;
bool CanFindEndOfResponse() const;
bool IsMoreDataBuffered() const;
private:
// FOO_COMPLETE states implement the second half of potentially asynchronous
// operations and don't necessarily mean that FOO is complete.
enum State {
STATE_NONE,
STATE_SENDING_HEADERS,
STATE_SENDING_BODY,
STATE_REQUEST_SENT,
STATE_READ_HEADERS,
STATE_READ_HEADERS_COMPLETE,
STATE_BODY_PENDING,
STATE_READ_BODY,
STATE_READ_BODY_COMPLETE,
STATE_DONE
};
// The number of bytes by which the header buffer is grown when it reaches
// capacity.
enum { kHeaderBufInitialSize = 4096 };
// |kMaxHeaderBufSize| is the number of bytes that the response headers can
// grow to. If the body start is not found within this range of the
// response, the transaction will fail with ERR_RESPONSE_HEADERS_TOO_BIG.
// Note: |kMaxHeaderBufSize| should be a multiple of |kHeaderBufInitialSize|.
enum { kMaxHeaderBufSize = 256 * 1024 }; // 256 kilobytes.
// The maximum sane buffer size.
enum { kMaxBufSize = 2 * 1024 * 1024 }; // 2 megabytes.
// Handle callbacks.
void OnIOComplete(int result);
// Try to make progress sending/receiving the request/response.
int DoLoop(int result);
// The implementations of each state of the state machine.
int DoSendHeaders(int result);
int DoSendBody(int result);
int DoReadHeaders();
int DoReadHeadersComplete(int result);
int DoReadBody();
int DoReadBodyComplete(int result);
// Examines |read_buf_| to find the start and end of the headers. Return
// the offset for the end of the headers, or -1 if the complete headers
// were not found. If they are are found, parse them with
// DoParseResponseHeaders().
int ParseResponseHeaders();
// Parse the headers into response_.
void DoParseResponseHeaders(int end_of_header_offset);
// Examine the parsed headers to try to determine the response body size.
void CalculateResponseBodySize();
// Current state of the request.
State io_state_;
// The request to send.
const HttpRequestInfo* request_;
// The request header data.
scoped_refptr<DrainableIOBuffer> request_headers_;
// The request body data.
scoped_ptr<UploadDataStream> request_body_;
// Temporary buffer for reading.
scoped_refptr<GrowableIOBuffer> read_buf_;
// Offset of the first unused byte in |read_buf_|. May be nonzero due to
// a 1xx header, or body data in the same packet as header data.
int read_buf_unused_offset_;
// The amount beyond |read_buf_unused_offset_| where the status line starts;
// -1 if not found yet.
int response_header_start_offset_;
// The parsed response headers. Owned by the caller.
HttpResponseInfo* response_;
// Indicates the content length. If this value is less than zero
// (and chunked_decoder_ is null), then we must read until the server
// closes the connection.
int64 response_body_length_;
// Keep track of the number of response body bytes read so far.
int64 response_body_read_;
// Helper if the data is chunked.
scoped_ptr<HttpChunkedDecoder> chunked_decoder_;
// Where the caller wants the body data.
scoped_refptr<IOBuffer> user_read_buf_;
int user_read_buf_len_;
// The callback to notify a user that their request or response is
// complete or there was an error
CompletionCallback* user_callback_;
// In the client callback, the client can do anything, including
// destroying this class, so any pending callback must be issued
// after everything else is done. When it is time to issue the client
// callback, move it from |user_callback_| to |scheduled_callback_|.
CompletionCallback* scheduled_callback_;
// The underlying socket.
ClientSocketHandle* const connection_;
scoped_refptr<LoadLog> load_log_;
// Callback to be used when doing IO.
CompletionCallbackImpl<HttpStreamParser> io_callback_;
DISALLOW_COPY_AND_ASSIGN(HttpStreamParser);
};
} // namespace net
#endif // NET_HTTP_HTTP_STREAM_PARSER_H_
|
/****************************************************************************
**
** BSD 3-Clause License
**
** Copyright (c) 2017, bitdewy
** All rights reserved.
**
****************************************************************************/
#pragma once
#include <QtCore/QMap>
#include <QtGui/QIcon>
class Property;
class BoolPropertyManager;
class BoolPropertyManagerPrivate
{
BoolPropertyManager* boolPropertyManagerPtr_;
friend class BoolPropertyManager;
public:
BoolPropertyManagerPrivate();
BoolPropertyManagerPrivate(const BoolPropertyManagerPrivate&) = delete;
BoolPropertyManagerPrivate& operator=(const BoolPropertyManagerPrivate&) = delete;
QMap<const Property*, bool> values_;
const QIcon checkedIcon_;
const QIcon uncheckedIcon_;
};
|
#include <lib.h>
#include <string.h>
/* lsearch(3) and lfind(3)
*
* Author: Terrence W. Holm Sep. 1988
*/
#include <stddef.h>
char *lsearch(key, base, count, width, keycmp)
char *key;
char *base;
unsigned *count;
unsigned width;
_PROTOTYPE( int (*keycmp), (const void *, const void *));
{
char *entry;
char *last = base + *count * width;
for (entry = base; entry < last; entry += width)
if (keycmp(key, entry) == 0) return(entry);
bcopy(key, last, width);
*count += 1;
return(last);
}
char *lfind(key, base, count, width, keycmp)
char *key;
char *base;
unsigned *count;
unsigned width;
_PROTOTYPE( int (*keycmp), (const void *, const void *));
{
char *entry;
char *last = base + *count * width;
for (entry = base; entry < last; entry += width)
if (keycmp(key, entry) == 0) return(entry);
return((char *)NULL);
}
|
/* $OpenBSD: limits.h,v 1.5 1998/03/22 21:15:24 millert Exp $ */
/* $NetBSD: limits.h,v 1.7 1996/01/05 18:10:57 pk Exp $ */
/*
* Copyright (c) 1988 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)limits.h 8.3 (Berkeley) 1/4/94
*/
#define CHAR_BIT 8 /* number of bits in a char */
#define MB_LEN_MAX 1 /* no multibyte characters */
#define SCHAR_MIN (-0x7f-1) /* max value for a signed char */
#define SCHAR_MAX 0x7f /* min value for a signed char */
#define UCHAR_MAX 0xffU /* max value for an unsigned char */
#define CHAR_MAX 0x7f /* max value for a char */
#define CHAR_MIN (-0x7f-1) /* min value for a char */
#define USHRT_MAX 0xffffU /* max value for an unsigned short */
#define SHRT_MAX 0x7fff /* max value for a short */
#define SHRT_MIN (-0x7fff-1) /* min value for a short */
#define UINT_MAX 0xffffffffU /* max value for an unsigned int */
#define INT_MAX 0x7fffffff /* max value for an int */
#define INT_MIN (-0x7fffffff-1) /* min value for an int */
#define ULONG_MAX 0xffffffffUL /* max value for an unsigned long */
#define LONG_MAX 0x7fffffffL /* max value for a long */
#define LONG_MIN (-0x7fffffffL-1) /* min value for a long */
#if !defined(_ANSI_SOURCE)
#define SSIZE_MAX INT_MAX /* max value for a ssize_t */
#if !defined(_POSIX_SOURCE) && !defined(_XOPEN_SOURCE)
#define SIZE_T_MAX UINT_MAX /* max value for a size_t */
#define UID_MAX UINT_MAX /* max value for a uid_t */
#define GID_MAX UINT_MAX /* max value for a gid_t */
/* GCC requires that quad constants be written as expressions. */
#define UQUAD_MAX ((u_quad_t)0-1) /* max value for a uquad_t */
/* max value for a quad_t */
#define QUAD_MAX ((quad_t)(UQUAD_MAX >> 1))
#define QUAD_MIN (-QUAD_MAX-1) /* min value for a quad_t */
#endif /* !_POSIX_SOURCE && !_XOPEN_SOURCE */
#endif /* !_ANSI_SOURCE */
#if (!defined(_ANSI_SOURCE)&&!defined(_POSIX_SOURCE)) || defined(_XOPEN_SOURCE)
#define LONG_BIT 32
#define WORD_BIT 32
#define DBL_DIG 15
#define DBL_MAX 1.7976931348623157E+308
#define DBL_MIN 2.2250738585072014E-308
#define FLT_DIG 6
#define FLT_MAX 3.40282347E+38F
#define FLT_MIN 1.17549435E-38F
#endif
|
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// This example code is from the book:
//
// Object-Oriented Programming with C++ and OSF/Motif
// by
// Douglas Young
// Prentice Hall, 1992
// ISBN 0-13-630252-1
//
// Copyright 1991 by Prentice Hall
// All Rights Reserved
//
// Permission to use, copy, modify, and distribute this software for
// any purpose except publication and without fee is hereby granted, provided
// that the above copyright notice appear in all copies of the software.
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// DialogManager.h: A base class for cached dialogs
//////////////////////////////////////////////////////////
#ifndef DIALOGMANAGER_H
#define DIALOGMANAGER_H
#include "UIComponent.h"
#include "DialogCallbackData.h"
class DialogManager : public UIComponent {
private:
Widget getDialog();
static void destroyTmpDialogCallback ( Widget,
XtPointer,
XtPointer );
static void okCallback ( Widget,
XtPointer,
XtPointer );
static void cancelCallback ( Widget,
XtPointer,
XtPointer );
static void helpCallback ( Widget,
XtPointer,
XtPointer );
void cleanup ( Widget, DialogCallbackData* );
protected:
// Called to get a new dialog
virtual Widget createDialog ( Widget ) = 0;
public:
DialogManager ( const char * );
virtual Widget post ( const char *,
void *clientData = NULL,
DialogCallback ok = NULL,
DialogCallback cancel = NULL,
DialogCallback help = NULL );
};
#endif
|
// RUN: %clang_builtins %s %librt -o %t && %run %t
//===-- ctzti2_test.c - Test __ctzti2 -------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file tests __ctzti2 for the compiler_rt library.
//
//===----------------------------------------------------------------------===//
#include "int_lib.h"
#include <stdio.h>
#ifdef CRT_HAS_128BIT
// Returns: the number of trailing 0-bits
// Precondition: a != 0
COMPILER_RT_ABI si_int __ctzti2(ti_int a);
int test__ctzti2(ti_int a, si_int expected)
{
si_int x = __ctzti2(a);
if (x != expected)
{
twords at;
at.all = a;
printf("error in __ctzti2(0x%llX%.16llX) = %d, expected %d\n",
at.s.high, at.s.low, x, expected);
}
return x != expected;
}
char assumption_1[sizeof(ti_int) == 2*sizeof(di_int)] = {0};
#endif
int main()
{
#ifdef CRT_HAS_128BIT
if (test__ctzti2(0x00000001, 0))
return 1;
if (test__ctzti2(0x00000002, 1))
return 1;
if (test__ctzti2(0x00000003, 0))
return 1;
if (test__ctzti2(0x00000004, 2))
return 1;
if (test__ctzti2(0x00000005, 0))
return 1;
if (test__ctzti2(0x0000000A, 1))
return 1;
if (test__ctzti2(0x10000000, 28))
return 1;
if (test__ctzti2(0x20000000, 29))
return 1;
if (test__ctzti2(0x60000000, 29))
return 1;
if (test__ctzti2(0x80000000uLL, 31))
return 1;
if (test__ctzti2(0x0000050000000000uLL, 40))
return 1;
if (test__ctzti2(0x0200080000000000uLL, 43))
return 1;
if (test__ctzti2(0x7200000000000000uLL, 57))
return 1;
if (test__ctzti2(0x8000000000000000uLL, 63))
return 1;
if (test__ctzti2(make_ti(0x00000000A0000000LL, 0x0000000000000000LL), 93))
return 1;
if (test__ctzti2(make_ti(0xF000000000000000LL, 0x0000000000000000LL), 124))
return 1;
if (test__ctzti2(make_ti(0x8000000000000000LL, 0x0000000000000000LL), 127))
return 1;
#else
printf("skipped\n");
#endif
return 0;
}
|
/*
* from: FreeBSD: src/sys/tools/fw_stub.awk,v 1.6 2007/03/02 11:42:53 flz
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/dev/cxgb/cxgb_t3fw.c 189643 2009-03-10 19:22:45Z gnn $");
#include <sys/param.h>
#include <sys/errno.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/linker.h>
#include <sys/firmware.h>
#include <sys/systm.h>
#include <cxgb_t3fw.h>
#include <t3b_protocol_sram.h>
#include <t3b_tp_eeprom.h>
#include <t3c_protocol_sram.h>
#include <t3c_tp_eeprom.h>
static int
cxgb_t3fw_modevent(module_t mod, int type, void *unused)
{
const struct firmware *fp, *parent;
int error;
switch (type) {
case MOD_LOAD:
fp = firmware_register("cxgb_t3fw", t3fw,
(size_t)t3fw_length,
0, NULL);
if (fp == NULL)
goto fail_0;
parent = fp;
return (0);
fail_0:
return (ENXIO);
case MOD_UNLOAD:
error = firmware_unregister("cxgb_t3fw");
return (error);
}
return (EINVAL);
}
static moduledata_t cxgb_t3fw_mod = {
"cxgb_t3fw",
cxgb_t3fw_modevent,
0
};
DECLARE_MODULE(cxgb_t3fw, cxgb_t3fw_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
MODULE_VERSION(cxgb_t3fw, 1);
MODULE_DEPEND(cxgb_t3fw, firmware, 1, 1, 1);
static int
cxgb_t3b_protocol_sram_modevent(module_t mod, int type, void *unused)
{
const struct firmware *fp, *parent;
int error;
switch (type) {
case MOD_LOAD:
fp = firmware_register("cxgb_t3b_protocol_sram", t3b_protocol_sram,
(size_t)t3b_protocol_sram_length,
0, NULL);
if (fp == NULL)
goto fail_0;
parent = fp;
return (0);
fail_0:
return (ENXIO);
case MOD_UNLOAD:
error = firmware_unregister("cxgb_t3b_protocol_sram");
return (error);
}
return (EINVAL);
}
static moduledata_t cxgb_t3b_protocol_sram_mod = {
"cxgb_t3b_protocol_sram",
cxgb_t3b_protocol_sram_modevent,
0
};
DECLARE_MODULE(cxgb_t3b_protocol_sram, cxgb_t3b_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
MODULE_VERSION(cxgb_t3b_protocol_sram, 1);
MODULE_DEPEND(cxgb_t3b_protocol_sram, firmware, 1, 1, 1);
static int
cxgb_t3b_tp_eeprom_modevent(module_t mod, int type, void *unused)
{
const struct firmware *fp, *parent;
int error;
switch (type) {
case MOD_LOAD:
fp = firmware_register("cxgb_t3b_tp_eeprom", t3b_tp_eeprom,
(size_t)t3b_tp_eeprom_length,
0, NULL);
if (fp == NULL)
goto fail_0;
parent = fp;
return (0);
fail_0:
return (ENXIO);
case MOD_UNLOAD:
error = firmware_unregister("cxgb_t3b_tp_eeprom");
return (error);
}
return (EINVAL);
}
static moduledata_t cxgb_t3b_tp_eeprom_mod = {
"cxgb_t3b_tp_eeprom",
cxgb_t3b_tp_eeprom_modevent,
0
};
DECLARE_MODULE(cxgb_t3b_tp_eeprom, cxgb_t3b_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
MODULE_VERSION(cxgb_t3b_tp_eeprom, 1);
MODULE_DEPEND(cxgb_t3b_tp_eeprom, firmware, 1, 1, 1);
static int
cxgb_t3c_protocol_sram_modevent(module_t mod, int type, void *unused)
{
const struct firmware *fp, *parent;
int error;
switch (type) {
case MOD_LOAD:
fp = firmware_register("cxgb_t3c_protocol_sram", t3c_protocol_sram,
(size_t)t3c_protocol_sram_length,
0, NULL);
if (fp == NULL)
goto fail_0;
parent = fp;
return (0);
fail_0:
return (ENXIO);
case MOD_UNLOAD:
error = firmware_unregister("cxgb_t3c_protocol_sram");
return (error);
}
return (EINVAL);
}
static moduledata_t cxgb_t3c_protocol_sram_mod = {
"cxgb_t3c_protocol_sram",
cxgb_t3c_protocol_sram_modevent,
0
};
DECLARE_MODULE(cxgb_t3c_protocol_sram, cxgb_t3c_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
MODULE_VERSION(cxgb_t3c_protocol_sram, 1);
MODULE_DEPEND(cxgb_t3c_protocol_sram, firmware, 1, 1, 1);
static int
cxgb_t3c_tp_eeprom_modevent(module_t mod, int type, void *unused)
{
const struct firmware *fp, *parent;
int error;
switch (type) {
case MOD_LOAD:
fp = firmware_register("cxgb_t3c_tp_eeprom", t3c_tp_eeprom,
(size_t)t3c_tp_eeprom_length,
0, NULL);
if (fp == NULL)
goto fail_0;
parent = fp;
return (0);
fail_0:
return (ENXIO);
case MOD_UNLOAD:
error = firmware_unregister("cxgb_t3c_tp_eeprom");
return (error);
}
return (EINVAL);
}
static moduledata_t cxgb_t3c_tp_eeprom_mod = {
"cxgb_t3c_tp_eeprom",
cxgb_t3c_tp_eeprom_modevent,
0
};
DECLARE_MODULE(cxgb_t3c_tp_eeprom, cxgb_t3c_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
MODULE_VERSION(cxgb_t3c_tp_eeprom, 1);
MODULE_DEPEND(cxgb_t3c_tp_eeprom, firmware, 1, 1, 1);
|
/* copyright(C) 2002 H.Kawai (under KL-01). */
#include <stdio.h>
#include <stdlib.h>
int GO_fputc(int c, GO_FILE *stream)
{
if (stream->p >= stream->p1)
abort();
*stream->p++ = c;
/* GOL_debuglog(1, &c); */
return (unsigned char) c;
}
|
// xml_do_read.h see license.txt for copyright and terms of use
#ifndef XML_DO_READ_H
#define XML_DO_READ_H
class TranslationUnit;
class StringTable;
TranslationUnit *xmlDoRead(StringTable &strTable, char const *inputFname);
#endif // XML_DO_READ_H
|
/*@author gihan tharanga*/
#include <iostream>
#include <string>
//video capturing methods
int videoCapturing();
int videoCapOriginal();
/*detect the faces display the frames and number of face*/
int FaceDetector(std::string&);
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__short_rand_postdec_07.c
Label Definition File: CWE191_Integer_Underflow.label.xml
Template File: sources-sinks-07.tmpl.c
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: rand Set data to result of rand()
* GoodSource: Set data to a small, non-zero number (negative two)
* Sinks: decrement
* GoodSink: Ensure there will not be an underflow before decrementing data
* BadSink : Decrement data, which can cause an Underflow
* Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
*
* */
#include "std_testcase.h"
/* The variable below is not declared "const", but is never assigned
any other value so a tool should be able to identify that reads of
this will always give its initialized value. */
static int staticFive = 5;
#ifndef OMITBAD
void CWE191_Integer_Underflow__short_rand_postdec_07_bad()
{
short data;
data = 0;
if(staticFive==5)
{
/* POTENTIAL FLAW: Use a random value */
data = (short)RAND32();
}
if(staticFive==5)
{
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
short result = data;
printIntLine(result);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second staticFive==5 to staticFive!=5 */
static void goodB2G1()
{
short data;
data = 0;
if(staticFive==5)
{
/* POTENTIAL FLAW: Use a random value */
data = (short)RAND32();
}
if(staticFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Add a check to prevent an underflow from occurring */
if (data > SHRT_MIN)
{
data--;
short result = data;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
short data;
data = 0;
if(staticFive==5)
{
/* POTENTIAL FLAW: Use a random value */
data = (short)RAND32();
}
if(staticFive==5)
{
/* FIX: Add a check to prevent an underflow from occurring */
if (data > SHRT_MIN)
{
data--;
short result = data;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first staticFive==5 to staticFive!=5 */
static void goodG2B1()
{
short data;
data = 0;
if(staticFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */
data = -2;
}
if(staticFive==5)
{
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
short result = data;
printIntLine(result);
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
short data;
data = 0;
if(staticFive==5)
{
/* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */
data = -2;
}
if(staticFive==5)
{
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
short result = data;
printIntLine(result);
}
}
}
void CWE191_Integer_Underflow__short_rand_postdec_07_good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE191_Integer_Underflow__short_rand_postdec_07_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE191_Integer_Underflow__short_rand_postdec_07_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
#pragma once
#include "boxFilter.hpp"
class boxFilter_Separable_VHI_nonVec : public cp::BoxFilterBase
{
protected:
int ksize;
void filter_naive_impl() override;
void filter_omp_impl() override;
void operator()(const cv::Range& range) const override;
public:
boxFilter_Separable_VHI_nonVec(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType);
virtual void init();
};
class boxFilter_Separable_VHI_SSE : public boxFilter_Separable_VHI_nonVec
{
private:
__m128 mDiv;
void filter_naive_impl() override;
void filter_omp_impl() override;
void operator()(const cv::Range& range) const override;
public:
boxFilter_Separable_VHI_SSE(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType);
void init() override;
};
class boxFilter_Separable_VHI_AVX : public boxFilter_Separable_VHI_nonVec
{
private:
__m256 mDiv;
void filter_naive_impl() override;
void filter_omp_impl() override;
void operator()(const cv::Range& range) const override;
public:
boxFilter_Separable_VHI_AVX(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType);
void init() override;
};
|
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.in by autoheader. */
/* Whether to build xhprof as dynamic module */
#define COMPILE_DL_XHPROF 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if your C compiler doesn't accept -c and -o together. */
/* #undef NO_MINUS_C_MINUS_O */
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT ""
/* Define to the full name of this package. */
#define PACKAGE_NAME ""
/* Define to the full name and version of this package. */
#define PACKAGE_STRING ""
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME ""
/* Define to the version of this package. */
#define PACKAGE_VERSION ""
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
|
/*
* ColorBasedROIExtractorRGB.h
*
* Created on: Dec 2, 2011
* Author: Pinaki Sunil Banerjee
*/
#ifndef BRICS_3D_COLORBASEDROIEXTRACTORRGB_H_
#define BRICS_3D_COLORBASEDROIEXTRACTORRGB_H_
#include "IFiltering.h"
#include <stdlib.h>
#include <cmath>
#include <iostream>
#include <stdio.h>
#include <stdint.h>
namespace brics_3d {
/**
* @brief Extracts subset of input point cloud based on color-properties in RGB color space
* @ingroup filtering
*/
class ColorBasedROIExtractorRGB : public IFiltering {
int red;
int green;
int blue;
double distanceThresholdMinimum;
double distanceThresholdMaximum;
public:
ColorBasedROIExtractorRGB();
virtual ~ColorBasedROIExtractorRGB();
void filter(PointCloud3D* originalPointCloud, PointCloud3D* resultPointCloud);
// void extractColorBasedROI(brics_3d::ColoredPointCloud3D *in_cloud, brics_3d::ColoredPointCloud3D *out_cloud);
// void extractColorBasedROI(brics_3d::ColoredPointCloud3D *in_cloud, brics_3d::PointCloud3D *out_cloud);
int getBlue() const
{
return blue;
}
double getDistanceThresholdMinimum() const
{
return distanceThresholdMinimum;
}
void setDistanceThresholdMinimum(double distanceThreshold)
{
this->distanceThresholdMinimum = distanceThreshold;
}
double getDistanceThresholdMaximum() const
{
return distanceThresholdMaximum;
}
void setDistanceThresholdMaximum(double distanceThreshold)
{
this->distanceThresholdMaximum = distanceThreshold;
}
int getGreen() const
{
return green;
}
int getRed() const
{
return red;
}
void setBlue(int blue)
{
this->blue = blue;
}
void setGreen(int green)
{
this->green = green;
}
void setRed(int red)
{
this->red = red;
}
};
}
#endif /* BRICS_3D_COLORBASEDROIEXTRACTORRGB_H_ */
|
// Copyright 2015 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef COBALT_BINDINGS_TESTING_GLOBAL_INTERFACE_PARENT_H_
#define COBALT_BINDINGS_TESTING_GLOBAL_INTERFACE_PARENT_H_
#include "cobalt/script/wrappable.h"
namespace cobalt {
namespace bindings {
namespace testing {
class GlobalInterfaceParent : public script::Wrappable {
public:
virtual void ParentOperation() {}
DEFINE_WRAPPABLE_TYPE(GlobalInterfaceParent);
};
} // namespace testing
} // namespace bindings
} // namespace cobalt
#endif // COBALT_BINDINGS_TESTING_GLOBAL_INTERFACE_PARENT_H_
|
/*-
* Copyright (c) 2006 The FreeBSD Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/dev/tdfx/tdfx_linux.c 224778 2011-08-11 12:30:23Z rwatson $");
#include <sys/param.h>
#include <sys/capability.h>
#include <sys/file.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/proc.h>
#include <sys/systm.h>
#include <dev/tdfx/tdfx_linux.h>
LINUX_IOCTL_SET(tdfx, LINUX_IOCTL_TDFX_MIN, LINUX_IOCTL_TDFX_MAX);
/*
* Linux emulation IOCTL for /dev/tdfx
*/
static int
linux_ioctl_tdfx(struct thread *td, struct linux_ioctl_args* args)
{
int error = 0;
u_long cmd = args->cmd & 0xffff;
/* The structure passed to ioctl has two shorts, one int
and one void*. */
char d_pio[2*sizeof(short) + sizeof(int) + sizeof(void*)];
struct file *fp;
if ((error = fget(td, args->fd, CAP_IOCTL, &fp)) != 0)
return (error);
/* We simply copy the data and send it right to ioctl */
copyin((caddr_t)args->arg, &d_pio, sizeof(d_pio));
error = fo_ioctl(fp, cmd, (caddr_t)&d_pio, td->td_ucred, td);
fdrop(fp, td);
return error;
}
static int
tdfx_linux_modevent(struct module *mod __unused, int what, void *arg __unused)
{
switch (what) {
case MOD_LOAD:
case MOD_UNLOAD:
return (0);
}
return (EOPNOTSUPP);
}
static moduledata_t tdfx_linux_mod = {
"tdfx_linux",
tdfx_linux_modevent,
0
};
/* As in SYSCALL_MODULE */
DECLARE_MODULE(tdfx_linux, tdfx_linux_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
MODULE_VERSION(tdfx_linux, 1);
MODULE_DEPEND(tdfx_linux, tdfx, 1, 1, 1);
MODULE_DEPEND(tdfx_linux, linux, 1, 1, 1);
|
/*
* 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.
*
* Jordan K. Hubbard
* 29 August 1998
*
* $FreeBSD: src/sys/boot/common/interp_backslash.c,v 1.4 1999/08/28 00:39:47 peter Exp $
*
* Routine for doing backslash elimination.
*/
#include <stand.h>
#include <string.h>
#define DIGIT(x) (isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A')
/*
* backslash: Return malloc'd copy of str with all standard "backslash
* processing" done on it. Original can be free'd if desired.
*/
char *
backslash(char *str)
{
/*
* Remove backslashes from the strings. Turn \040 etc. into a single
* character (we allow eight bit values). Currently NUL is not
* allowed.
*
* Turn "\n" and "\t" into '\n' and '\t' characters. Etc.
*
*/
char *new_str;
int seenbs = 0;
int i = 0;
if ((new_str = strdup(str)) == NULL)
return NULL;
while (*str) {
if (seenbs) {
seenbs = 0;
switch (*str) {
case '\\':
new_str[i++] = '\\';
str++;
break;
/* preserve backslashed quotes, dollar signs */
case '\'':
case '"':
case '$':
new_str[i++] = '\\';
new_str[i++] = *str++;
break;
case 'b':
new_str[i++] = '\b';
str++;
break;
case 'f':
new_str[i++] = '\f';
str++;
break;
case 'r':
new_str[i++] = '\r';
str++;
break;
case 'n':
new_str[i++] = '\n';
str++;
break;
case 's':
new_str[i++] = ' ';
str++;
break;
case 't':
new_str[i++] = '\t';
str++;
break;
case 'v':
new_str[i++] = '\13';
str++;
break;
case 'z':
str++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
char val;
/* Three digit octal constant? */
if (*str >= '0' && *str <= '3' &&
*(str + 1) >= '0' && *(str + 1) <= '7' &&
*(str + 2) >= '0' && *(str + 2) <= '7') {
val = (DIGIT(*str) << 6) + (DIGIT(*(str + 1)) << 3) +
DIGIT(*(str + 2));
/* Allow null value if user really wants to shoot
at feet, but beware! */
new_str[i++] = val;
str += 3;
break;
}
/* One or two digit hex constant?
* If two are there they will both be taken.
* Use \z to split them up if this is not wanted.
*/
if (*str == '0' &&
(*(str + 1) == 'x' || *(str + 1) == 'X') &&
isxdigit(*(str + 2))) {
val = DIGIT(*(str + 2));
if (isxdigit(*(str + 3))) {
val = (val << 4) + DIGIT(*(str + 3));
str += 4;
}
else
str += 3;
/* Yep, allow null value here too */
new_str[i++] = val;
break;
}
}
break;
default:
new_str[i++] = *str++;
break;
}
}
else {
if (*str == '\\') {
seenbs = 1;
str++;
}
else
new_str[i++] = *str++;
}
}
if (seenbs) {
/*
* The final character was a '\'. Put it in as a single backslash.
*/
new_str[i++] = '\\';
}
new_str[i] = '\0';
return new_str;
}
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_CROSTINI_CROSTINI_ENGAGEMENT_METRICS_SERVICE_H_
#define CHROME_BROWSER_ASH_CROSTINI_CROSTINI_ENGAGEMENT_METRICS_SERVICE_H_
#include "base/macros.h"
#include "base/no_destructor.h"
#include "components/guest_os/guest_os_engagement_metrics.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "components/keyed_service/core/keyed_service.h"
class Profile;
namespace crostini {
// A KeyedService for tracking engagement with Crostini, reporting values as
// per GuestOsEngagementMetrics.
class CrostiniEngagementMetricsService : public KeyedService {
public:
class Factory : public BrowserContextKeyedServiceFactory {
public:
static CrostiniEngagementMetricsService* GetForProfile(Profile* profile);
static Factory* GetInstance();
private:
friend class base::NoDestructor<Factory>;
Factory();
~Factory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
bool ServiceIsCreatedWithBrowserContext() const override;
bool ServiceIsNULLWhileTesting() const override;
};
explicit CrostiniEngagementMetricsService(Profile* profile);
CrostiniEngagementMetricsService(const CrostiniEngagementMetricsService&) =
delete;
CrostiniEngagementMetricsService& operator=(
const CrostiniEngagementMetricsService&) = delete;
~CrostiniEngagementMetricsService() override;
// This needs to be called when Crostini starts and stops being active so we
// can correctly track background active time.
void SetBackgroundActive(bool background_active);
private:
std::unique_ptr<guest_os::GuestOsEngagementMetrics>
guest_os_engagement_metrics_;
};
} // namespace crostini
#endif // CHROME_BROWSER_ASH_CROSTINI_CROSTINI_ENGAGEMENT_METRICS_SERVICE_H_
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import <ABI42_0_0React/ABI42_0_0RCTView.h>
@interface ABI42_0_0RCTMaskedView : ABI42_0_0RCTView
@end
|
#ifndef MTF_MC_RSCV_H
#define MTF_MC_RSCV_H
#include "RSCV.h"
_MTF_BEGIN_NAMESPACE
class MCRSCV : public RSCV{
public:
MCRSCV(const ParamType *rscv_params = nullptr);
};
_MTF_END_NAMESPACE
#endif
|
#include <stdlib.h>
#include <stdio.h>
#include <utp.h>
#include <utp.c>
int test()
{
return -1;
}
int main(int argc, char ** argv)
{
if (argc != 2) {
fprintf(stderr, "usage: server <PORT>\n");
return EXIT_FAILURE;
}
int port = atoi(argv[1]);
printf("using port = %i\n", port);
struct usocket * sock = usocket();
if (sock == NULL) {
perror("unable to open socket");
return EXIT_FAILURE;
}
printf("socket opened 0x%x\n", sock);
struct sockaddr_in serv_addr;
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
int ret = ubind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (ret == -1) {
perror("unable to bind socket");
return EXIT_FAILURE;
}
printf("socket bound\n");
// TODO listen
int i = 0;
for (; ; ++i) {
struct sockaddr_in cli_addr;
socklen_t len = sizeof(cli_addr);
fprintf(stderr, "waiting for a connection\n");
struct usocket * conn = uaccept(sock, (struct sockaddr *)&cli_addr, &len);
if (conn == NULL) {
perror("accept");
continue;
}
fprintf(stderr, "opened %i connection\n", i);
//pid_t pid = fork();
int ret = uclose(conn);
if (ret == -1) {
perror("unable to close connection");
return EXIT_FAILURE;
}
}
ret = uclose(sock);
if (ret == -1) {
perror("unable to close socket");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
/*
* mplsred.h
*
* Copyright 2010 Daniel Mende <dmende@ernw.de>
*/
/*
* 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 the nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MPLSRED_H
#define MPLSRED_H 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <winsock2.h>
#include <time.h>
#else
#include <unistd.h>
#include <sys/time.h>
#endif
#include <dnet.h>
#include <pcap.h>
#define MAX_PACKET_LEN 1500
#define CHECK_FOR_LOCKFILE 1000
#define TIMEOUT_SEC 1
#define TIMEOUT_USEC 0
extern int mplsred(char*, char*, int, uint16_t, uint16_t, char*, char*, int);
#endif
|
/* $OpenBSD: tls_server.c,v 1.4 2015/02/07 06:19:26 jsing Exp $ */
/*
* Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <openssl/ec.h>
#include <openssl/ssl.h>
#include <tls.h>
#include "tls_internal.h"
struct tls *
tls_server(void)
{
struct tls *ctx;
if ((ctx = tls_new()) == NULL)
return (NULL);
ctx->flags |= TLS_SERVER;
return (ctx);
}
struct tls *
tls_server_conn(struct tls *ctx)
{
struct tls *conn_ctx;
if ((conn_ctx = tls_new()) == NULL)
return (NULL);
conn_ctx->flags |= TLS_SERVER_CONN;
return (conn_ctx);
}
int
tls_configure_server(struct tls *ctx)
{
EC_KEY *ecdh_key;
unsigned char sid[SSL_MAX_SSL_SESSION_ID_LENGTH];
if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
tls_set_error(ctx, "ssl context failure");
goto err;
}
if (tls_configure_ssl(ctx) != 0)
goto err;
if (tls_configure_keypair(ctx) != 0)
goto err;
if (ctx->config->dheparams == -1)
SSL_CTX_set_dh_auto(ctx->ssl_ctx, 1);
else if (ctx->config->dheparams == 1024)
SSL_CTX_set_dh_auto(ctx->ssl_ctx, 2);
if (ctx->config->ecdhecurve == -1) {
SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
} else if (ctx->config->ecdhecurve != NID_undef) {
if ((ecdh_key = EC_KEY_new_by_curve_name(
ctx->config->ecdhecurve)) == NULL) {
tls_set_error(ctx, "failed to set ECDHE curve");
goto err;
}
SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
SSL_CTX_set_tmp_ecdh(ctx->ssl_ctx, ecdh_key);
EC_KEY_free(ecdh_key);
}
/*
* Set session ID context to a random value. We don't support
* persistent caching of sessions so it is OK to set a temporary
* session ID context that is valid during run time.
*/
arc4random_buf(sid, sizeof(sid));
if (!SSL_CTX_set_session_id_context(ctx->ssl_ctx, sid, sizeof(sid))) {
tls_set_error(ctx, "failed to set session id context");
goto err;
}
return (0);
err:
return (-1);
}
int
tls_accept_socket(struct tls *ctx, struct tls **cctx, int socket)
{
struct tls *conn_ctx = *cctx;
int ret, err;
if ((ctx->flags & TLS_SERVER) == 0) {
tls_set_error(ctx, "not a server context");
goto err;
}
if (conn_ctx == NULL) {
if ((conn_ctx = tls_server_conn(ctx)) == NULL) {
tls_set_error(ctx, "connection context failure");
goto err;
}
*cctx = conn_ctx;
conn_ctx->socket = socket;
if ((conn_ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) {
tls_set_error(ctx, "ssl failure");
goto err;
}
if (SSL_set_fd(conn_ctx->ssl_conn, socket) != 1) {
tls_set_error(ctx, "ssl set fd failure");
goto err;
}
SSL_set_app_data(conn_ctx->ssl_conn, conn_ctx);
}
if ((ret = SSL_accept(conn_ctx->ssl_conn)) != 1) {
err = tls_ssl_error(conn_ctx, ret, "accept");
if (err == TLS_READ_AGAIN || err == TLS_WRITE_AGAIN) {
return (err);
}
goto err;
}
return (0);
err:
return (-1);
}
|
/*
Copyright (c) 2015, Kripasindhu Sarkar
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 the copyright holder(s) nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOS 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.
*/
//
// Created by sarkar on 03.06.15.
//
#pragma once
#include <string>
#include <vector>
#include "od/common/pipeline/Detection.h"
#include "od/common/pipeline/Scene.h"
namespace od
{
enum DetectionMethod {
PC_GLOBAL_FEATUREMATCHING,
PC_LOCAL_CORRESPONDENCE_GROUPING,
IMAGE_LOCAL_SIMPLE,
IMAGE_GLOBAL_DENSE,
IMAGE_GLOBAL_CLASSIFICATION,
};
/** \brief The common class for detectors. Both Trainers and Detectors drerives from this and therefore, all the common data/functionalities of Trainers and Detectors should go here.
*
*
* \author Kripasindhu Sarkar
*
*/
class DetectorCommon
{
public:
DetectorCommon(const std::string & trained_data_location);
DetectorCommon() {}
virtual void init() = 0;
/** \brief Gets/Sets the directory containing the data for training. The trainer uses the data from directory for training. Detectors can use this location to get additional information in its detection algirhtms as well.
*/
std::string getTrainingInputLocation() const;
/** \brief Gets/Sets the directory containing the data for training. The trainer uses the data from directory for training. Detectors can use this location to get additional information in its detection algirhtms as well.
*/
void setTrainingInputLocation(const std::string & training_input_location);
/** \brief Gets/Sets the base directory for trained data. This should be same for all Trainers and Detectors and can be considered as the 'database' of trained data. Trainers uses one of its
* subdirectories based on its type to store algo specific trained data. The corresponding Detector would use the same directory to fetch the trained data for online detection.
*/
std::string getTrainedDataLocation() const;
/** \brief The base directory for trained data. This should be same for all Trainers and Detectors and can be considered as the 'database' of trained data. Trainers uses one of its
* subdirectories based on its type to store algo specific trained data. The corresponding Detector would use the same directory to fetch the trained data for online detection.
*/
virtual void setTrainedDataLocation(const std::string & trained_data_location);
/** \brief Gets the specific directory for a Trainer or a Detector inside trained_data_location_.
*/
std::string getSpecificTrainingDataLocation();
std::string getSpecificTrainingData();
const std::string & getTrainedDataID() const;
void setTrainedDataID(const std::string & trainedDataID);
protected:
std::string training_input_location_, trained_data_location_;
std::string trained_data_id_, trained_location_identifier_;
};
/** \brief This is the main class for object detection and recognition.
*
*
* \author Kripasindhu Sarkar
*
*/
class ObjectDetector {
public:
const DetectionMethod & getMethod() const;
void setDetectionMethod(const DetectionMethod & detection_method);
bool getAlwaysTrain() const;
void setAlwaysTrain(bool always_train);
std::string getTrainingInputLocation() const;
void setTrainingInputLocation(const std::string & training_input_location);
std::string getTrainingDataLocation() const;
void setTrainingDataLocation(const std::string & training_data_location);
std::string getSpecificTrainingDataLocation();
virtual void init() = 0;
virtual void initDetector(){}
virtual void initTrainer(){}
virtual int train() = 0;
virtual int detect(shared_ptr<Scene> scene, const std::vector<shared_ptr<Detection> > & detections) = 0;
virtual shared_ptr<Detection> detect(shared_ptr<Scene> scene) = 0;
virtual shared_ptr<Detections> detectOmni(shared_ptr<Scene> scene) = 0;
protected:
DetectionMethod method_;
bool always_train_;
bool trained_;
std::string training_input_location_, training_data_location_;
std::string trained_data_ext_, trained_data_identifier_;
};
}
|
/*
Copyright (c) 2010 Anders Bakken
Copyright (c) 2010 Donald Carr
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 any associated
organizations nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
#ifndef PHONONBACKEND_H
#define PHONONBACKEND_H
#include <QtCore>
#include <phonon>
#include "backend.h"
#include "backendplugin.h"
struct Private;
class Q_DECL_EXPORT PhononBackend : public Backend
{
public:
PhononBackend(QObject *tail);
virtual ~PhononBackend();
virtual bool initBackend();
virtual void shutdown();
virtual bool trackData(TrackData *data, const QUrl &url, int types = All) const;
virtual bool isValid(const QUrl &url) const;
virtual void play();
virtual void pause();
virtual void setProgress(int type, int progress);
virtual int progress(int type);
virtual void stop();
virtual bool loadUrl(const QUrl &url);
virtual int status() const;
virtual int volume() const;
virtual void setVolume(int vol);
virtual QString errorMessage() const;
virtual int errorCode() const;
virtual void setMute(bool on);
virtual bool isMute() const;
virtual int flags() const;
private:
Private *d;
};
class Q_DECL_EXPORT PhononBackendPlugin : public BackendPlugin
{
public:
PhononBackendPlugin() : BackendPlugin(QStringList() << "phonon" << "phononbackend") {}
virtual Backend *createBackend(QObject *parent)
{
return new PhononBackend(parent);
}
};
#endif
|
/*============================================================================
WCSLIB 7.6 - an implementation of the FITS WCS standard.
Copyright (C) 1995-2021, Mark Calabretta
This file is part of WCSLIB.
WCSLIB is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
WCSLIB is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with WCSLIB. If not, see http://www.gnu.org/licenses.
Author: Mark Calabretta, Australia Telescope National Facility, CSIRO.
http://www.atnf.csiro.au/people/Mark.Calabretta
$Id: log.h,v 7.6 2021/04/13 12:57:01 mcalabre Exp $
*=============================================================================
*
* WCSLIB 7.6 - C routines that implement the FITS World Coordinate System
* (WCS) standard. Refer to the README file provided with WCSLIB for an
* overview of the library.
*
*
* Summary of the log routines
* ---------------------------
* Routines in this suite implement the part of the FITS World Coordinate
* System (WCS) standard that deals with logarithmic coordinates, as described
* in
*
* "Representations of world coordinates in FITS",
* Greisen, E.W., & Calabretta, M.R. 2002, A&A, 395, 1061 (WCS Paper I)
*
* "Representations of spectral coordinates in FITS",
* Greisen, E.W., Calabretta, M.R., Valdes, F.G., & Allen, S.L.
* 2006, A&A, 446, 747 (WCS Paper III)
*
* These routines define methods to be used for computing logarithmic world
* coordinates from intermediate world coordinates (a linear transformation of
* image pixel coordinates), and vice versa.
*
* logx2s() and logs2x() implement the WCS logarithmic coordinate
* transformations.
*
* Argument checking:
* ------------------
* The input log-coordinate values are only checked for values that would
* result in floating point exceptions and the same is true for the
* log-coordinate reference value.
*
* Accuracy:
* ---------
* No warranty is given for the accuracy of these routines (refer to the
* copyright notice); intending users must satisfy for themselves their
* adequacy for the intended purpose. However, closure effectively to within
* double precision rounding error was demonstrated by test routine tlog.c
* which accompanies this software.
*
*
* logx2s() - Transform to logarithmic coordinates
* -----------------------------------------------
* logx2s() transforms intermediate world coordinates to logarithmic
* coordinates.
*
* Given and returned:
* crval double Log-coordinate reference value (CRVALia).
*
* Given:
* nx int Vector length.
*
* sx int Vector stride.
*
* slogc int Vector stride.
*
* x const double[]
* Intermediate world coordinates, in SI units.
*
* Returned:
* logc double[] Logarithmic coordinates, in SI units.
*
* stat int[] Status return value status for each vector element:
* 0: Success.
*
* Function return value:
* int Status return value:
* 0: Success.
* 2: Invalid log-coordinate reference value.
*
*
* logs2x() - Transform logarithmic coordinates
* --------------------------------------------
* logs2x() transforms logarithmic world coordinates to intermediate world
* coordinates.
*
* Given and returned:
* crval double Log-coordinate reference value (CRVALia).
*
* Given:
* nlogc int Vector length.
*
* slogc int Vector stride.
*
* sx int Vector stride.
*
* logc const double[]
* Logarithmic coordinates, in SI units.
*
* Returned:
* x double[] Intermediate world coordinates, in SI units.
*
* stat int[] Status return value status for each vector element:
* 0: Success.
* 1: Invalid value of logc.
*
* Function return value:
* int Status return value:
* 0: Success.
* 2: Invalid log-coordinate reference value.
* 4: One or more of the world-coordinate values
* are incorrect, as indicated by the stat vector.
*
*
* Global variable: const char *log_errmsg[] - Status return messages
* ------------------------------------------------------------------
* Error messages to match the status value returned from each function.
*
*===========================================================================*/
#ifndef WCSLIB_LOG
#define WCSLIB_LOG
#ifdef __cplusplus
extern "C" {
#endif
extern const char *log_errmsg[];
enum log_errmsg_enum {
LOGERR_SUCCESS = 0, // Success.
LOGERR_NULL_POINTER = 1, // Null pointer passed.
LOGERR_BAD_LOG_REF_VAL = 2, // Invalid log-coordinate reference value.
LOGERR_BAD_X = 3, // One or more of the x coordinates were
// invalid.
LOGERR_BAD_WORLD = 4 // One or more of the world coordinates were
// invalid.
};
int logx2s(double crval, int nx, int sx, int slogc, const double x[],
double logc[], int stat[]);
int logs2x(double crval, int nlogc, int slogc, int sx, const double logc[],
double x[], int stat[]);
#ifdef __cplusplus
}
#endif
#endif // WCSLIB_LOG
|
extern zend_class_entry *ice_mvc_service_ce;
ZEPHIR_INIT_CLASS(Ice_Mvc_Service);
PHP_METHOD(Ice_Mvc_Service, setModel);
PHP_METHOD(Ice_Mvc_Service, getModel);
PHP_METHOD(Ice_Mvc_Service, __call);
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_mvc_service_setmodel, 0, 0, 1)
ZEND_ARG_INFO(0, model)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_mvc_service_getmodel, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_mvc_service___call, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, method, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, method)
#endif
ZEND_ARG_INFO(0, arguments)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(ice_mvc_service_method_entry) {
PHP_ME(Ice_Mvc_Service, setModel, arginfo_ice_mvc_service_setmodel, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Mvc_Service, getModel, arginfo_ice_mvc_service_getmodel, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Mvc_Service, __call, arginfo_ice_mvc_service___call, ZEND_ACC_PUBLIC)
PHP_FE_END
};
|
/*
* Copyright 2004-2009, IM Kit Team. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _LOGGER_H
#define _LOGGER_H
void logmsg(const char* message, ...);
#endif // _LOGGER_H
|
#ifndef SSERVICE_LOGGER_H
#define SSERVICE_LOGGER_H
/******************************************************************************
"Copyright (c) 2015-2015, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"
******************************************************************************/
/** @file
@brief Logger system header.
*/
#include "xss_types.h"
#include "xss_error.h"
/**
* @enum log_target_t defines Types of log messages
*/
#define LOG_ERROR_VAL (0)
#define LOG_WARNING_VAL (1)
#define LOG_INFO_VAL (2)
#define LOG_ALL_VAL ( 0xff )
typedef enum
{
LOG_ERROR = LOG_ERROR_VAL, /**< error. Operation is not successfull; Continue to run */
LOG_WARNING = LOG_WARNING_VAL, /**< Warning. Operation is finished successfully, but there is something to notify (Old keys?) */
LOG_INFO = LOG_INFO_VAL, /**< Information to developer; */
LOG_ALL = LOG_ALL_VAL, /**< Cannot be passed to log, it is just set for Log filtering: Print ALL logs */
} sservice_log_level_t ;
#define LOG_SOURCE_JS_VAL (2)
#define LOG_SOURCE_BRIDGE_VAL (1)
#define LOG_SOURCE_RUNTIME_VAL (0)
typedef enum
{
LOG_SOURCE_JS=LOG_SOURCE_JS_VAL,
LOG_SOURCE_BRIDGE = LOG_SOURCE_BRIDGE_VAL,
LOG_SOURCE_RUNTIME = LOG_SOURCE_RUNTIME_VAL,
} sservice_log_source_t ;
#endif
|
// 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.
#ifndef MEDIA_GPU_TEST_VIDEO_PLAYER_TEST_VDA_VIDEO_DECODER_H_
#define MEDIA_GPU_TEST_VIDEO_PLAYER_TEST_VDA_VIDEO_DECODER_H_
#include <stdint.h>
#include <map>
#include <memory>
#include "base/containers/lru_cache.h"
#include "base/macros.h"
#include "base/sequence_checker.h"
#include "gpu/ipc/service/gpu_memory_buffer_factory.h"
#include "media/base/video_decoder.h"
#include "media/gpu/test/video_player/video_decoder_client.h"
#include "media/media_buildflags.h"
#include "media/video/video_decode_accelerator.h"
namespace media {
class VideoFrame;
namespace test {
class FrameRenderer;
// The test VDA video decoder translates between the media::VideoDecoder and the
// media::VideoDecodeAccelerator interfaces. This makes it possible to run
// VD-based tests against VDA's.
class TestVDAVideoDecoder : public media::VideoDecoder,
public VideoDecodeAccelerator::Client {
public:
// Constructor for the TestVDAVideoDecoder.
TestVDAVideoDecoder(bool use_vd_vda,
const gfx::ColorSpace& target_color_space,
FrameRenderer* const frame_renderer,
gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory);
TestVDAVideoDecoder(const TestVDAVideoDecoder&) = delete;
TestVDAVideoDecoder& operator=(const TestVDAVideoDecoder&) = delete;
~TestVDAVideoDecoder() override;
// media::VideoDecoder implementation
VideoDecoderType GetDecoderType() const override;
bool IsPlatformDecoder() const override;
void Initialize(const VideoDecoderConfig& config,
bool low_delay,
CdmContext* cdm_context,
InitCB init_cb,
const OutputCB& output_cb,
const WaitingCB& waiting_cb) override;
void Decode(scoped_refptr<DecoderBuffer> buffer, DecodeCB decode_cb) override;
void Reset(base::OnceClosure reset_cb) override;
bool NeedsBitstreamConversion() const override;
bool CanReadWithoutStalling() const override;
int GetMaxDecodeRequests() const override;
private:
// media::VideoDecodeAccelerator::Client implementation
void NotifyInitializationComplete(Status status) override;
void ProvidePictureBuffers(uint32_t requested_num_of_buffers,
VideoPixelFormat format,
uint32_t textures_per_buffer,
const gfx::Size& dimensions,
uint32_t texture_target) override;
void ProvidePictureBuffersWithVisibleRect(uint32_t requested_num_of_buffers,
VideoPixelFormat format,
uint32_t textures_per_buffer,
const gfx::Size& dimensions,
const gfx::Rect& visible_rect,
uint32_t texture_target) override;
void DismissPictureBuffer(int32_t picture_buffer_id) override;
void PictureReady(const Picture& picture) override;
void ReusePictureBufferTask(int32_t picture_buffer_id);
void NotifyEndOfBitstreamBuffer(int32_t bitstream_buffer_id) override;
void NotifyFlushDone() override;
void NotifyResetDone() override;
void NotifyError(VideoDecodeAccelerator::Error error) override;
// Helper thunk to avoid dereferencing WeakPtrs on the wrong thread.
static void ReusePictureBufferThunk(
absl::optional<base::WeakPtr<TestVDAVideoDecoder>> decoder_client,
scoped_refptr<base::SequencedTaskRunner> task_runner,
int32_t picture_buffer_id);
// Get the next bitstream buffer id to be used.
int32_t GetNextBitstreamBufferId();
// Get the next picture buffer id to be used.
int32_t GetNextPictureBufferId();
// Called when initialization is done. The callback is stored only when VDA
// allows deferred initialization.
InitCB init_cb_;
// Called when a buffer is decoded.
OutputCB output_cb_;
// Called when the decoder finished flushing.
DecodeCB flush_cb_;
// Called when the decoder finished resetting.
base::OnceClosure reset_cb_;
// Whether VdVideoDecodeAccelerator is used.
bool use_vd_vda_;
// Output color space, used as hint to decoder to avoid conversions.
const gfx::ColorSpace target_color_space_;
// Frame renderer used to manage GL context.
FrameRenderer* const frame_renderer_;
#if BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION)
// Owned by VideoDecoderClient.
gpu::GpuMemoryBufferFactory* const gpu_memory_buffer_factory_;
#endif // BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION)
// Map of video frames the decoder uses as output, keyed on picture buffer id.
std::map<int32_t, scoped_refptr<VideoFrame>> video_frames_;
// Map of video frame decoded callbacks, keyed on bitstream buffer id.
std::map<int32_t, DecodeCB> decode_cbs_;
// Records the time at which each bitstream buffer decode operation started.
base::LRUCache<int32_t, base::TimeDelta> decode_start_timestamps_;
int32_t next_bitstream_buffer_id_ = 0;
int32_t next_picture_buffer_id_ = 0;
std::unique_ptr<VideoDecodeAccelerator> decoder_;
scoped_refptr<base::SequencedTaskRunner> vda_wrapper_task_runner_;
SEQUENCE_CHECKER(vda_wrapper_sequence_checker_);
base::WeakPtr<TestVDAVideoDecoder> weak_this_;
base::WeakPtrFactory<TestVDAVideoDecoder> weak_this_factory_{this};
};
} // namespace test
} // namespace media
#endif // MEDIA_GPU_TEST_VIDEO_PLAYER_TEST_VDA_VIDEO_DECODER_H_
|
//
// BenthosLibraryTableCell.h
// SeafloorExplore
//
// Modified from Brad Larson's Molecules Project in 2011-2012 for use in The SeafloorExplore Project
//
// Copyright (C) 2012 Matthew Johnson-Roberson
//
// See COPYING for license details
//
// Molecules
//
// The source code for Molecules is available under a BSD license. See COPYING for details.
//
// Created by Brad Larson on 4/30/2011.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface BenthosLibraryTableCell : UITableViewCell
{
CAGradientLayer *highlightGradientLayer;
BOOL isSelected;
}
@property(assign, nonatomic) CAGradientLayer *highlightGradientLayer;
@property(assign, nonatomic) BOOL isSelected;
@end
|
/*
* Kit.h
*
* Created on: 21 Aug 2016
* Author: jeremy
*/
#ifndef SOURCE_DRUMKIT_KITS_KIT_H_
#define SOURCE_DRUMKIT_KITS_KIT_H_
#include "KitParameters.h"
#include "KitManager.h"
#include "../../Sound/SoundBank/SoundBank.h"
#include "../Instruments/Instrument.h"
#include "../Triggers/Triggers/Trigger.h"
#include <string>
#include <vector>
namespace DrumKit
{
class Kit
{
public:
Kit(const KitParameters& params, std::vector<TriggerPtr> const& trigs, std::shared_ptr<Sound::SoundBank> sb);
virtual ~Kit();
void Enable();
void Disable();
void Save() const { KitManager::SaveKit(parameters.configFilePath, parameters);}
void SetInstrumentVolume(size_t id, float volume);
std::string GetConfigFilePath() const noexcept { return parameters.configFilePath; }
float GetInstrumentVolume(int id) const { return instruments[id]->GetVolume(); }
std::string GetInstrumentName(std::size_t id) const;
std::string GetName() const noexcept { return parameters.kitName; }
int GetNumInstruments() const { return (int)parameters.instrumentParameters.size(); }
const std::vector<InstrumentPtr>& GetInstruments() const { return instruments; }
private:
void CreateInstruments();
KitParameters parameters;
const std::vector<TriggerPtr>& triggers;
std::shared_ptr<Sound::SoundBank> soundBank;
std::vector<InstrumentPtr> instruments;
};
} /* namespace DrumKit */
#endif /* SOURCE_DRUMKIT_KITS_KIT_H_ */
|
/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
\file cmdtextfield.h
\date Dec 2011
\author TNick
\brief Contains the definition for CmdTextField class
*//*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please read COPYING and README files in root folder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
#ifndef __CMDTEXTFIELD_INC__
#define __CMDTEXTFIELD_INC__
//
//
//
//
/* INCLUDES ------------------------------------------------------------ */
#include <QPlainTextEdit>
#include <QLabel>
#include <QStringList>
/* INCLUDES ============================================================ */
//
//
//
//
/* CLASS --------------------------------------------------------------- */
namespace Gui {
/**
* @brief class representing a plain text control that interprets commands
*/
class CmdTextField :public QPlainTextEdit {
Q_OBJECT
//
//
//
//
/* DEFINITIONS ----------------------------------------------------- */
/* DEFINITIONS ===================================================== */
//
//
//
//
/* DATA ------------------------------------------------------------ */
private:
/**
* @brief associated log panel
*/
QPlainTextEdit * tx_Log;
/**
* @brief the label shown in front of text
*/
QLabel * lbl_;
/**
* @brief previously inputted text
*/
QStringList tx_prev_;
/**
* @brief index of previously inputted text
*/
int prev_idx_;
/* DATA ============================================================ */
//
//
//
//
/* FUNCTIONS ------------------------------------------------------- */
public:
/**
* @brief constructor;
*/
CmdTextField ( QWidget * parent = 0 );
/**
* @brief constructor;
*/
CmdTextField ( QPlainTextEdit * log_target, QWidget * parent = 0 );
/**
* @brief destructor;
*/
virtual ~CmdTextField ( void );
/**
* @brief get
*/
inline QPlainTextEdit * assocLog ( void )
{ return tx_Log; }
/**
* @brief set
*/
inline void setAssocLog ( QPlainTextEdit * new_val )
{ tx_Log = new_val; }
/**
* @brief change the text displayied at the left of the input box
*/
void setLabelText (
const QString & new_val = QString()
);
protected:
/**
* @brief filter the keys
*/
void keyPressEvent ( QKeyEvent *e );
/**
* @brief helps us keep the label in place
*/
void resizeEvent ( QResizeEvent * );
private:
/**
* @brief common initialisation to all constructors
*/
void init ( void );
/**
* @brief append a new string to the list
*/
void appendCommand ( const QString & s_in );
/**
* @brief get previously entered string at index i
*/
QString previousCommand ( int i = 0 );
/* FUNCTIONS ======================================================= */
//
//
//
//
}; /* class CmdTextField */
/* CLASS =============================================================== */
//
//
//
//
} // namespace Gui
#endif // __CMDTEXTFIELD_INC__
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2021 musikcube team
//
// 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 the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
extern "C" {
#pragma warning(push, 0)
#include <microhttpd.h>
#pragma warning(pop)
}
#include "Context.h"
#include <condition_variable>
#include <mutex>
#include <vector>
#if MHD_VERSION < 0x00097001
#define MHD_Result int
#endif
class HttpServer {
public:
HttpServer(Context& context);
~HttpServer();
bool Start();
bool Stop();
void Wait();
private:
static MHD_Result HandleRequest(
void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method,
const char *version,
const char *upload_data,
size_t *upload_data_size,
void **con_cls);
static size_t HandleUnescape(
void * cls,
struct MHD_Connection *c,
char *s);
static int HandleAudioTrackRequest(
HttpServer* server,
MHD_Response*& response,
MHD_Connection* connection,
std::vector<std::string>& pathParts);
static int HandleThumbnailRequest(
HttpServer* server,
MHD_Response*& response,
MHD_Connection* connection,
std::vector<std::string>& pathParts);
struct MHD_Daemon *httpServer;
Context& context;
volatile bool running;
std::condition_variable exitCondition;
std::mutex exitMutex;
};
|
#ifndef REGRESS_H
#define REGRESS_H
/* Macro to shorten code where a number is added to the current value of an
* element in a matrix. */
#define addval(A, VAL, I, J) setval((A), (VAL) + val((A), (I), (J)), (I), (J))
typedef struct {
double **array;
int rows;
int cols;
} matrix;
void DestroyMatrix(matrix*);
matrix* CalcMinor(matrix*, int, int);
double CalcDeterminant(matrix*);
int nCols(matrix*);
int nRows(matrix*);
double val(matrix*, int, int);
void setval(matrix*, double, int, int);
matrix* CreateMatrix(int, int);
matrix* mtxtrn(matrix*);
matrix* mtxmul(matrix*, matrix*);
matrix* CalcAdj(matrix*);
matrix* CalcInv(matrix*);
matrix* regress(matrix*, matrix*);
matrix* polyfit(matrix*, matrix*, int);
matrix* ParseMatrix(char*);
matrix* linspace(double, double, int);
void Map(matrix*, double (*func)(double));
void mtxprnt(matrix*);
void mtxprntfile(matrix*, char*);
#endif
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_COMPONENTS_PHONEHUB_FAKE_NOTIFICATION_ACCESS_MANAGER_H_
#define ASH_COMPONENTS_PHONEHUB_FAKE_NOTIFICATION_ACCESS_MANAGER_H_
#include "ash/components/phonehub/notification_access_manager.h"
namespace ash {
namespace phonehub {
class FakeNotificationAccessManager : public NotificationAccessManager {
public:
explicit FakeNotificationAccessManager(
AccessStatus access_status = AccessStatus::kAvailableButNotGranted);
~FakeNotificationAccessManager() override;
using NotificationAccessManager::IsSetupOperationInProgress;
void SetAccessStatusInternal(AccessStatus access_status) override;
void SetNotificationSetupOperationStatus(
NotificationAccessSetupOperation::Status new_status);
// NotificationAccessManager:
AccessStatus GetAccessStatus() const override;
bool HasNotificationSetupUiBeenDismissed() const override;
void DismissSetupRequiredUi() override;
void ResetHasNotificationSetupUiBeenDismissed();
private:
AccessStatus access_status_;
bool has_notification_setup_ui_been_dismissed_ = false;
};
} // namespace phonehub
} // namespace ash
// TODO(https://crbug.com/1164001): remove after the migration is finished.
namespace chromeos {
namespace phonehub {
using ::ash::phonehub::FakeNotificationAccessManager;
}
} // namespace chromeos
#endif // ASH_COMPONENTS_PHONEHUB_FAKE_NOTIFICATION_ACCESS_MANAGER_H_
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SYSTEM_AUDIO_TRAY_AUDIO_H_
#define ASH_SYSTEM_AUDIO_TRAY_AUDIO_H_
#include "ash/system/audio/audio_observer.h"
#include "ash/system/tray/tray_image_item.h"
#include "base/memory/scoped_ptr.h"
namespace ash {
namespace system {
class TrayAudioDelegate;
}
namespace internal {
namespace tray {
class VolumeView;
}
class TrayAudio : public TrayImageItem,
public AudioObserver {
public:
TrayAudio(SystemTray* system_tray,
scoped_ptr<system::TrayAudioDelegate> audio_delegate);
virtual ~TrayAudio();
protected:
virtual void Update();
scoped_ptr<system::TrayAudioDelegate> audio_delegate_;
tray::VolumeView* volume_view_;
// True if VolumeView should be created for accelerator pop up;
// Otherwise, it should be created for detailed view in ash tray bubble.
bool pop_up_volume_view_;
private:
// Overridden from TrayImageItem.
virtual bool GetInitialVisibility() OVERRIDE;
// Overridden from SystemTrayItem.
virtual views::View* CreateDefaultView(user::LoginStatus status) OVERRIDE;
virtual views::View* CreateDetailedView(user::LoginStatus status) OVERRIDE;
virtual void DestroyDefaultView() OVERRIDE;
virtual void DestroyDetailedView() OVERRIDE;
virtual bool ShouldHideArrow() const OVERRIDE;
virtual bool ShouldShowShelf() const OVERRIDE;
// Overridden from AudioObserver.
virtual void OnOutputVolumeChanged() OVERRIDE;
virtual void OnOutputMuteChanged() OVERRIDE;
virtual void OnAudioNodesChanged() OVERRIDE;
virtual void OnActiveOutputNodeChanged() OVERRIDE;
virtual void OnActiveInputNodeChanged() OVERRIDE;
DISALLOW_COPY_AND_ASSIGN(TrayAudio);
};
} // namespace internal
} // namespace ash
#endif // ASH_SYSTEM_AUDIO_TRAY_AUDIO_H_
|
//
// CEDestinySDK.h
// CEDestinySDK
//
// Created by Caleb Eades on 11/12/15.
// Copyright (c) 2015 Caleb Eades. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for CEDestinySDK.
FOUNDATION_EXPORT double CEDestinySDKVersionNumber;
//! Project version string for CEDestinySDK.
FOUNDATION_EXPORT const unsigned char CEDestinySDKVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <CEDestinySDK/PublicHeader.h>
#import "CEDestinySDK.h"
|
#ifndef CTRL_PARTITION_H
#define CTRL_PARTITION_H
#include <wx/panel.h>
//#include <wx/sizer.h>
enum CTRL_STATE
{
S_IDLE,
S_LEFT_SLIDER,
S_RIGHT_SLIDER,
S_MOVE
};
class wxPartition : public wxPanel
{
static const int slider_width = 10;
int slider_left_pos;
int slider_right_pos;
CTRL_STATE state;
unsigned n_steps;
wxMouseEvent mouse_old_pos;
bool enabled;
public:
wxPartition(wxWindow *parent,
wxWindowID winid = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString &name = wxPanelNameStr);
void SetNumberOfSteps(unsigned n_steps){this->n_steps=n_steps;}
unsigned GetNumberOfSteps(){return n_steps;}
bool SetLeftSliderPos(unsigned pos);
bool SetRightSliderPos(unsigned pos);
unsigned GetLeftSliderPos();
unsigned GetRightSliderPos();
bool Enable(bool enable=true);
void paintEvent(wxPaintEvent & evt);
void paintNow();
void render(wxDC& dc);
void mouseMoved(wxMouseEvent& event);
void mouseDown(wxMouseEvent& event);
void mouseReleased(wxMouseEvent& event);
void mouseLeftWindow(wxMouseEvent& event);
void mouseLeftDoubleClick(wxMouseEvent& event);
DECLARE_EVENT_TABLE()
};
#endif
|
#ifndef __KIDS_CONFIG_H_
#define __KIDS_CONFIG_H_
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#define NLIMIT_NORMAL 0
#define NLIMIT_NETWORKSTORE 1
#define NLIMIT_PUBSUB 2
struct LimitConfig {
int hard_limit_bytes;
int soft_limit_bytes;
int soft_limit_seconds;
};
struct StoreConfig {
~StoreConfig() {
for (std::vector<StoreConfig*>::iterator it = stores.begin(); it != stores.end(); ++it) {
delete *it;
}
}
std::string type;
std::string buffer_type;
std::string socket;
std::string host;
std::string port;
std::string path;
std::string name;
std::string rotate;
std::string success;
std::string topic;
std::vector<StoreConfig*> stores;
};
struct KidsConfig {
KidsConfig() : store(NULL) { memset(nlimit, 0, sizeof(nlimit)); }
~KidsConfig() { delete store; }
std::string listen_socket;
std::string listen_host;
std::string listen_port;
std::string log_level;
std::string log_file;
std::string max_clients;
std::string worker_threads;
std::string ignore_case;
LimitConfig nlimit[3];
StoreConfig *store;
};
struct Token {
Token() {}
Token(int tid, char *s, char *e) {
id = tid;
while (s < e) {
value.push_back(*s);
s++;
}
}
int id;
std::string value;
};
struct KeyValue {
KeyValue(std::string k, std::vector<std::string>* v)
:key(k), value(*v) {}
std::string key;
std::vector<std::string> value;
};
struct ParseContext {
ParseContext() : line(0), success(true), conf(NULL) {}
~ParseContext() { delete conf; }
int line;
bool success;
char error[1025];
KidsConfig *conf;
};
ParseContext *ParseConfigFile(const std::string& filename);
ParseContext *ParseConfig(std::string str);
#endif // __KIDS_CONFIG_H_
|
// Copyright 2010-2016, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef MOZC_WIN32_BASE_OMAHA_UTIL_H_
#define MOZC_WIN32_BASE_OMAHA_UTIL_H_
// Omaha is the code name of Google Update, which is not used in
// OSS version of Mozc.
#if !defined(GOOGLE_JAPANESE_INPUT_BUILD)
#error OmahaUtil must be used with Google Japanese Input, not OSS Mozc
#endif // !GOOGLE_JAPANESE_INPUT_BUILD
#include <windows.h>
#include <string>
#include "base/port.h"
namespace mozc {
namespace win32 {
// TODO(yukawa): Add unit test for this class.
class OmahaUtil {
public:
// Writes the channel name specified by |value| for Omaha.
// Returns true if the operation completed successfully.
static bool WriteChannel(const wstring &value);
// Reads the channel name for Omaha.
// Returns an empty string if there is no entry or fails to retrieve the
// channel name.
static wstring ReadChannel();
// Clears the registry entry to specify error message for Omaha.
// Returns true if the operation completed successfully.
static bool ClearOmahaError();
// Writes the registry entry for Omaha to show some error messages.
// Returns true if the operation completed successfully.
static bool WriteOmahaError(const wstring &ui_message, const wstring &header);
// Clears the registry entry for the channel name.
// Returns true if the operation completed successfully.
static bool ClearChannel();
private:
DISALLOW_COPY_AND_ASSIGN(OmahaUtil);
};
} // namespace win32
} // namespace mozc
#endif // MOZC_WIN32_BASE_OMAHA_UTIL_H_
|
/* $NetBSD: proc.h,v 1.8 1996/11/25 22:09:11 gwr Exp $ */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: proc.h 8.1 (Berkeley) 6/10/93
*/
/*
* Machine-dependent part of the proc structure for sun3.
*/
struct mdproc {
int *md_regs; /* registers on current frame */
int md_flags; /* machine-dependent flags */
};
/* md_flags */
#define MDP_FPUSED 0x0001 /* floating point coprocessor used */
#define MDP_STACKADJ 0x0002 /* frame SP adjusted, might have to
undo when system call returns
ERESTART. */
#define MDP_HPUXTRACE 0x0004 /* being traced by HP-UX process */
|
/*
* Copyright (c) 2006, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* ceil(x)
* Return x rounded toward -inf to integral value
* Method:
* Bit twiddling.
* Exception:
* Inexact flag raised if x not equal to ceil(x).
*/
#include "fdlibm.h"
#ifdef __STDC__
static const double huge = 1.0e300;
#else
static double huge = 1.0e300;
#endif
#ifdef __STDC__
double ceil(double x)
#else
double ceil(x)
double x;
#endif
{
int i0,i1,j0;
unsigned i,j;
i0 = __HI(x);
i1 = __LO(x);
j0 = ((i0>>20)&0x7ff)-0x3ff;
if(j0<20) {
if(j0<0) { /* raise inexact if x != 0 */
if(huge+x>0.0) {/* return 0*sign(x) if |x|<1 */
if(i0<0) {i0=0x80000000;i1=0;}
else if((i0|i1)!=0) { i0=0x3ff00000;i1=0;}
}
} else {
i = (0x000fffff)>>j0;
if(((i0&i)|i1)==0) return x; /* x is integral */
if(huge+x>0.0) { /* raise inexact flag */
if(i0>0) i0 += (0x00100000)>>j0;
i0 &= (~i); i1=0;
}
}
} else if (j0>51) {
if(j0==0x400) return x+x; /* inf or NaN */
else return x; /* x is integral */
} else {
i = ((unsigned)(0xffffffff))>>(j0-20);
if((i1&i)==0) return x; /* x is integral */
if(huge+x>0.0) { /* raise inexact flag */
if(i0>0) {
if(j0==20) i0+=1;
else {
j = i1 + (1<<(52-j0));
if(j<i1) i0+=1; /* got a carry */
i1 = j;
}
}
i1 &= (~i);
}
}
__HI(x) = i0;
__LO(x) = i1;
return x;
}
|
#include <core/Runtime.h>
#include <stdlib.h>
#include <math.h>
int runtime_f32_mul(Stack stack)
{
Value* operand1 = NULL;
Value* operand2 = NULL;
pop_Value(stack, &operand2);
pop_Value(stack, &operand1);
if(isnan(operand1->value.f32) || isnan(operand2->value.f32)) {
push_Value(stack, new_f32Value(nanf("")));
} else if(isinf(operand1->value.f32) || isinf(operand2->value.f32)) {
if(operand1->value.f32 == 0 || operand2->value.f32 == 0) {
push_Value(stack, new_f32Value(nanf("")));
} else if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) {
push_Value(stack, new_f32Value(-strtof("INF", NULL)));
} else {
push_Value(stack, new_f32Value(strtof("INF", NULL)));
}
} else if(operand1->value.f32 == 0 && operand2->value.f32 == 0) {
if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) {
push_Value(stack, new_f32Value(-0.0f));
} else {
push_Value(stack, new_f32Value(+0.0f));
}
} else {
push_Value(stack, new_f32Value(operand1->value.f32 * operand2->value.f32));
}
free_Value(operand1);
free_Value(operand2);
return 0;
}
|
/*
* ctm-cvb
*
* CollapsedBayesEngine
*/
#ifndef COLLAPSED_BAYES_ENGINE_H
#define COLLAPSED_BAYES_ENGINE_H
#include "InferenceEngine.h"
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
namespace ctm
{
class CollapsedBayesEngine : public InferenceEngine
{
/***
* Model hyperparameters learnt by maximisation
*/
struct Model
{
gsl_vector* mu;
gsl_matrix* cov;
gsl_matrix* inv_cov;
gsl_matrix* log_beta;
double gamma;
double log_det_inv_cov;
Model( int D, int K, int V );
~Model();
};
/***
* Data collected in the 'expectation' step, to be used in the
* maximisation step.
*/
struct CollectedData
{
// Expected counts
gsl_matrix* n_ij;
gsl_matrix* n_jk;
double ndata;
CollectedData( int D, int K, int V );
~CollectedData();
};
/***
* Variational parameters to be optimised in the expectation step
*/
struct Parameters
{
// Stores \phi_{*kj}
gsl_matrix* phi;
gsl_matrix* log_phi;
// Likelihood saved for optimisation purposes
double lhood;
Parameters( int K, int V );
~Parameters();
};
public:
CollapsedBayesEngine(InferenceOptions& options);
// Load/Store in a file
virtual void init( string filename );
virtual void save( string filename );
// Parse a single file
virtual double infer( Corpus& data );
virtual double infer( Corpus& data, CollectedData* cd );
virtual void estimate( Corpus& data );
protected:
Model* model;
};
};
#endif // COLLAPSED_BAYES_ENGINE_H
|
/*
* This file is part of the MIAMI framework. For copyright information, see
* the LICENSE file in the MIAMI root folder.
*/
/*
* File: TemplateExecutionUnit.h
* Author: Gabriel Marin, mgabi99@gmail.com
*
* Defines data structure to hold information about the use pattern of an
* execution unit type as part of an instruction execution template.
*/
#ifndef _TEMPLATE_EXECUTION_UNIT_H_
#define _TEMPLATE_EXECUTION_UNIT_H_
#include <stdio.h>
#include <stdlib.h>
#include "BitSet.h"
#include <list>
namespace MIAMI
{
#define EXACT_MATCH_ALLOCATE 0
class TemplateExecutionUnit
{
public:
TemplateExecutionUnit (int _unit, BitSet* _umask, int _count);
~TemplateExecutionUnit ()
{
if (unit_mask)
delete unit_mask;
}
inline BitSet* UnitsMask () const { return (unit_mask); }
inline int Count () const { return (count); }
int index;
int count;
BitSet *unit_mask;
};
typedef std::list<TemplateExecutionUnit*> TEUList;
} /* namespace MIAMI */
#endif
|
// 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.
#ifndef MEDIA_VIDEO_SUPPORTED_VIDEO_DECODER_CONFIG_H_
#define MEDIA_VIDEO_SUPPORTED_VIDEO_DECODER_CONFIG_H_
#include <vector>
#include "base/containers/flat_map.h"
#include "base/macros.h"
#include "media/base/media_export.h"
#include "media/base/video_codecs.h"
#include "media/base/video_decoder_config.h"
#include "ui/gfx/geometry/size.h"
namespace media {
// Specification of a range of configurations that are supported by a video
// decoder. Also provides the ability to check if a VideoDecoderConfig matches
// the supported range.
struct MEDIA_EXPORT SupportedVideoDecoderConfig {
SupportedVideoDecoderConfig();
SupportedVideoDecoderConfig(VideoCodecProfile profile_min,
VideoCodecProfile profile_max,
const gfx::Size& coded_size_min,
const gfx::Size& coded_size_max,
bool allow_encrypted,
bool require_encrypted);
~SupportedVideoDecoderConfig();
// Returns true if and only if |config| is a supported config.
bool Matches(const VideoDecoderConfig& config) const;
// Range of VideoCodecProfiles to match, inclusive.
VideoCodecProfile profile_min = VIDEO_CODEC_PROFILE_UNKNOWN;
VideoCodecProfile profile_max = VIDEO_CODEC_PROFILE_UNKNOWN;
// Coded size range, inclusive.
gfx::Size coded_size_min;
gfx::Size coded_size_max;
// TODO(liberato): consider switching these to "allow_clear" and
// "allow_encrypted", so that they're orthogonal.
// If true, then this will match encrypted configs.
bool allow_encrypted = true;
// If true, then unencrypted configs will not match.
bool require_encrypted = false;
// Allow copy and assignment.
};
// Enumeration of possible implementations for (Mojo)VideoDecoders.
enum class VideoDecoderImplementation {
kDefault = 0,
kAlternate = 1,
kMaxValue = kAlternate
};
using SupportedVideoDecoderConfigs = std::vector<SupportedVideoDecoderConfig>;
// Map of mojo VideoDecoder implementations to the vector of configs that they
// (probably) support.
using SupportedVideoDecoderConfigMap =
base::flat_map<VideoDecoderImplementation, SupportedVideoDecoderConfigs>;
// Helper method to determine if |config| is supported by |supported_configs|.
MEDIA_EXPORT bool IsVideoDecoderConfigSupported(
const SupportedVideoDecoderConfigs& supported_configs,
const VideoDecoderConfig& config);
} // namespace media
#endif // MEDIA_VIDEO_SUPPORTED_VIDEO_DECODER_CONFIG_H_
|
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "MockORKTask.h"
#import "MockTrackedDataStore.h"
#import "MockAppInfoDelegate.h"
#import "MockKeychainWrapper.h"
#import "BridgeSDKTestable.h"
|
#ifndef ENTRY_H
#define ENTRY_H
#include "Object.h"
#include "CompiledCode.h"
#include "String.h"
#define ENTRY_MAX_ARGS_SIZE 16
typedef struct {
_Bool isHandle;
union { Value value; Object *handle; };
} EntryArg;
typedef struct {
size_t size;
EntryArg values[ENTRY_MAX_ARGS_SIZE];
} EntryArgs;
Value invokeMethod(CompiledMethod *method, EntryArgs *args);
Value invokeInititalize(Object *object);
Value sendMessage(String *selector, EntryArgs *args);
Value evalCode(char *source);
_Bool parseFileAndInitialize(char *filename, Value *lastBlockResult);
_Bool parseFile(char *filename, OrderedCollection *classes, OrderedCollection *blocks);
static void entryArgsAddObject(EntryArgs *args, Object *object)
{
intptr_t index = args->size++;
ASSERT(index <= ENTRY_MAX_ARGS_SIZE);
args->values[index].isHandle = 1;
args->values[index].handle = object;
}
static void entryArgsAdd(EntryArgs *args, Value value)
{
intptr_t index = args->size++;
ASSERT(index <= ENTRY_MAX_ARGS_SIZE);
args->values[index].isHandle = 0;
args->values[index].value = value;
}
#endif
|
// Copyright (c) 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.
#ifndef QUICHE_QUIC_QBONE_QBONE_CLIENT_INTERFACE_H_
#define QUICHE_QUIC_QBONE_QBONE_CLIENT_INTERFACE_H_
#include <cstdint>
#include "absl/strings/string_view.h"
namespace quic {
// An interface that includes methods to interact with a QBONE client.
class QboneClientInterface {
public:
virtual ~QboneClientInterface() {}
// Accepts a given packet from the network and sends the packet down to the
// QBONE connection.
virtual void ProcessPacketFromNetwork(absl::string_view packet) = 0;
};
} // namespace quic
#endif // QUICHE_QUIC_QBONE_QBONE_CLIENT_INTERFACE_H_
|
/**
* Copyright (c) 2019, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com>
* ESP8266/005
* Blinky example using pure ESP8266 Non-OS SDK.
*/
#include "ets_sys.h"
#include "osapi.h"
#include "gpio.h"
#include "os_type.h"
#include "user_config.h"
#define LED_PIN (2)
static volatile os_timer_t blinky_timer;
static void blinky_timer_handler(void *prv);
void ICACHE_FLASH_ATTR
user_init()
{
uint8_t value = 0;
/* setup */
gpio_init(); // init gpio subsytem
gpio_output_set(0, 0, (1 << LED_PIN), 0); // set LED pin as output with low state
uart_div_modify(0, UART_CLK_FREQ / 115200); // set UART baudrate
os_printf("\n\nSDK version:%s\n\n", system_get_sdk_version());
/* start timer (500ms) */
os_timer_setfn(&blinky_timer, (os_timer_func_t *)blinky_timer_handler, NULL);
os_timer_arm(&blinky_timer, 500, 1);
}
void
blinky_timer_handler(void *prv)
{
if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & (1 << LED_PIN)) {
gpio_output_set(0, (1 << LED_PIN), 0, 0); // LED off
} else {
gpio_output_set((1 << LED_PIN), 0, 0, 0); // LED on
}
}
|
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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.
*
*/
#pragma once
#if defined(BUILDING_LIBHOSTILE)
# if defined(HAVE_VISIBILITY) && HAVE_VISIBILITY
# define LIBHOSTILE_API __attribute__ ((visibility("default")))
# define LIBHOSTILE_LOCAL __attribute__ ((visibility("hidden")))
# elif defined (__SUNPRO_C) && (__SUNPRO_C >= 0x550)
# define LIBHOSTILE_API __global
# define LIBHOSTILE_LOCAL __global
# elif defined(_MSC_VER)
# define LIBHOSTILE_API extern __declspec(dllexport)
# define LIBHOSTILE_LOCAL extern __declspec(dllexport)
# else
# define LIBHOSTILE_API
# define LIBHOSTILE_LOCAL
# endif /* defined(HAVE_VISIBILITY) */
#else /* defined(BUILDING_LIBHOSTILE) */
# if defined(_MSC_VER)
# define LIBHOSTILE_API extern __declspec(dllimport)
# define LIBHOSTILE_LOCAL
# else
# define LIBHOSTILE_API
# define LIBHOSTILE_LOCAL
# endif /* defined(_MSC_VER) */
#endif /* defined(BUILDING_LIBHOSTILE) */
|
//
// text_recognizer.h
// STR
//
// Created by vampirewalk on 2015/4/14.
// Copyright (c) 2015年 mocacube. All rights reserved.
//
#ifndef __STR__text_recognizer__
#define __STR__text_recognizer__
#include <iostream>
#include <string>
#include <vector>
#include <opencv2/text.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
class TextRecognizer {
public:
TextRecognizer(){};
std::vector<std::string> recognize(std::vector<char> data);
};
#endif /* defined(__STR__text_recognizer__) */
|
/*
* ArrayEntryType.h
*
* Created on: Nov 14, 2012
* Author: Mitchell Wills
*/
#ifndef ARRAYENTRYTYPE_H_
#define ARRAYENTRYTYPE_H_
#include <stdlib.h>
#include <stdio.h>
#ifndef _WRS_KERNEL
#include <stdint.h>
#endif
class ArrayEntryType;
#include "ArrayData.h"
#include "ComplexEntryType.h"
struct ArrayEntryData{
uint8_t length;
EntryValue* array;
};
/**
* Represents the size and contents of an array.
*/
typedef struct ArrayEntryData ArrayEntryData;
/**
* Represents the type of an array entry value.
*/
class ArrayEntryType : public ComplexEntryType {//TODO allow for array of complex type
private:
NetworkTableEntryType& m_elementType;
public:
/**
* Creates a new ArrayEntryType.
*
* @param id The ID which identifies this type to other nodes on
* across the network.
* @param elementType The type of the elements this array contains.
*/
ArrayEntryType(TypeId id, NetworkTableEntryType& elementType);
/**
* Creates a copy of an value which is of the type contained by
* this array.
*
* @param value The element, of this array's contained type, to
* copy.
* @return A copy of the given value.
*/
EntryValue copyElement(EntryValue value);
/**
* Deletes a entry value which is of the type contained by
* this array.
*
* After calling this method, the given entry value is
* no longer valid.
*
* @param value The value to delete.
*/
void deleteElement(EntryValue value);
/**
* See {@link NetworkTableEntryType}::sendValue
*/
void sendValue(EntryValue value, DataIOStream& os);
/**
* See {@link NetworkTableEntryType}::readValue
*/
EntryValue readValue(DataIOStream& is);
/**
* See {@link NetworkTableEntryType}::copyValue
*/
EntryValue copyValue(EntryValue value);
/**
* See {@link NetworkTableEntryType}::deleteValue
*/
void deleteValue(EntryValue value);
/**
* See {@link ComplexEntryType}::internalizeValue
*/
EntryValue internalizeValue(std::string& key, ComplexData& externalRepresentation, EntryValue currentInteralValue);
/**
* See {@link ComplexEntryType}::exportValue
*/
void exportValue(std::string& key, EntryValue internalData, ComplexData& externalRepresentation);
};
#endif /* ARRAYENTRYTYPE_H_ */
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_environment_w32_spawnv_61b.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-61b.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: environment Read input from an environment variable
* GoodSource: Fixed string
* Sinks: w32_spawnv
* BadSink : execute command with spawnv
* Flow Variant: 61 Data flow: data returned from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#define ENV_VARIABLE "ADD"
#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif
#include <process.h>
#ifndef OMITBAD
char * CWE78_OS_Command_Injection__char_environment_w32_spawnv_61b_badSource(char * data)
{
{
/* Append input from an environment variable to data */
size_t dataLen = strlen(data);
char * environment = GETENV(ENV_VARIABLE);
/* If there is data in the environment variable */
if (environment != NULL)
{
/* POTENTIAL FLAW: Read data from an environment variable */
strncat(data+dataLen, environment, 100-dataLen-1);
}
}
return data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
char * CWE78_OS_Command_Injection__char_environment_w32_spawnv_61b_goodG2BSource(char * data)
{
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
return data;
}
#endif /* OMITGOOD */
|
// Copyright 2021-present 650 Industries. All rights reserved.
#import <Foundation/Foundation.h>
#import <ABI44_0_0UMTaskManagerInterface/ABI44_0_0UMTaskConsumerInterface.h>
NS_ASSUME_NONNULL_BEGIN
@interface ABI44_0_0EXBackgroundRemoteNotificationConsumer : NSObject <ABI44_0_0UMTaskConsumerInterface>
@property (nonatomic, strong) id<ABI44_0_0UMTaskInterface> task;
@end
NS_ASSUME_NONNULL_END
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__fgets_malloc_03.c
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-03.tmpl.c
*/
/*
* @description
* CWE: 194 Unexpected Sign Extension
* BadSource: fgets Read data from the console using fgets()
* GoodSource: Positive integer
* Sink: malloc
* BadSink : Allocate memory using malloc() with the size of data
* Flow Variant: 03 Control flow: if(5==5) and if(5!=5)
*
* */
#include "std_testcase.h"
/* Must be at least 8 for atoi() to work properly */
#define CHAR_ARRAY_SIZE 8
#ifndef OMITBAD
void CWE194_Unexpected_Sign_Extension__fgets_malloc_03_bad()
{
short data;
/* Initialize data */
data = 0;
if(5==5)
{
{
char inputBuffer[CHAR_ARRAY_SIZE] = "";
/* FLAW: Use a value input from the console using fgets() */
if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
{
/* Convert to short */
data = (short)atoi(inputBuffer);
}
else
{
printLine("fgets() failed.");
}
}
}
/* Assume we want to allocate a relatively small buffer */
if (data < 100)
{
/* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
* the conversion will cause malloc() to allocate a very large amount of data or fail */
char * dataBuffer = (char *)malloc(data);
if (dataBuffer == NULL) {exit(-1);}
/* Do something with dataBuffer */
memset(dataBuffer, 'A', data-1);
dataBuffer[data-1] = '\0';
printLine(dataBuffer);
free(dataBuffer);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the 5==5 to 5!=5 */
static void goodG2B1()
{
short data;
/* Initialize data */
data = 0;
if(5!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a positive integer less than &InitialDataSize&*/
data = 100-1;
}
/* Assume we want to allocate a relatively small buffer */
if (data < 100)
{
/* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
* the conversion will cause malloc() to allocate a very large amount of data or fail */
char * dataBuffer = (char *)malloc(data);
if (dataBuffer == NULL) {exit(-1);}
/* Do something with dataBuffer */
memset(dataBuffer, 'A', data-1);
dataBuffer[data-1] = '\0';
printLine(dataBuffer);
free(dataBuffer);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
short data;
/* Initialize data */
data = 0;
if(5==5)
{
/* FIX: Use a positive integer less than &InitialDataSize&*/
data = 100-1;
}
/* Assume we want to allocate a relatively small buffer */
if (data < 100)
{
/* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
* the conversion will cause malloc() to allocate a very large amount of data or fail */
char * dataBuffer = (char *)malloc(data);
if (dataBuffer == NULL) {exit(-1);}
/* Do something with dataBuffer */
memset(dataBuffer, 'A', data-1);
dataBuffer[data-1] = '\0';
printLine(dataBuffer);
free(dataBuffer);
}
}
void CWE194_Unexpected_Sign_Extension__fgets_malloc_03_good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE194_Unexpected_Sign_Extension__fgets_malloc_03_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE194_Unexpected_Sign_Extension__fgets_malloc_03_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_RENDERER_CHROME_RENDER_THREAD_OBSERVER_H_
#define CHROME_RENDERER_CHROME_RENDER_THREAD_OBSERVER_H_
#include <memory>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "build/chromeos_buildflags.h"
#include "chrome/common/renderer_configuration.mojom.h"
#include "components/content_settings/common/content_settings_manager.mojom.h"
#include "components/content_settings/core/common/content_settings.h"
#include "content/public/renderer/render_thread_observer.h"
#include "mojo/public/cpp/bindings/associated_receiver_set.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/renderer/chromeos_delayed_callback_group.h"
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
namespace blink {
class WebResourceRequestSenderDelegate;
} // namespace blink
namespace visitedlink {
class VisitedLinkReader;
}
// This class filters the incoming control messages (i.e. ones not destined for
// a RenderView) for Chrome specific messages that the content layer doesn't
// happen. If a few messages are related, they should probably have their own
// observer.
class ChromeRenderThreadObserver : public content::RenderThreadObserver,
public chrome::mojom::RendererConfiguration {
public:
#if BUILDFLAG(IS_CHROMEOS_ASH)
// A helper class to handle Mojo calls that need to be dispatched to the IO
// thread instead of the main thread as is the norm.
// This class is thread-safe.
class ChromeOSListener : public chrome::mojom::ChromeOSListener,
public base::RefCountedThreadSafe<ChromeOSListener> {
public:
static scoped_refptr<ChromeOSListener> Create(
mojo::PendingReceiver<chrome::mojom::ChromeOSListener>
chromeos_listener_receiver);
ChromeOSListener(const ChromeOSListener&) = delete;
ChromeOSListener& operator=(const ChromeOSListener&) = delete;
// Is the merge session still running?
bool IsMergeSessionRunning() const;
// Run |callback| on the calling sequence when the merge session has
// finished (or timed out).
void RunWhenMergeSessionFinished(DelayedCallbackGroup::Callback callback);
protected:
// chrome::mojom::ChromeOSListener:
void MergeSessionComplete() override;
private:
friend class base::RefCountedThreadSafe<ChromeOSListener>;
ChromeOSListener();
~ChromeOSListener() override;
void BindOnIOThread(mojo::PendingReceiver<chrome::mojom::ChromeOSListener>
chromeos_listener_receiver);
scoped_refptr<DelayedCallbackGroup> session_merged_callbacks_;
bool merge_session_running_ GUARDED_BY(lock_);
mutable base::Lock lock_;
mojo::Receiver<chrome::mojom::ChromeOSListener> receiver_{this};
};
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
ChromeRenderThreadObserver();
ChromeRenderThreadObserver(const ChromeRenderThreadObserver&) = delete;
ChromeRenderThreadObserver& operator=(const ChromeRenderThreadObserver&) =
delete;
~ChromeRenderThreadObserver() override;
static bool is_incognito_process() { return is_incognito_process_; }
// Return the dynamic parameters - those that may change while the
// render process is running.
static const chrome::mojom::DynamicParams& GetDynamicParams();
// Returns a pointer to the content setting rules owned by
// |ChromeRenderThreadObserver|.
const RendererContentSettingRules* content_setting_rules() const;
visitedlink::VisitedLinkReader* visited_link_reader() {
return visited_link_reader_.get();
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
scoped_refptr<ChromeOSListener> chromeos_listener() const {
return chromeos_listener_;
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
content_settings::mojom::ContentSettingsManager* content_settings_manager() {
if (content_settings_manager_)
return content_settings_manager_.get();
return nullptr;
}
private:
// content::RenderThreadObserver:
void RegisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) override;
void UnregisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) override;
// chrome::mojom::RendererConfiguration:
void SetInitialConfiguration(
bool is_incognito_process,
mojo::PendingReceiver<chrome::mojom::ChromeOSListener>
chromeos_listener_receiver,
mojo::PendingRemote<content_settings::mojom::ContentSettingsManager>
content_settings_manager) override;
void SetConfiguration(chrome::mojom::DynamicParamsPtr params) override;
void SetContentSettingRules(
const RendererContentSettingRules& rules) override;
void OnRendererConfigurationAssociatedRequest(
mojo::PendingAssociatedReceiver<chrome::mojom::RendererConfiguration>
receiver);
static bool is_incognito_process_;
std::unique_ptr<blink::WebResourceRequestSenderDelegate>
resource_request_sender_delegate_;
RendererContentSettingRules content_setting_rules_;
mojo::Remote<content_settings::mojom::ContentSettingsManager>
content_settings_manager_;
std::unique_ptr<visitedlink::VisitedLinkReader> visited_link_reader_;
mojo::AssociatedReceiverSet<chrome::mojom::RendererConfiguration>
renderer_configuration_receivers_;
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Only set if the Chrome OS merge session was running when the renderer
// was started.
scoped_refptr<ChromeOSListener> chromeos_listener_;
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
};
#endif // CHROME_RENDERER_CHROME_RENDER_THREAD_OBSERVER_H_
|
/****************************************************************************/
/* */
/* Module: LegTrnaslationFuncs.h */
/* */
/* Description: This module provides compatibility support to allow */
/* QST 2.x applications run on QST 1.x firmware. */
/* */
/****************************************************************************/
/****************************************************************************/
/* */
/* Copyright (c) 2005-2009, Intel Corporation. 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 Intel Corporation nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* */
/* DISCLAIMER: 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 */
/* INTEL CORPORATION OR THE 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 _LEG_TRANSLATION_FUNCS_H
#define _LEG_TRANSLATION_FUNCS_H
// Error platform independent error codes for using this module
typedef enum
{
TRANSLATE_CMD_SUCCESS = 0,
TRANSLATE_CMD_INVALID_PARAMETER,
TRANSLATE_CMD_BAD_COMMAND,
TRANSLATE_CMD_NOT_ENOUGH_MEMORY,
TRANSLATE_CMD_FAILED_WITH_ERROR_SET
} CMD_TRANSLATION_STATUS;
// Function prototypes
BOOL GetSubsystemInformation( void );
BOOL TranslationToLegacyRequired( void );
BOOL TranslationToNewRequired( void );
CMD_TRANSLATION_STATUS TranslateToLegacyCommand(
IN void *pvCmdBuf, // Address of buffer contaiing command packet
IN size_t tCmdSize, // Size of command packet
OUT void *pvRspBuf, // Address of buffer for response packet
IN size_t tRspSize // Expected size of response packet
);
CMD_TRANSLATION_STATUS TranslateToNewCommand(
IN void *pvCmdBuf, // Address of buffer contaiing command packet
IN size_t tCmdSize, // Size of command packet
OUT void *pvRspBuf, // Address of buffer for response packet
IN size_t tRspSize // Expected size of response packet
);
BOOL CommonCmdHandler(
IN void *pvCmdBuf, // Address of buffer contaiing command packet
IN size_t tCmdSize, // Size of command packet
OUT void *pvRspBuf, // Address of buffer for response packet
IN size_t tRspSize // Expected size of response packet
);
#endif // ndef _LEG_TRANSLATION_FUNCS_H
|
#ifndef APPS_SFDL_HW_V_INP_GEN_HW_H_
#define APPS_SFDL_HW_V_INP_GEN_HW_H_
#include <libv/libv.h>
#include <common/utility.h>
#include <apps_sfdl_gen/fannkuch_v_inp_gen.h>
/*
* Provides the ability for user-defined input creation
*/
class fannkuchVerifierInpGenHw : public InputCreator {
public:
fannkuchVerifierInpGenHw(Venezia* v);
void create_input(mpq_t* input_q, int num_inputs);
private:
Venezia* v;
fannkuchVerifierInpGen compiler_implementation;
};
#endif // APPS_SFDL_HW_V_INP_GEN_HW_H_
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_COMMON_MATERIAL_DESIGN_MATERIAL_DESIGN_CONTROLLER_H_
#define ASH_COMMON_MATERIAL_DESIGN_MATERIAL_DESIGN_CONTROLLER_H_
#include "ash/ash_export.h"
#include "base/macros.h"
namespace ash {
namespace test {
class MaterialDesignControllerTestAPI;
} // namespace test
// Central controller to handle material design modes.
class ASH_EXPORT MaterialDesignController {
public:
// The different material design modes for Chrome OS system UI.
enum Mode {
// Not initialized.
UNINITIALIZED = -1,
// Classic, non-material design.
NON_MATERIAL = 0,
// Basic material design.
MATERIAL_NORMAL = 1,
// Material design with experimental features.
MATERIAL_EXPERIMENTAL = 2
};
// Initializes |mode_|. Must be called before calling IsMaterial(),
// IsMaterialExperimental(), IsMaterialNormal(), or GetMode().
static void Initialize();
// Returns the currently initialized MaterialDesignController::Mode type for
// Chrome OS system UI.
static Mode GetMode();
// Returns true if overview mode is using Material Design.
static bool IsOverviewMaterial();
// Returns true if Material Design features are enabled for Chrome OS shelf.
static bool IsShelfMaterial();
// Returns true if Material Design features are enabled for Chrome OS system
// tray menu.
static bool IsSystemTrayMenuMaterial();
// Returns true if material design versions of icons should be used in the
// status tray and system menu.
static bool UseMaterialDesignSystemIcons();
private:
friend class test::MaterialDesignControllerTestAPI;
// Declarations only. Do not allow construction of an object.
MaterialDesignController();
~MaterialDesignController();
// Material Design |Mode| for Chrome OS system UI. Used only by tests.
static Mode mode();
// Returns true if Material Design is enabled in Chrome OS system UI.
// Maps to "ash-md" flag "enabled" or "experimental" values.
static bool IsMaterial();
// Returns true if Material Design normal features are enabled in Chrome OS
// system UI. Maps to "--ash-md=enabled" command line switch value.
static bool IsMaterialNormal();
// Returns true if Material Design experimental features are enabled in
// Chrome OS system UI. Maps to "--ash-md=experimental" command line switch
// value.
static bool IsMaterialExperimental();
// Returns the per-platform default material design variant.
static Mode DefaultMode();
// Sets |mode_| to |mode|. Can be used by tests to directly set the mode.
static void SetMode(Mode mode);
// Resets the initialization state to uninitialized. To be used by tests to
// allow calling Initialize() more than once.
static void Uninitialize();
DISALLOW_COPY_AND_ASSIGN(MaterialDesignController);
};
} // namespace ash
#endif // ASH_COMMON_MATERIAL_DESIGN_MATERIAL_DESIGN_CONTROLLER_H_
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_LOGIN_USERS_AVATAR_USER_IMAGE_LOADER_H_
#define CHROME_BROWSER_CHROMEOS_LOGIN_USERS_AVATAR_USER_IMAGE_LOADER_H_
#include <string>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/image_decoder.h"
class SkBitmap;
namespace base {
class SequencedTaskRunner;
}
namespace user_manager {
class UserImage;
}
namespace chromeos {
// Helper that reads, decodes and optionally resizes an image on a background
// thread. Returns the image in the form of an SkBitmap.
class UserImageLoader : public base::RefCountedThreadSafe<UserImageLoader> {
public:
// Callback used to return the result of an image load operation.
typedef base::Callback<void(const user_manager::UserImage& user_image)>
LoadedCallback;
// All file I/O, decoding and resizing are done via |background_task_runner|.
UserImageLoader(
ImageDecoder::ImageCodec image_codec,
scoped_refptr<base::SequencedTaskRunner> background_task_runner);
// Load an image in the background and call |loaded_cb| with the resulting
// UserImage (which may be empty in case of error). If |pixels_per_side| is
// positive, the image is cropped to a square and shrunk so that it does not
// exceed |pixels_per_side|x|pixels_per_side|. The first variant of this
// method reads the image from |filepath| on disk, the second processes |data|
// read into memory already.
void Start(const std::string& filepath,
int pixels_per_side,
const LoadedCallback& loaded_cb);
void Start(scoped_ptr<std::string> data,
int pixels_per_side,
const LoadedCallback& loaded_cb);
private:
friend class base::RefCountedThreadSafe<UserImageLoader>;
// Contains attributes we need to know about each image we decode.
struct ImageInfo {
ImageInfo(const std::string& file_path,
int pixels_per_side,
const LoadedCallback& loaded_cb);
~ImageInfo();
const std::string file_path;
const int pixels_per_side;
const LoadedCallback loaded_cb;
};
class UserImageRequest : public ImageDecoder::ImageRequest {
public:
UserImageRequest(const ImageInfo& image_info,
const std::string& image_data,
UserImageLoader* user_image_loader);
// ImageDecoder::ImageRequest implementation. These callbacks will only be
// invoked via user_image_loader_'s background_task_runner_.
void OnImageDecoded(const SkBitmap& decoded_image) override;
void OnDecodeImageFailed() override;
private:
~UserImageRequest() override;
const ImageInfo image_info_;
std::vector<unsigned char> image_data_;
UserImageLoader* user_image_loader_;
};
~UserImageLoader();
// Reads the image from |image_info.file_path| and starts the decoding
// process. This method may only be invoked via the |background_task_runner_|.
void ReadAndDecodeImage(const ImageInfo& image_info);
// Decodes the image |data|. This method may only be invoked via the
// |background_task_runner_|.
void DecodeImage(const scoped_ptr<std::string> data,
const ImageInfo& image_info);
// The foreground task runner on which |this| is instantiated, Start() is
// called and LoadedCallbacks are invoked.
scoped_refptr<base::SequencedTaskRunner> foreground_task_runner_;
// The background task runner on which file I/O, image decoding and resizing
// are done.
scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
// Specify how the file should be decoded in the utility process.
const ImageDecoder::ImageCodec image_codec_;
DISALLOW_COPY_AND_ASSIGN(UserImageLoader);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_LOGIN_USERS_AVATAR_USER_IMAGE_LOADER_H_
|
//===-- MainLoopBase.h ------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_HOST_MAINLOOPBASE_H
#define LLDB_HOST_MAINLOOPBASE_H
#include "lldb/Utility/IOObject.h"
#include "lldb/Utility/Status.h"
#include "llvm/Support/ErrorHandling.h"
#include <functional>
namespace lldb_private {
// The purpose of this class is to enable multiplexed processing of data from
// different sources without resorting to multi-threading. Clients can register
// IOObjects, which will be monitored for readability, and when they become
// ready, the specified callback will be invoked. Monitoring for writability is
// not supported, but can be easily added if needed.
//
// The RegisterReadObject function return a handle, which controls the duration
// of the monitoring. When this handle is destroyed, the callback is
// deregistered.
//
// This class simply defines the interface common for all platforms, actual
// implementations are platform-specific.
class MainLoopBase {
private:
class ReadHandle;
public:
MainLoopBase() {}
virtual ~MainLoopBase() {}
typedef std::unique_ptr<ReadHandle> ReadHandleUP;
typedef std::function<void(MainLoopBase &)> Callback;
virtual ReadHandleUP RegisterReadObject(const lldb::IOObjectSP &object_sp,
const Callback &callback,
Status &error) {
llvm_unreachable("Not implemented");
}
// Waits for registered events and invoke the proper callbacks. Returns when
// all callbacks deregister themselves or when someone requests termination.
virtual Status Run() { llvm_unreachable("Not implemented"); }
// Requests the exit of the Run() function.
virtual void RequestTermination() { llvm_unreachable("Not implemented"); }
protected:
ReadHandleUP CreateReadHandle(const lldb::IOObjectSP &object_sp) {
return ReadHandleUP(new ReadHandle(*this, object_sp->GetWaitableHandle()));
}
virtual void UnregisterReadObject(IOObject::WaitableHandle handle) {
llvm_unreachable("Not implemented");
}
private:
class ReadHandle {
public:
~ReadHandle() { m_mainloop.UnregisterReadObject(m_handle); }
private:
ReadHandle(MainLoopBase &mainloop, IOObject::WaitableHandle handle)
: m_mainloop(mainloop), m_handle(handle) {}
MainLoopBase &m_mainloop;
IOObject::WaitableHandle m_handle;
friend class MainLoopBase;
DISALLOW_COPY_AND_ASSIGN(ReadHandle);
};
private:
DISALLOW_COPY_AND_ASSIGN(MainLoopBase);
};
} // namespace lldb_private
#endif // LLDB_HOST_MAINLOOPBASE_H
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef FLUXMETA_METAPROTOCOL_H
#define FLUXMETA_METAPROTOCOL_H
#include <flux/meta/MetaObject>
namespace flux {
namespace meta {
/** \brief Duck-typed object protocol
*/
class MetaProtocol: public Object
{
public:
inline static Ref<MetaProtocol> create() {
return new MetaProtocol;
}
template<class Prototype>
Prototype *define(const String &className) {
Ref<Prototype> prototype = Prototype::create(className);
define(prototype);
return prototype;
}
template<class Prototype>
Prototype *define() {
Ref<Prototype> prototype = Prototype::create();
define(prototype);
return prototype;
}
MetaObject *define(MetaObject *prototype) {
prototype->define();
prototypes()->insert(prototype->className(), prototype);
return prototype;
}
template<class Prototype>
static Ref<MetaObject> createPrototype() {
Ref<MetaObject> prototype = Prototype::create();
prototype->define();
return prototype;
}
virtual MetaObject *lookup(String className) const {
MetaObject *prototype = 0;
if (prototypes_) prototypes_->lookup(className, &prototype);
return prototype;
}
int minCount() const { return minCount_; }
int maxCount() const { return maxCount_; }
void minCount(int newCount) { minCount_ = newCount; }
void maxCount(int newCount) { maxCount_ = newCount; }
inline bool lookup(const String &className, MetaObject **prototype) const {
*prototype = lookup(className);
return *prototype;
}
protected:
friend class YasonSyntax;
MetaProtocol():
minCount_(0),
maxCount_(flux::intMax)
{}
virtual Ref<MetaObject> produce(MetaObject *prototype) const {
return prototype->produce();
}
private:
typedef Map<String, Ref<MetaObject> > Prototypes;
Prototypes *prototypes() {
if (!prototypes_) prototypes_ = Prototypes::create();
return prototypes_;
}
Ref<Prototypes> prototypes_;
int minCount_;
int maxCount_;
};
}} // namespace flux::meta
#endif // FLUXMETA_METAPROTOCOL_H
|
/*
----------------------
BeDC License
----------------------
Copyright 2002, The BeDC team.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the BeDC team nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 _DC_STRINGS_H_
#define _DC_STRINGS_H_
#include <String.h>
// String constants
enum
{
// Hub window
STR_HUB_WINDOW_TITLE = 0,
// Hub window -> Buttons
STR_HUB_CONNECT,
STR_HUB_REFRESH,
STR_HUB_NEXT50,
STR_HUB_PREV50,
// Hub window -> List view
STR_SERVER_NAME,
STR_SERVER_ADDR,
STR_SERVER_DESC,
STR_SERVER_USERS,
// Hub window -> Status
STR_STATUS_IDLE,
STR_STATUS_CONNECTING,
STR_STATUS_CONNECTED,
STR_STATUS_CONNECT_ERROR,
STR_STATUS_SEND_ERROR,
STR_STATUS_RECV_ERROR,
STR_STATUS_NUM_SERVERS,
// Main window -> Menus
STR_MENU_FILE,
STR_MENU_FILE_ABOUT,
STR_MENU_FILE_CLOSE,
STR_MENU_EDIT,
STR_MENU_EDIT_PREFS,
STR_MENU_WINDOWS,
STR_MENU_WINDOWS_HUB,
// Prefernces window
STR_PREFS_TITLE,
STR_PREFS_GENERAL,
STR_PREFS_GENERAL_PERSONAL,
STR_PREFS_GENERAL_CONNECTION_SETTINGS,
STR_PREFS_GENERAL_NICK,
STR_PREFS_GENERAL_EMAIL,
STR_PREFS_GENERAL_DESC,
STR_PREFS_GENERAL_CONNECTION,
STR_PREFS_GENERAL_ACTIVE,
STR_PREFS_GENERAL_PASSIVE,
STR_PREFS_GENERAL_IP,
STR_PREFS_GENERAL_PORT,
STR_PREFS_COLORS,
STR_PREFS_COLORS_SYSTEM,
STR_PREFS_COLORS_TEXT,
STR_PREFS_COLORS_ERROR,
STR_PREFS_COLORS_REMOTE_NICK,
STR_PREFS_COLORS_LOCAL_NICK,
STR_PREFS_COLORS_PRIVATE_TEXT,
// For the user list view
STR_VIEW_NAME = STR_SERVER_NAME, // Reuse ;)
STR_VIEW_SPEED = STR_PREFS_COLORS_PRIVATE_TEXT + 1,
STR_VIEW_DESC,
STR_VIEW_EMAIL,
STR_VIEW_SHARED,
STR_VIEW_CHAT,
STR_VIEW_CLOSE,
STR_OK,
STR_CANCEL,
STR_ERROR,
STR_USERS,
STR_LANGUAGE,
STR_REVERT,
STR_ALERT_BAD_NICK,
// Messages
STR_MSG_SYSTEM,
STR_MSG_ERROR,
STR_MSG_CONNECTING_TO,
STR_MSG_CONNECTED,
STR_MSG_CONNECT_ERROR,
STR_MSG_RECONNECTING,
STR_MSG_DISCONNECTED_FROM_SERVER,
STR_MSG_INVALID_NICK,
STR_MSG_USER_LOGGED_IN,
STR_MSG_USER_LOGGED_OUT,
STR_MSG_REDIRECTING,
STR_MSG_HUB_IS_FULL,
STR_MSG_USER_NOT_FOUND,
STR_MSG_UNKNOWN_COMMAND,
// This is a LONG string that contains the WHOLE /help text
STR_MSG_HELP,
STR_NUM // Place holder
};
// Key shortcuts for menu items
enum
{
KEY_FILE_ABOUT = 0,
KEY_FILE_CLOSE,
KEY_EDIT_PREFS,
KEY_WINDOWS_HUB,
KEY_NUM
};
enum
{
DC_LANG_ENGLISH = 0,
DC_LANG_SWEDISH,
DC_LANG_FINNISH,
DC_LANG_GERMAN,
DC_LANG_NORWEGIAN,
DC_LANG_POLISH,
DC_LANG_RUSSIAN,
DC_LANG_NUM // Place holder
};
extern const char * DC_LANGUAGES[DC_LANG_NUM];
const char * DCStr(int);
char DCKey(int);
void DCSetLanguage(int);
int DCGetLanguage();
BString DCUTF8(const char * str);
BString DCMS(const char * str);
#endif // _DC_STRINGS_H_
|
/*
* Copyright (c) 2012 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "native_client/src/include/portability_string.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/nacl_platform.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/trusted/service_runtime/nacl_syscall_asm_symbols.h"
#include "native_client/src/trusted/service_runtime/nacl_globals.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/service_runtime/sel_memory.h"
#include "native_client/src/trusted/service_runtime/springboard.h"
#include "native_client/src/trusted/service_runtime/arch/x86/sel_ldr_x86.h"
#include "native_client/src/trusted/service_runtime/arch/x86_64/tramp_64.h"
static uintptr_t AddDispatchThunk(uintptr_t *next_addr,
uintptr_t target_routine) {
struct NaClPatchInfo patch_info;
struct NaClPatch jmp_target;
jmp_target.target = (((uintptr_t) &NaClDispatchThunk_jmp_target)
- sizeof(uintptr_t));
jmp_target.value = target_routine;
NaClPatchInfoCtor(&patch_info);
patch_info.abs64 = &jmp_target;
patch_info.num_abs64 = 1;
patch_info.dst = *next_addr;
patch_info.src = (uintptr_t) &NaClDispatchThunk;
patch_info.nbytes = ((uintptr_t) &NaClDispatchThunkEnd
- (uintptr_t) &NaClDispatchThunk);
NaClApplyPatchToMemory(&patch_info);
*next_addr += patch_info.nbytes;
return patch_info.dst;
}
int NaClMakeDispatchThunk(struct NaClApp *nap) {
int retval = 0; /* fail */
int error;
void *thunk_addr = NULL;
uintptr_t next_addr;
uintptr_t dispatch_thunk = 0;
uintptr_t get_tls_fast_path1 = 0;
uintptr_t get_tls_fast_path2 = 0;
NaClLog(2, "Entered NaClMakeDispatchThunk\n");
if (0 != nap->dispatch_thunk) {
NaClLog(LOG_ERROR, " dispatch_thunk already initialized!\n");
return 1;
}
if (0 != (error = NaCl_page_alloc_randomized(&thunk_addr,
NACL_MAP_PAGESIZE))) {
NaClLog(LOG_INFO,
"NaClMakeDispatchThunk::NaCl_page_alloc failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
NaClLog(2, "NaClMakeDispatchThunk: got addr 0x%"NACL_PRIxPTR"\n",
(uintptr_t) thunk_addr);
if (0 != (error = NaCl_mprotect(thunk_addr,
NACL_MAP_PAGESIZE,
PROT_READ | PROT_WRITE))) {
NaClLog(LOG_INFO,
"NaClMakeDispatchThunk::NaCl_mprotect r/w failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
NaClFillMemoryRegionWithHalt(thunk_addr, NACL_MAP_PAGESIZE);
next_addr = (uintptr_t) thunk_addr;
dispatch_thunk =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClSyscallSeg);
get_tls_fast_path1 =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClGetTlsFastPath1);
get_tls_fast_path2 =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClGetTlsFastPath2);
if (0 != (error = NaCl_mprotect(thunk_addr,
NACL_MAP_PAGESIZE,
PROT_EXEC|PROT_READ))) {
NaClLog(LOG_INFO,
"NaClMakeDispatchThunk::NaCl_mprotect r/x failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
retval = 1;
cleanup:
if (0 == retval) {
if (NULL != thunk_addr) {
NaCl_page_free(thunk_addr, NACL_MAP_PAGESIZE);
thunk_addr = NULL;
}
} else {
nap->dispatch_thunk = dispatch_thunk;
nap->get_tls_fast_path1 = get_tls_fast_path1;
nap->get_tls_fast_path2 = get_tls_fast_path2;
}
return retval;
}
/*
* Install a syscall trampoline at target_addr. NB: Thread-safe.
*/
void NaClPatchOneTrampolineCall(uintptr_t call_target_addr,
uintptr_t target_addr) {
struct NaClPatchInfo patch_info;
struct NaClPatch call_target;
NaClLog(6, "call_target_addr = 0x%"NACL_PRIxPTR"\n", call_target_addr);
CHECK(0 != call_target_addr);
call_target.target = (((uintptr_t) &NaCl_trampoline_call_target)
- sizeof(uintptr_t));
call_target.value = call_target_addr;
NaClPatchInfoCtor(&patch_info);
patch_info.abs64 = &call_target;
patch_info.num_abs64 = 1;
patch_info.dst = target_addr;
patch_info.src = (uintptr_t) &NaCl_trampoline_code;
patch_info.nbytes = ((uintptr_t) &NaCl_trampoline_code_end
- (uintptr_t) &NaCl_trampoline_code);
NaClApplyPatchToMemory(&patch_info);
}
void NaClPatchOneTrampoline(struct NaClApp *nap,
uintptr_t target_addr) {
uintptr_t call_target_addr;
call_target_addr = nap->dispatch_thunk;
NaClPatchOneTrampolineCall(call_target_addr, target_addr);
}
void NaClFillMemoryRegionWithHalt(void *start, size_t size) {
CHECK(!(size % NACL_HALT_LEN));
/* Tell valgrind that this memory is accessible and undefined */
NACL_MAKE_MEM_UNDEFINED(start, size);
memset(start, NACL_HALT_OPCODE, size);
}
void NaClFillTrampolineRegion(struct NaClApp *nap) {
NaClFillMemoryRegionWithHalt(
(void *) (nap->mem_start + NACL_TRAMPOLINE_START),
NACL_TRAMPOLINE_SIZE);
}
void NaClLoadSpringboard(struct NaClApp *nap) {
/*
* There is no springboard for x86-64.
*/
UNREFERENCED_PARAMETER(nap);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.