hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
599d251811c9c5309ea327b992d94f04bc42ce41 | 444 | h | C | WeSdk/1.3.5/WeMobSdk.framework/Headers/WeMobNetworkConfigs.h | webeyemob/WeSdkiOSPub | f4d95ca87ac7d4a5629893f1ecf9f8fe0847ad92 | [
"MIT"
] | null | null | null | WeSdk/1.3.5/WeMobSdk.framework/Headers/WeMobNetworkConfigs.h | webeyemob/WeSdkiOSPub | f4d95ca87ac7d4a5629893f1ecf9f8fe0847ad92 | [
"MIT"
] | null | null | null | WeSdk/1.3.5/WeMobSdk.framework/Headers/WeMobNetworkConfigs.h | webeyemob/WeSdkiOSPub | f4d95ca87ac7d4a5629893f1ecf9f8fe0847ad92 | [
"MIT"
] | null | null | null | //
// WeMobNetworkConfigs.h
// WeMobSdk
//
// Created by Matthew on 2019/10/8.
// Copyright © 2019年 WeMob. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "WeMobNetworkConfig.h"
@interface WeMobNetworkConfigs : NSObject
-(void)addConfig:(WeMobNetworkConfig *)config;
-(NSObject *)getNetworkConfig:(Class)clazz;
-(NSObject *)getNetworkConfigOrGlobal:(Class)clazz;
+(NSObject *)getGlobalNetworkConfig:(Class)clazz;
@end
| 22.2 | 51 | 0.75 |
25c951c22a50a01139c13093ac97dce2cd3d18ad | 4,560 | h | C | arcane/extras/NumericalModel/src/Utils/IOBuffer.h | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 16 | 2021-09-20T12:37:01.000Z | 2022-03-18T09:19:14.000Z | arcane/extras/NumericalModel/src/Utils/IOBuffer.h | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 66 | 2021-09-17T13:49:39.000Z | 2022-03-30T16:24:07.000Z | arcane/extras/NumericalModel/src/Utils/IOBuffer.h | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 11 | 2021-09-27T16:48:55.000Z | 2022-03-23T19:06:56.000Z | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
#ifndef IOBUFFER_H_
#define IOBUFFER_H_
#include "Utils/Utils.h"
#include <arcane/utils/Iostream.h>
#include <arcane/utils/Buffer.h>
#include <arcane/utils/StdHeader.h>
#include <arcane/utils/HashTableMap.h>
#include <arcane/utils/ValueConvert.h>
#include <arcane/utils/String.h>
#include <arcane/utils/IOException.h>
#include <arcane/utils/Collection.h>
#include <arcane/utils/Enumerator.h>
#include <sstream>
using namespace Arcane;
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
class IOFile
{
public:
static const int BUFSIZE = 10000;
public:
IOFile(istream* stream) : m_stream(stream) {}
virtual ~IOFile() { }
const char* getNextLine();
Real getReal();
Integer getInteger();
template<class T> void getValue(T& v) ;
bool isEnd(){ (*m_stream) >> ws; return m_stream->eof(); }
private:
istream* m_stream;
char m_buf[BUFSIZE];
};
template<>
void IOFile::getValue(Real& x) ;
template<>
void IOFile::getValue(Integer& i) ;
template<>
void IOFile::getValue(String& str) ;
template<class T>
void IOFile::getValue(T& v)
{
(*m_stream) >> ws >> v;
if (m_stream->good())
return ;
throw IOException("IOFile::getValue()","Bad Type");
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
class _Split
{
private:
template<class T> friend bool readBufferFromStringBuffer(const String& strbuffer,
Array<T> &buffer,
const String sep,
Integer size);
template<class T> friend bool readBufferFromStringBuffer(const String& strbuffer,
Array<T> &buffer,
const String sep);
template<class T>
static void split(const String& str,Array<T>& buffer,const String& sep,Integer size) ;
};
template<>
void _Split::split(const String& str,Array<Integer>& buffer,const String& sep,Integer size) ;
template<>
void _Split::split(const String& str,Array<Real>& buffer,const String& sep,Integer size) ;
template<>
void _Split::split(const String& str,Array<String>& buffer,const String& sep,Integer size) ;
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
template<class T>
bool readBufferFromFile(const String& file_name,
Array<T> &buffer,
Integer size)
{
if(buffer.size()<size)
{
cout<<"Buffer size is too small"<<endl ;
return false ;
}
ifstream ifile(file_name.localstr());
if (!ifile){
cout << "Unable to open in read mode file '"
<< file_name.localstr() << "'"<<endl;
return false;
}
IOFile file(&ifile);
Integer count = 0 ;
try
{
while(!file.isEnd())
{
T x ;
file.getValue(x) ;
buffer[count] = x ;
count++ ;
if(count==size) break ;
}
if(count<size) cout <<"Warning there are less element than : "<<size<<endl ;
return true ;
}
catch(IOException e)
{
cerr<<"Reading file problem :"<<e<<endl ;
return false ;
}
}
/*---------------------------------------------------------------------------*/
template<class T>
bool readBufferFromStringBuffer(const String& strbuffer,
Array<T> &buffer,
const String sep,
Integer size)
{
if(buffer.size()<size)
{
cout<<"Buffer size is too small"<<endl ;
return false ;
}
_Split::split(strbuffer,buffer,sep,size) ;
return true ;
}
/*---------------------------------------------------------------------------*/
template<class T>
bool readBufferFromStringBuffer(const String& strbuffer,
Array<T> &buffer,
const String sep)
{
_Split::split(strbuffer,buffer,sep,0) ;
return true ;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#endif /*IOBUFFER_H_*/
| 28.322981 | 93 | 0.474342 |
971cfc98f427f3a89f1d8d6b5116e1dd0330bb54 | 5,950 | h | C | kratos/utilities/dof_updater.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | kratos/utilities/dof_updater.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | kratos/utilities/dof_updater.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Jordi Cotela
//
#if !defined(KRATOS_DOF_UPDATER_H_INCLUDED )
#define KRATOS_DOF_UPDATER_H_INCLUDED
// Project includes
#include "includes/define.h"
#include "includes/model_part.h"
#include "utilities/parallel_utilities.h"
namespace Kratos
{
///@addtogroup KratosCore
///@{
///@name Kratos Classes
///@{
/// Utility class to update the values of degree of freedom (Dof) variables after solving the system.
/** This class encapsulates the operation of updating nodal degrees of freedom after a system solution.
* In pseudo-code, the operation to be performed is
* for each dof: dof.variable += dx[dof.equation_id]
* This operation is a simple loop in shared memory, but requires additional infrastructure in MPI,
* to obtain out-of-process update data. DofUpdater takes care of both the operation and the eventual
* auxiliary infrastructure.
* @see TrilinosDofUpdater for the trilinos version.
*/
template< class TSparseSpace >
class DofUpdater
{
public:
///@name Type Definitions
///@{
/// Pointer definition of DofUpdater
KRATOS_CLASS_POINTER_DEFINITION(DofUpdater);
using DofType = Dof<typename TSparseSpace::DataType>;
using DofsArrayType = PointerVectorSet<
DofType,
SetIdentityFunction<DofType>,
std::less<typename SetIdentityFunction<DofType>::result_type>,
std::equal_to<typename SetIdentityFunction<DofType>::result_type>,
DofType* >;
using SystemVectorType = typename TSparseSpace::VectorType;
///@}
///@name Life Cycle
///@{
/// Default constructor.
DofUpdater(){}
/// Deleted copy constructor
DofUpdater(DofUpdater const& rOther) = delete;
/// Destructor.
virtual ~DofUpdater(){}
/// Deleted assignment operator
DofUpdater& operator=(DofUpdater const& rOther) = delete;
///@}
///@name Operations
///@{
/// Create a new instance of this class.
/** This function is used by the SparseSpace class to create new
* DofUpdater instances of the appropriate type.
* @return a std::unique_pointer to the new instance.
* @see UblasSpace::CreateDofUpdater(), TrilinosSpace::CreateDofUpdater().
*/
virtual typename DofUpdater::UniquePointer Create() const
{
return Kratos::make_unique<DofUpdater>();
}
/// Initialize the DofUpdater in preparation for a subsequent UpdateDofs call.
/** Note that the base DofUpdater does not have internal data, so this does nothing.
* @param[in] rDofSet The list of degrees of freedom.
* @param[in] rDx The update vector.
*/
virtual void Initialize(
const DofsArrayType& rDofSet,
const SystemVectorType& rDx)
{}
/// Free internal storage to reset the instance and/or optimize memory consumption.
/** Note that the base DofUpdater does not have internal data, so this does nothing.
*/
virtual void Clear() {}
/// Calculate new values for the problem's degrees of freedom using the update vector rDx.
/** For each Dof in rDofSet, this function calculates the updated value for the corresponding
* variable as value += rDx[dof.EquationId()].
* @param[in/out] rDofSet The list of degrees of freedom.
* @param[in] rDx The update vector.
* This method will check if Initialize() was called before and call it if necessary.
*/
virtual void UpdateDofs(
DofsArrayType& rDofSet,
const SystemVectorType& rDx)
{
block_for_each(
rDofSet,
[&rDx](DofType& rDof)
{
if (rDof.IsFree()) {
rDof.GetSolutionStepValue() += TSparseSpace::GetValue(rDx, rDof.EquationId());
}
}
);
}
/// Assign new values for the problem's degrees of freedom using the vector rX.
/** For each Dof in rDofSet, this function assigns the value for the corresponding
* variable as value = rX[dof.EquationId()].
* @param[in/out] rDofSet The list of degrees of freedom.
* @param[in] rX The solution vector.
* This method will check if Initialize() was called before and call it if necessary.
*/
virtual void AssignDofs(DofsArrayType& rDofSet, const SystemVectorType& rX)
{
block_for_each(
rDofSet,
[&rX](DofType& rDof)
{
if (rDof.IsFree()) {
rDof.GetSolutionStepValue() = TSparseSpace::GetValue(rX, rDof.EquationId());
}
}
);
}
///@}
///@name Input and output
///@{
/// Turn back information as a string.
virtual std::string Info() const
{
std::stringstream buffer;
buffer << "DofUpdater" ;
return buffer.str();
}
/// Print information about this object.
virtual void PrintInfo(std::ostream& rOStream) const
{
rOStream << this->Info() << std::endl;
}
/// Print object's data.
virtual void PrintData(std::ostream& rOStream) const
{
rOStream << this->Info() << std::endl;
}
///@}
}; // Class DofUpdater
///@}
///@name Input and output
///@{
/// input stream function
template< class TSparseSpace >
inline std::istream& operator >> (
std::istream& rIStream,
DofUpdater<TSparseSpace>& rThis)
{
return rIStream;
}
/// output stream function
template< class TSparseSpace >
inline std::ostream& operator << (
std::ostream& rOStream,
const DofUpdater<TSparseSpace>& rThis)
{
rThis.PrintInfo(rOStream);
rOStream << std::endl;
rThis.PrintData(rOStream);
return rOStream;
}
///@}
///@} addtogroup block
} // namespace Kratos.
#endif // KRATOS_DOF_UPDATER_H_INCLUDED defined
| 28.605769 | 103 | 0.638487 |
1c7fcb18312fbdbac557a18570616ef8d0f34352 | 389 | h | C | thn/store/JYSexPicker.h | purpen/frbird-app | 852416a8a6e332ab28df1821a194c9de7c1852b4 | [
"MIT"
] | null | null | null | thn/store/JYSexPicker.h | purpen/frbird-app | 852416a8a6e332ab28df1821a194c9de7c1852b4 | [
"MIT"
] | null | null | null | thn/store/JYSexPicker.h | purpen/frbird-app | 852416a8a6e332ab28df1821a194c9de7c1852b4 | [
"MIT"
] | null | null | null | //
// JYSexPicker.h
// HaojyClient
//
// Created by Robinkey on 14-5-9.
// Copyright (c) 2014年 JYHD. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum {
kJYSexNone = 0,
kJYSexMan = 1,
kJYSexWoman = 2
}JYSexType;
@interface JYSexPicker : UIView
@property (nonatomic, assign) JYSexType sex;
@property (nonatomic, copy) CallbackBlockWithPara selectedBlock;
@end
| 18.52381 | 64 | 0.696658 |
85033f392c78a7959aa397903955c36e2e3189a0 | 16,593 | c | C | arch/powerpc/platforms/pseries/mobility.c | Sunrisepeak/Linux2.6-Reading | c25102a494a37f9f30a27ca2cd4a1a412bffc80f | [
"MIT"
] | 1 | 2022-03-31T03:23:42.000Z | 2022-03-31T03:23:42.000Z | arch/powerpc/platforms/pseries/mobility.c | Sunrisepeak/Linux2.6-Reading | c25102a494a37f9f30a27ca2cd4a1a412bffc80f | [
"MIT"
] | null | null | null | arch/powerpc/platforms/pseries/mobility.c | Sunrisepeak/Linux2.6-Reading | c25102a494a37f9f30a27ca2cd4a1a412bffc80f | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: GPL-2.0-only
/*
* Support for Partition Mobility/Migration
*
* Copyright (C) 2010 Nathan Fontenot
* Copyright (C) 2010 IBM Corporation
*/
#define pr_fmt(fmt) "mobility: " fmt
#include <linux/cpu.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/nmi.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/stat.h>
#include <linux/stop_machine.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/stringify.h>
#include <asm/machdep.h>
#include <asm/rtas.h>
#include "pseries.h"
#include "../../kernel/cacheinfo.h"
static struct kobject *mobility_kobj;
struct update_props_workarea {
__be32 phandle;
__be32 state;
__be64 reserved;
__be32 nprops;
} __packed;
#define NODE_ACTION_MASK 0xff000000
#define NODE_COUNT_MASK 0x00ffffff
#define DELETE_DT_NODE 0x01000000
#define UPDATE_DT_NODE 0x02000000
#define ADD_DT_NODE 0x03000000
#define MIGRATION_SCOPE (1)
#define PRRN_SCOPE -2
static int mobility_rtas_call(int token, char *buf, s32 scope)
{
int rc;
spin_lock(&rtas_data_buf_lock);
memcpy(rtas_data_buf, buf, RTAS_DATA_BUF_SIZE);
rc = rtas_call(token, 2, 1, NULL, rtas_data_buf, scope);
memcpy(buf, rtas_data_buf, RTAS_DATA_BUF_SIZE);
spin_unlock(&rtas_data_buf_lock);
return rc;
}
static int delete_dt_node(struct device_node *dn)
{
struct device_node *pdn;
bool is_platfac;
pdn = of_get_parent(dn);
is_platfac = of_node_is_type(dn, "ibm,platform-facilities") ||
of_node_is_type(pdn, "ibm,platform-facilities");
of_node_put(pdn);
/*
* The drivers that bind to nodes in the platform-facilities
* hierarchy don't support node removal, and the removal directive
* from firmware is always followed by an add of an equivalent
* node. The capability (e.g. RNG, encryption, compression)
* represented by the node is never interrupted by the migration.
* So ignore changes to this part of the tree.
*/
if (is_platfac) {
pr_notice("ignoring remove operation for %pOFfp\n", dn);
return 0;
}
pr_debug("removing node %pOFfp\n", dn);
dlpar_detach_node(dn);
return 0;
}
static int update_dt_property(struct device_node *dn, struct property **prop,
const char *name, u32 vd, char *value)
{
struct property *new_prop = *prop;
int more = 0;
/* A negative 'vd' value indicates that only part of the new property
* value is contained in the buffer and we need to call
* ibm,update-properties again to get the rest of the value.
*
* A negative value is also the two's compliment of the actual value.
*/
if (vd & 0x80000000) {
vd = ~vd + 1;
more = 1;
}
if (new_prop) {
/* partial property fixup */
char *new_data = kzalloc(new_prop->length + vd, GFP_KERNEL);
if (!new_data)
return -ENOMEM;
memcpy(new_data, new_prop->value, new_prop->length);
memcpy(new_data + new_prop->length, value, vd);
kfree(new_prop->value);
new_prop->value = new_data;
new_prop->length += vd;
} else {
new_prop = kzalloc(sizeof(*new_prop), GFP_KERNEL);
if (!new_prop)
return -ENOMEM;
new_prop->name = kstrdup(name, GFP_KERNEL);
if (!new_prop->name) {
kfree(new_prop);
return -ENOMEM;
}
new_prop->length = vd;
new_prop->value = kzalloc(new_prop->length, GFP_KERNEL);
if (!new_prop->value) {
kfree(new_prop->name);
kfree(new_prop);
return -ENOMEM;
}
memcpy(new_prop->value, value, vd);
*prop = new_prop;
}
if (!more) {
pr_debug("updating node %pOF property %s\n", dn, name);
of_update_property(dn, new_prop);
*prop = NULL;
}
return 0;
}
static int update_dt_node(struct device_node *dn, s32 scope)
{
struct update_props_workarea *upwa;
struct property *prop = NULL;
int i, rc, rtas_rc;
char *prop_data;
char *rtas_buf;
int update_properties_token;
u32 nprops;
u32 vd;
update_properties_token = rtas_token("ibm,update-properties");
if (update_properties_token == RTAS_UNKNOWN_SERVICE)
return -EINVAL;
rtas_buf = kzalloc(RTAS_DATA_BUF_SIZE, GFP_KERNEL);
if (!rtas_buf)
return -ENOMEM;
upwa = (struct update_props_workarea *)&rtas_buf[0];
upwa->phandle = cpu_to_be32(dn->phandle);
do {
rtas_rc = mobility_rtas_call(update_properties_token, rtas_buf,
scope);
if (rtas_rc < 0)
break;
prop_data = rtas_buf + sizeof(*upwa);
nprops = be32_to_cpu(upwa->nprops);
/* On the first call to ibm,update-properties for a node the
* the first property value descriptor contains an empty
* property name, the property value length encoded as u32,
* and the property value is the node path being updated.
*/
if (*prop_data == 0) {
prop_data++;
vd = be32_to_cpu(*(__be32 *)prop_data);
prop_data += vd + sizeof(vd);
nprops--;
}
for (i = 0; i < nprops; i++) {
char *prop_name;
prop_name = prop_data;
prop_data += strlen(prop_name) + 1;
vd = be32_to_cpu(*(__be32 *)prop_data);
prop_data += sizeof(vd);
switch (vd) {
case 0x00000000:
/* name only property, nothing to do */
break;
case 0x80000000:
of_remove_property(dn, of_find_property(dn,
prop_name, NULL));
prop = NULL;
break;
default:
rc = update_dt_property(dn, &prop, prop_name,
vd, prop_data);
if (rc) {
pr_err("updating %s property failed: %d\n",
prop_name, rc);
}
prop_data += vd;
break;
}
cond_resched();
}
cond_resched();
} while (rtas_rc == 1);
kfree(rtas_buf);
return 0;
}
static int add_dt_node(struct device_node *parent_dn, __be32 drc_index)
{
struct device_node *dn;
int rc;
dn = dlpar_configure_connector(drc_index, parent_dn);
if (!dn)
return -ENOENT;
/*
* Since delete_dt_node() ignores this node type, this is the
* necessary counterpart. We also know that a platform-facilities
* node returned from dlpar_configure_connector() has children
* attached, and dlpar_attach_node() only adds the parent, leaking
* the children. So ignore these on the add side for now.
*/
if (of_node_is_type(dn, "ibm,platform-facilities")) {
pr_notice("ignoring add operation for %pOF\n", dn);
dlpar_free_cc_nodes(dn);
return 0;
}
rc = dlpar_attach_node(dn, parent_dn);
if (rc)
dlpar_free_cc_nodes(dn);
pr_debug("added node %pOFfp\n", dn);
return rc;
}
int pseries_devicetree_update(s32 scope)
{
char *rtas_buf;
__be32 *data;
int update_nodes_token;
int rc;
update_nodes_token = rtas_token("ibm,update-nodes");
if (update_nodes_token == RTAS_UNKNOWN_SERVICE)
return 0;
rtas_buf = kzalloc(RTAS_DATA_BUF_SIZE, GFP_KERNEL);
if (!rtas_buf)
return -ENOMEM;
do {
rc = mobility_rtas_call(update_nodes_token, rtas_buf, scope);
if (rc && rc != 1)
break;
data = (__be32 *)rtas_buf + 4;
while (be32_to_cpu(*data) & NODE_ACTION_MASK) {
int i;
u32 action = be32_to_cpu(*data) & NODE_ACTION_MASK;
u32 node_count = be32_to_cpu(*data) & NODE_COUNT_MASK;
data++;
for (i = 0; i < node_count; i++) {
struct device_node *np;
__be32 phandle = *data++;
__be32 drc_index;
np = of_find_node_by_phandle(be32_to_cpu(phandle));
if (!np) {
pr_warn("Failed lookup: phandle 0x%x for action 0x%x\n",
be32_to_cpu(phandle), action);
continue;
}
switch (action) {
case DELETE_DT_NODE:
delete_dt_node(np);
break;
case UPDATE_DT_NODE:
update_dt_node(np, scope);
break;
case ADD_DT_NODE:
drc_index = *data++;
add_dt_node(np, drc_index);
break;
}
of_node_put(np);
cond_resched();
}
}
cond_resched();
} while (rc == 1);
kfree(rtas_buf);
return rc;
}
void post_mobility_fixup(void)
{
int rc;
rtas_activate_firmware();
/*
* We don't want CPUs to go online/offline while the device
* tree is being updated.
*/
cpus_read_lock();
/*
* It's common for the destination firmware to replace cache
* nodes. Release all of the cacheinfo hierarchy's references
* before updating the device tree.
*/
cacheinfo_teardown();
rc = pseries_devicetree_update(MIGRATION_SCOPE);
if (rc)
pr_err("device tree update failed: %d\n", rc);
cacheinfo_rebuild();
cpus_read_unlock();
/* Possibly switch to a new L1 flush type */
pseries_setup_security_mitigations();
/* Reinitialise system information for hv-24x7 */
read_24x7_sys_info();
return;
}
static int poll_vasi_state(u64 handle, unsigned long *res)
{
unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
long hvrc;
int ret;
hvrc = plpar_hcall(H_VASI_STATE, retbuf, handle);
switch (hvrc) {
case H_SUCCESS:
ret = 0;
*res = retbuf[0];
break;
case H_PARAMETER:
ret = -EINVAL;
break;
case H_FUNCTION:
ret = -EOPNOTSUPP;
break;
case H_HARDWARE:
default:
pr_err("unexpected H_VASI_STATE result %ld\n", hvrc);
ret = -EIO;
break;
}
return ret;
}
static int wait_for_vasi_session_suspending(u64 handle)
{
unsigned long state;
int ret;
/*
* Wait for transition from H_VASI_ENABLED to
* H_VASI_SUSPENDING. Treat anything else as an error.
*/
while (true) {
ret = poll_vasi_state(handle, &state);
if (ret != 0 || state == H_VASI_SUSPENDING) {
break;
} else if (state == H_VASI_ENABLED) {
ssleep(1);
} else {
pr_err("unexpected H_VASI_STATE result %lu\n", state);
ret = -EIO;
break;
}
}
/*
* Proceed even if H_VASI_STATE is unavailable. If H_JOIN or
* ibm,suspend-me are also unimplemented, we'll recover then.
*/
if (ret == -EOPNOTSUPP)
ret = 0;
return ret;
}
static void prod_single(unsigned int target_cpu)
{
long hvrc;
int hwid;
hwid = get_hard_smp_processor_id(target_cpu);
hvrc = plpar_hcall_norets(H_PROD, hwid);
if (hvrc == H_SUCCESS)
return;
pr_err_ratelimited("H_PROD of CPU %u (hwid %d) error: %ld\n",
target_cpu, hwid, hvrc);
}
static void prod_others(void)
{
unsigned int cpu;
for_each_online_cpu(cpu) {
if (cpu != smp_processor_id())
prod_single(cpu);
}
}
static u16 clamp_slb_size(void)
{
#ifdef CONFIG_PPC_64S_HASH_MMU
u16 prev = mmu_slb_size;
slb_set_size(SLB_MIN_SIZE);
return prev;
#else
return 0;
#endif
}
static int do_suspend(void)
{
u16 saved_slb_size;
int status;
int ret;
pr_info("calling ibm,suspend-me on CPU %i\n", smp_processor_id());
/*
* The destination processor model may have fewer SLB entries
* than the source. We reduce mmu_slb_size to a safe minimum
* before suspending in order to minimize the possibility of
* programming non-existent entries on the destination. If
* suspend fails, we restore it before returning. On success
* the OF reconfig path will update it from the new device
* tree after resuming on the destination.
*/
saved_slb_size = clamp_slb_size();
ret = rtas_ibm_suspend_me(&status);
if (ret != 0) {
pr_err("ibm,suspend-me error: %d\n", status);
slb_set_size(saved_slb_size);
}
return ret;
}
/**
* struct pseries_suspend_info - State shared between CPUs for join/suspend.
* @counter: Threads are to increment this upon resuming from suspend
* or if an error is received from H_JOIN. The thread which performs
* the first increment (i.e. sets it to 1) is responsible for
* waking the other threads.
* @done: False if join/suspend is in progress. True if the operation is
* complete (successful or not).
*/
struct pseries_suspend_info {
atomic_t counter;
bool done;
};
static int do_join(void *arg)
{
struct pseries_suspend_info *info = arg;
atomic_t *counter = &info->counter;
long hvrc;
int ret;
retry:
/* Must ensure MSR.EE off for H_JOIN. */
hard_irq_disable();
hvrc = plpar_hcall_norets(H_JOIN);
switch (hvrc) {
case H_CONTINUE:
/*
* All other CPUs are offline or in H_JOIN. This CPU
* attempts the suspend.
*/
ret = do_suspend();
break;
case H_SUCCESS:
/*
* The suspend is complete and this cpu has received a
* prod, or we've received a stray prod from unrelated
* code (e.g. paravirt spinlocks) and we need to join
* again.
*
* This barrier orders the return from H_JOIN above vs
* the load of info->done. It pairs with the barrier
* in the wakeup/prod path below.
*/
smp_mb();
if (READ_ONCE(info->done) == false) {
pr_info_ratelimited("premature return from H_JOIN on CPU %i, retrying",
smp_processor_id());
goto retry;
}
ret = 0;
break;
case H_BAD_MODE:
case H_HARDWARE:
default:
ret = -EIO;
pr_err_ratelimited("H_JOIN error %ld on CPU %i\n",
hvrc, smp_processor_id());
break;
}
if (atomic_inc_return(counter) == 1) {
pr_info("CPU %u waking all threads\n", smp_processor_id());
WRITE_ONCE(info->done, true);
/*
* This barrier orders the store to info->done vs subsequent
* H_PRODs to wake the other CPUs. It pairs with the barrier
* in the H_SUCCESS case above.
*/
smp_mb();
prod_others();
}
/*
* Execution may have been suspended for several seconds, so
* reset the watchdog.
*/
touch_nmi_watchdog();
return ret;
}
/*
* Abort reason code byte 0. We use only the 'Migrating partition' value.
*/
enum vasi_aborting_entity {
ORCHESTRATOR = 1,
VSP_SOURCE = 2,
PARTITION_FIRMWARE = 3,
PLATFORM_FIRMWARE = 4,
VSP_TARGET = 5,
MIGRATING_PARTITION = 6,
};
static void pseries_cancel_migration(u64 handle, int err)
{
u32 reason_code;
u32 detail;
u8 entity;
long hvrc;
entity = MIGRATING_PARTITION;
detail = abs(err) & 0xffffff;
reason_code = (entity << 24) | detail;
hvrc = plpar_hcall_norets(H_VASI_SIGNAL, handle,
H_VASI_SIGNAL_CANCEL, reason_code);
if (hvrc)
pr_err("H_VASI_SIGNAL error: %ld\n", hvrc);
}
static int pseries_suspend(u64 handle)
{
const unsigned int max_attempts = 5;
unsigned int retry_interval_ms = 1;
unsigned int attempt = 1;
int ret;
while (true) {
struct pseries_suspend_info info;
unsigned long vasi_state;
int vasi_err;
info = (struct pseries_suspend_info) {
.counter = ATOMIC_INIT(0),
.done = false,
};
ret = stop_machine(do_join, &info, cpu_online_mask);
if (ret == 0)
break;
/*
* Encountered an error. If the VASI stream is still
* in Suspending state, it's likely a transient
* condition related to some device in the partition
* and we can retry in the hope that the cause has
* cleared after some delay.
*
* A better design would allow drivers etc to prepare
* for the suspend and avoid conditions which prevent
* the suspend from succeeding. For now, we have this
* mitigation.
*/
pr_notice("Partition suspend attempt %u of %u error: %d\n",
attempt, max_attempts, ret);
if (attempt == max_attempts)
break;
vasi_err = poll_vasi_state(handle, &vasi_state);
if (vasi_err == 0) {
if (vasi_state != H_VASI_SUSPENDING) {
pr_notice("VASI state %lu after failed suspend\n",
vasi_state);
break;
}
} else if (vasi_err != -EOPNOTSUPP) {
pr_err("VASI state poll error: %d", vasi_err);
break;
}
pr_notice("Will retry partition suspend after %u ms\n",
retry_interval_ms);
msleep(retry_interval_ms);
retry_interval_ms *= 10;
attempt++;
}
return ret;
}
static int pseries_migrate_partition(u64 handle)
{
int ret;
ret = wait_for_vasi_session_suspending(handle);
if (ret)
return ret;
ret = pseries_suspend(handle);
if (ret == 0)
post_mobility_fixup();
else
pseries_cancel_migration(handle, ret);
return ret;
}
int rtas_syscall_dispatch_ibm_suspend_me(u64 handle)
{
return pseries_migrate_partition(handle);
}
static ssize_t migration_store(struct class *class,
struct class_attribute *attr, const char *buf,
size_t count)
{
u64 streamid;
int rc;
rc = kstrtou64(buf, 0, &streamid);
if (rc)
return rc;
rc = pseries_migrate_partition(streamid);
if (rc)
return rc;
return count;
}
/*
* Used by drmgr to determine the kernel behavior of the migration interface.
*
* Version 1: Performs all PAPR requirements for migration including
* firmware activation and device tree update.
*/
#define MIGRATION_API_VERSION 1
static CLASS_ATTR_WO(migration);
static CLASS_ATTR_STRING(api_version, 0444, __stringify(MIGRATION_API_VERSION));
static int __init mobility_sysfs_init(void)
{
int rc;
mobility_kobj = kobject_create_and_add("mobility", kernel_kobj);
if (!mobility_kobj)
return -ENOMEM;
rc = sysfs_create_file(mobility_kobj, &class_attr_migration.attr);
if (rc)
pr_err("unable to create migration sysfs file (%d)\n", rc);
rc = sysfs_create_file(mobility_kobj, &class_attr_api_version.attr.attr);
if (rc)
pr_err("unable to create api_version sysfs file (%d)\n", rc);
return 0;
}
machine_device_initcall(pseries, mobility_sysfs_init);
| 22.606267 | 80 | 0.693124 |
3e00081d8581ad37ca8b21b6b5bab8974038ef81 | 1,263 | h | C | src/chrono_ogre/Graphics/ChOgreCameraManager.h | felixvd/chrono | 4c437fc1fc8964310d53206dda45e8ba9c734fa2 | [
"BSD-3-Clause"
] | 1 | 2015-03-19T16:48:13.000Z | 2015-03-19T16:48:13.000Z | src/chrono_ogre/Graphics/ChOgreCameraManager.h | felixvd/chrono | 4c437fc1fc8964310d53206dda45e8ba9c734fa2 | [
"BSD-3-Clause"
] | null | null | null | src/chrono_ogre/Graphics/ChOgreCameraManager.h | felixvd/chrono | 4c437fc1fc8964310d53206dda45e8ba9c734fa2 | [
"BSD-3-Clause"
] | 1 | 2018-10-25T07:05:40.000Z | 2018-10-25T07:05:40.000Z | /*
Author: Charles Ricchio
Contains a managment class for easy manipulation of the camera. ChOgreCameraManager doesn't actually manage any Ogre
camera objects,
but instead retains points in space and points to orient to in space for easy access for the actual camera object within
ChOgreApplication.
*/
#pragma once
#include "chrono_ogre/ChOgreApi.h"
#include "ChOgreCamera.h"
#include <Ogre.h>
#include <core/ChQuaternion.h>
#include <core/ChVector.h>
#include <vector>
namespace ChOgre {
class CHOGRE_DLL_TAG ChOgreCameraManager {
public:
ChOgreCameraManager(Ogre::SceneManager* SceneManager, Ogre::Viewport* Viewport);
~ChOgreCameraManager();
virtual ChOgreCamera* createCamera(const std::string& Name = ("Camera" + std::to_string(g_CameraCount)));
virtual ChOgreCamera* getCamera(unsigned int iterator);
virtual ChOgreCamera* getCamera(const std::string& Name);
virtual ChOgreCamera* operator[](unsigned int iterator);
virtual ChOgreCamera* operator[](const std::string& Name);
virtual void makeActive(ChOgreCamera* Camera);
protected:
std::vector<ChOgreCamera*> m_CameraList;
Ogre::SceneManager* m_pSceneManager;
Ogre::Viewport* m_pViewport;
static unsigned int g_CameraCount;
private:
};
} | 26.87234 | 120 | 0.756928 |
206d0381338364701b01ac92e1c2b0527c5d50ba | 941 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/SecurityGuardOpenSecureSignature.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/SecurityGuardOpenSecureSignature.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/SecurityGuardOpenSecureSignature.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
#import "ISecurityGuardOpenSecureSignature-Protocol.h"
@class NSString;
@interface SecurityGuardOpenSecureSignature : NSObject <ISecurityGuardOpenSecureSignature>
{
}
- (long long)transferOpenSignType:(long long)arg1;
- (id)callCoreSignFunctionsWithArray:(id)arg1 appKey:(id)arg2 signType:(long long)arg3 mask:(id)arg4;
- (struct _HashMap *)NSDictionary2HashMap:(id)arg1;
- (Class)getMetaClass;
- (id)getSafeCookie:(id)arg1 secretKey:(id)arg2 authCode:(id)arg3;
- (id)signRequest:(id)arg1 authCode:(id)arg2;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 29.40625 | 101 | 0.758767 |
2d38ad3a7786064cb839e3660f2bbb15926a9de2 | 561 | h | C | IntagratingMachine/Pages/ThirdPage/ThirdViewController.h | siggb/FunctionIntegrator | 6af85c8f9db026e6b3b85e1298c298b063bd67e5 | [
"MIT",
"Unlicense"
] | 1 | 2016-07-14T12:59:42.000Z | 2016-07-14T12:59:42.000Z | IntagratingMachine/Pages/ThirdPage/ThirdViewController.h | siggb/FunctionIntegrator | 6af85c8f9db026e6b3b85e1298c298b063bd67e5 | [
"MIT",
"Unlicense"
] | null | null | null | IntagratingMachine/Pages/ThirdPage/ThirdViewController.h | siggb/FunctionIntegrator | 6af85c8f9db026e6b3b85e1298c298b063bd67e5 | [
"MIT",
"Unlicense"
] | null | null | null | //
// ThirdViewController.h
// IntagratingMachine
//
// Created by sig on 30.05.13.
// Copyright (c) 2013 sig. All rights reserved.
//
#import "RootViewController.h"
@interface ThirdViewController : RootViewController
/*
Здесь нам удалось минимизировать:
- погрешность квантования
- погрешность методическую (в незначительной мере)
Погрешность исходных данных и инструментальную погрешность
находятся в допустимом диапазоне yE-6 благодаря используемому
типу данных float с мантиссой в 24 бита.
(порядок 8 бит и 1 скрытый знаковый бит)
*/
@end
| 22.44 | 62 | 0.764706 |
874be0dfe2e6a8cc8f4b75e1baf7d77edec67d6f | 385 | h | C | WeiBang/WeiBang/Module/HomeModule/View/NoticeView/RNOLHomeNoticeView.h | LKPeng/WeiBang | 4a6d4153422200b844e0c846722b9540cbaf4ef7 | [
"MIT"
] | null | null | null | WeiBang/WeiBang/Module/HomeModule/View/NoticeView/RNOLHomeNoticeView.h | LKPeng/WeiBang | 4a6d4153422200b844e0c846722b9540cbaf4ef7 | [
"MIT"
] | null | null | null | WeiBang/WeiBang/Module/HomeModule/View/NoticeView/RNOLHomeNoticeView.h | LKPeng/WeiBang | 4a6d4153422200b844e0c846722b9540cbaf4ef7 | [
"MIT"
] | null | null | null | //
// RNOLHomeNoticeView.h
// RongNiuOnline
//
// Created by apple on 2018/4/8.
// Copyright © 2018年 rongniu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface RNOLHomeNoticeView : UIView
@property (nonatomic,strong) NSArray *msgArray;
@property (nonatomic,copy) void (^noticeIndexBlock)(NSInteger index);
@property (nonatomic,copy) dispatch_block_t moreBlock;
@end
| 20.263158 | 69 | 0.737662 |
eeddfb46b3a0d2bef9fd22bfa0dff7d67b891844 | 1,177 | h | C | 0819-Most-Common-Word/cpp_0819/Solution2.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | 12 | 2020-03-18T14:36:23.000Z | 2021-12-19T02:24:33.000Z | 0819-Most-Common-Word/cpp_0819/Solution2.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | 0819-Most-Common-Word/cpp_0819/Solution2.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | //
// Created by ooooo on 2020/1/30.
//
#ifndef CPP_0819__SOLUTION2_H_
#define CPP_0819__SOLUTION2_H_
#include <iostream>
#include <vector>
#include <regex>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/**
*
*/
class Solution {
public:
string mostCommonWord(string paragraph, vector<string> &banned) {
unordered_map<string, int> m;
unordered_set<string> bannedSet(begin(banned), end(banned));
int i = 0, j = 0;
string ans = "";
int max = 0;
while (true) {
while (i < paragraph.size() && !isalpha(paragraph[i])) {
i++;
}
while (j < paragraph.size() && isalpha(paragraph[j])) {
paragraph[j] = tolower(paragraph[j]);
j++;
}
if (j > i) {
string word = paragraph.substr(i, j - i);
if (!bannedSet.count(word)) {
++m[word];
// 计数的同时可以比较!!!
if (max < m[word]) {
max = m[word];
ans = word;
}
}
j++;
i = j;
} else if (i > j) {
// j不是字符,可能是','
j++;
} else {
break;
}
}
return ans;
}
};
#endif //CPP_0819__SOLUTION2_H_
| 19.949153 | 67 | 0.516568 |
f535ec39159d8c3d183c8e4970b93322b2b2f07b | 2,216 | h | C | ext/lib/ipc/open-amp/open-amp/lib/include/openamp/sh_mem.h | SebastianBoe/fw-nrfconnect-zephyr | c74c0ef21daf7594b5c4d531e75cc72bae29f9b7 | [
"Apache-2.0"
] | 16 | 2019-10-26T17:09:18.000Z | 2022-02-21T12:15:32.000Z | ext/lib/ipc/open-amp/open-amp/lib/include/openamp/sh_mem.h | SebastianBoe/fw-nrfconnect-zephyr | c74c0ef21daf7594b5c4d531e75cc72bae29f9b7 | [
"Apache-2.0"
] | 44 | 2016-12-08T21:36:34.000Z | 2017-10-08T23:29:39.000Z | ext/lib/ipc/open-amp/open-amp/lib/include/openamp/sh_mem.h | SebastianBoe/fw-nrfconnect-zephyr | c74c0ef21daf7594b5c4d531e75cc72bae29f9b7 | [
"Apache-2.0"
] | 8 | 2016-12-08T21:27:13.000Z | 2017-04-13T21:26:04.000Z | /*
* Copyright (c) 2014, Mentor Graphics Corporation
* All rights reserved.
* Copyright (c) 2016 Freescale Semiconductor, Inc. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**************************************************************************
* FILE NAME
*
* sh_mem.c
*
* COMPONENT
*
* IPC Stack for uAMP systems.
*
* DESCRIPTION
*
* Header file for fixed buffer size memory management service. Currently
* it is being used to manage shared memory.
*
**************************************************************************/
#ifndef SH_MEM_H_
#define SH_MEM_H_
#include <metal/mutex.h>
#if defined __cplusplus
extern "C" {
#endif
/* Macros */
#define BITMAP_WORD_SIZE (sizeof(unsigned long) << 3)
#define WORD_SIZE sizeof(unsigned long)
#define WORD_ALIGN(a) (((a) & (WORD_SIZE-1)) != 0)? \
(((a) & (~(WORD_SIZE-1))) + sizeof(unsigned long)):(a)
#define SH_MEM_POOL_LOCATE_BITMAP(pool,idx) ((unsigned char *) pool \
+ sizeof(struct sh_mem_pool) \
+ (BITMAP_WORD_SIZE * idx))
/*
* This structure represents a shared memory pool.
*
* @start_addr - start address of shared memory region
* @lock - lock to ensure exclusive access
* @size - size of shared memory*
* @buff_size - size of each buffer
* @total_buffs - total number of buffers in shared memory region
* @used_buffs - number of used buffers
* @bmp_size - size of bitmap array
*
*/
struct sh_mem_pool {
void *start_addr;
metal_mutex_t lock;
unsigned int size;
unsigned int buff_size;
unsigned int total_buffs;
unsigned int used_buffs;
unsigned int bmp_size;
};
/* APIs */
struct sh_mem_pool *sh_mem_create_pool(void *start_addr, unsigned int size,
unsigned int buff_size);
void sh_mem_delete_pool(struct sh_mem_pool *pool);
void *sh_mem_get_buffer(struct sh_mem_pool *pool);
void sh_mem_free_buffer(void *ptr, struct sh_mem_pool *pool);
int get_first_zero_bit(unsigned long value);
#if defined __cplusplus
}
#endif
#endif /* SH_MEM_H_ */
| 28.410256 | 87 | 0.594765 |
dc79cebb38208b1d4c593c74630098358c52417d | 4,908 | h | C | ext/rhoconnect-client/ext/shared/sync/ClientRegister.h | nhinze/rhoconnect-client | 6a18f334a50923ab494182917d9967fce3f7948f | [
"MIT"
] | 1 | 2016-08-05T13:19:40.000Z | 2016-08-05T13:19:40.000Z | ext/rhoconnect-client/ext/shared/sync/ClientRegister.h | nhinze/rhoconnect-client | 6a18f334a50923ab494182917d9967fce3f7948f | [
"MIT"
] | 4 | 2017-06-06T10:40:25.000Z | 2019-10-07T18:02:36.000Z | ext/rhoconnect-client/ext/shared/sync/ClientRegister.h | nhinze/rhoconnect-client | 6a18f334a50923ab494182917d9967fce3f7948f | [
"MIT"
] | 3 | 2015-10-14T14:39:36.000Z | 2019-10-03T11:54:55.000Z | /*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS 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.
*
* http://rhomobile.com
* Copyright (c) 2011-2016 Symbol Technologies, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS 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.
*
* http://symbol.com
*------------------------------------------------------------------------*/
#pragma once
#ifdef __cplusplus
#include "logging/RhoLog.h"
#include "common/RhoThread.h"
#include "common/RhoStd.h"
#include "net/INetRequest.h"
#include "common/IRhoClassFactory.h"
namespace rho{
namespace sync{
class ILoginListener;
class CSyncEngine;
#define WAIT_BEFOREKILL_SECONDS 3
#define POLL_INTERVAL_SECONDS 60
#define POLL_INTERVAL_INFINITE (unsigned int)(-1)
#define DEFAULT_PUSH_PORT 100
class CClientRegister : protected common::CRhoThread
{
DEFINE_LOGCLASS;
static CClientRegister* m_pInstance;
static bool s_sslVerifyPeer;
static VectorPtr<ILoginListener*> s_loginListeners;
NetRequest m_NetRequest;
String m_strDevicePin;
unsigned int m_nPollInterval;
enum EnState
{
stRegister,
stUnregister
};
EnState m_state;
common::CMutex m_mxStateAccess;
String m_unregisterSession;
String m_unregisterClientID;
public:
static void SetSslVerifyPeer(boolean b);
static bool GetSslVerifyPeer();
static void AddLoginListener(ILoginListener* listener);
static CClientRegister* Get();
static CClientRegister* Create();
static CClientRegister* Create(const String& devicePin);
static void Stop();
static void Destroy();
static CClientRegister* getInstance() { return m_pInstance; }
void setRhoconnectCredentials(const String& user, const String& pass, const String& session);
void dropRhoconnectCredentials(const String& session,const String& clientID);
void setDevicehPin(const String& pin);
const String& getDevicePin() const { return m_strDevicePin; }
void startUp();
protected:
virtual void run();
private:
String getRegisterBody(const String& strClientID);
String getUnregisterBody(const String& strClientID);
CClientRegister();
~CClientRegister();
void doStop();
boolean doRegister(CSyncEngine& oSync);
boolean doUnregister(CSyncEngine& oSync);
net::CNetRequestWrapper getNet(){ return getNetRequest(&m_NetRequest); }
void notifyLoggedIn(const String& user, const String& pass, const String& session);
void notifyLoggedOut(const String& session);
void setState( EnState st );
EnState getState();
};
}
}
#endif //__cplusplus
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void rho_clientregister_create(const char* szDevicePin);
#ifdef __cplusplus
};
#endif //__cplusplus
| 33.162162 | 97 | 0.718826 |
87b4a9993681c86eb6b11275ce2d3800755a1f48 | 609 | h | C | tinymath/Computation.h | Guarneri1743/TinyMath | c1cb399677699a9da037b9575dca2c2af647a0a3 | [
"MIT"
] | null | null | null | tinymath/Computation.h | Guarneri1743/TinyMath | c1cb399677699a9da037b9575dca2c2af647a0a3 | [
"MIT"
] | null | null | null | tinymath/Computation.h | Guarneri1743/TinyMath | c1cb399677699a9da037b9575dca2c2af647a0a3 | [
"MIT"
] | null | null | null | #pragma once
#include "MathDefine.h"
#include "Matrix.h"
#include "Vector.h"
TINYMATH_NAMESPACE
template<typename Component, size_t ROW, size_t N>
TMATH_INLINE Vector<Component, N> operator*(const Matrix<Component, ROW, N>& m, const Vector<Component, N>& v);
template<typename Component>
TMATH_INLINE Vector<Component, 3> transform_point(const Matrix<Component, 4, 4>& m, const Vector<Component, 3>& point);
template<typename Component>
TMATH_INLINE Vector<Component, 3> transform_vector(const Matrix<Component, 4, 4>& m, const Vector<Component, 3>& vec);
END_NAMESPACE
#include "detail/Computation.inl" | 32.052632 | 119 | 0.773399 |
7b85253659ca9d092d86fd02a53fd778c2f0240b | 19,281 | c | C | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56780_a0/bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56780_a0/bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56780_a0/bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*******************************************************************************
*
* DO NOT EDIT THIS FILE!
* This file is auto-generated by fltg from
* INTERNAL/fltg/xgs/ctr/bcm56780_a0/bcm56780_a0_CTR_EGR_TM_BST_PORT_SERVICE_POOL.map.ltl for
* bcm56780_a0
*
* Tool: $SDK/INTERNAL/fltg/bin/fltg
*
* Edits to this file will be lost when it is regenerated.
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include <bcmlrd/bcmlrd_internal.h>
#include <bcmlrd/chip/bcmlrd_id.h>
#include <bcmlrd/chip/bcm56780_a0/bcm56780_a0_lrd_field_data.h>
#include <bcmlrd/chip/bcm56780_a0/bcm56780_a0_lrd_ltm_intf.h>
#include <bcmlrd/chip/bcm56780_a0/bcm56780_a0_lrd_xfrm_field_desc.h>
#include <bcmdrd/chip/bcm56780_a0_enum.h>
#include "bcmltd/chip/bcmltd_common_enumpool.h"
#include "bcm56780_a0_lrd_enumpool.h"
#include <bcmltd/bcmltd_handler.h>
/* CTR_EGR_TM_BST_PORT_SERVICE_POOL field init */
static const bcmlrd_field_data_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map_field_data_mmd[] = {
{ /* 0 PORT_ID */
.flags = BCMLTD_FIELD_F_KEY,
.min = &bcm56780_a0_lrd_ifd_u16_0x0,
.def = &bcm56780_a0_lrd_ifd_u16_0x0,
.max = &bcm56780_a0_lrd_ifd_u16_0x4f,
.depth = 0,
.width = 7,
.edata = NULL,
},
{ /* 1 TM_EGR_SERVICE_POOL_ID */
.flags = BCMLTD_FIELD_F_KEY,
.min = &bcm56780_a0_lrd_ifd_u8_0x0,
.def = &bcm56780_a0_lrd_ifd_u8_0x0,
.max = &bcm56780_a0_lrd_ifd_u8_0x3,
.depth = 0,
.width = 2,
.edata = NULL,
},
{ /* 2 BUFFER_POOL */
.flags = BCMLTD_FIELD_F_KEY,
.min = &bcm56780_a0_lrd_ifd_u8_0x0,
.def = &bcm56780_a0_lrd_ifd_u8_0x0,
.max = &bcm56780_a0_lrd_ifd_u8_0x0,
.depth = 0,
.width = 1,
.edata = NULL,
},
{ /* 3 UC_CELLS */
.flags = 0,
.min = &bcm56780_a0_lrd_ifd_u64_0x0,
.def = &bcm56780_a0_lrd_ifd_u64_0x0,
.max = &bcm56780_a0_lrd_ifd_u64_0x7ffff,
.depth = 0,
.width = 19,
.edata = NULL,
},
{ /* 4 MC_CELLS */
.flags = 0,
.min = &bcm56780_a0_lrd_ifd_u64_0x0,
.def = &bcm56780_a0_lrd_ifd_u64_0x0,
.max = &bcm56780_a0_lrd_ifd_u64_0x7ffff,
.depth = 0,
.width = 19,
.edata = NULL,
},
{ /* 5 OPERATIONAL_STATE */
.flags = BCMLRD_FIELD_F_READ_ONLY | BCMLTD_FIELD_F_ENUM,
.min = &bcm56780_a0_lrd_ifd_u32_0x0,
.def = &bcm56780_a0_lrd_ifd_u32_0x0,
.max = &bcm56780_a0_lrd_ifd_u32_0x2,
.depth = 0,
.width = 2,
.edata = BCMLTD_COMMON_CTR_PORT_ENTRY_STATE_T_DATA,
},
};
const bcmlrd_map_field_data_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map_field_data = {
.fields = 6,
.field = bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map_field_data_mmd
};
static const bcmlrd_map_table_attr_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_attr_entry[] = {
{ /* 0 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_INSTANCE_MAX_INDEX,
.value = 0,
},
{ /* 1 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_INSTANCE_MIN_INDEX,
.value = 0,
},
{ /* 2 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_INTERACTIVE,
.value = true,
},
{ /* 3 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_TABLE_MAX_INDEX,
.value = 319,
},
{ /* 4 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_TABLE_MIN_INDEX,
.value = 0,
},
{ /* 5 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_TRACK_INDEX_MAX_INDEX,
.value = 639,
},
{ /* 6 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_TRACK_INDEX_MIN_INDEX,
.value = 0,
},
};
static const bcmlrd_map_attr_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_attr_group = {
.attributes = 7,
.attr = bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_attr_entry,
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_chip_port_idx_src_field_desc_s0[1] = {
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_PORT_IDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_chip_port_idx_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0[2] = {
{
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = BCMLRD_FIELD_INSTANCE,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0,
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_pt_field_sel_src_field_desc_s0[1] = {
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_UC_CELLSf,
.field_idx = 0,
.minbit = 0,
.maxbit = 63,
.entry_idx = 0,
.reserved = 0
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_pt_field_sel_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0[4] = {
{
.field_id = SP0_BST_PORT_SHARED_COUNTf,
.field_idx = 0,
.minbit = 0,
.maxbit = 18,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = SP1_BST_PORT_SHARED_COUNTf,
.field_idx = 0,
.minbit = 20,
.maxbit = 38,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = SP2_BST_PORT_SHARED_COUNTf,
.field_idx = 0,
.minbit = 40,
.maxbit = 58,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = SP3_BST_PORT_SHARED_COUNTf,
.field_idx = 0,
.minbit = 60,
.maxbit = 78,
.entry_idx = 0,
.reserved = 0,
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_track_index_src_field_desc_s2[3] = {
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_PORT_IDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_TM_EGR_SERVICE_POOL_IDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 1,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_BUFFER_POOLf,
.field_idx = 0,
.minbit = 0,
.maxbit = 1,
.entry_idx = 0,
.reserved = 0
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_track_index_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0[1] = {
{
.field_id = BCMLRD_FIELD_TRACK_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 31,
.entry_idx = 0,
.reserved = 0,
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_port_pt_suppress_src_field_desc_s0[1] = {
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_PORT_IDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_port_pt_suppress_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0[1] = {
{
.field_id = BCMLRD_FIELD_PT_SUPPRESS,
.field_idx = 0,
.minbit = 0,
.maxbit = 31,
.entry_idx = 0,
.reserved = 0,
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_port_oper_state_src_field_desc_s0[1] = {
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_OPERATIONAL_STATEf,
.field_idx = 0,
.minbit = 0,
.maxbit = 31,
.entry_idx = 0,
.reserved = 0
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_chip_port_sp_idx_src_field_desc_s0[2] = {
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_PORT_IDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_TM_EGR_SERVICE_POOL_IDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 1,
.entry_idx = 0,
.reserved = 0
},
};
const bcmltd_field_desc_t
bcm56780_a0_lrd_bcmltx_chip_port_sp_idx_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0[2] = {
{
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 9,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = BCMLRD_FIELD_INSTANCE,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0,
},
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_chip_port_idx_xfrm_handler_fwd_s0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_CHIP_PORT_IDX_XFRM_HANDLER_FWD_S0_D0_ID,
.src_fields = 1,
.src = bcm56780_a0_lrd_bcmltx_chip_port_idx_src_field_desc_s0,
.dst_fields = 2,
.dst = bcm56780_a0_lrd_bcmltx_chip_port_idx_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0,
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_pt_field_sel_xfrm_handler_fwd_s0_k0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_PT_FIELD_SEL_XFRM_HANDLER_FWD_S0_K0_D0_ID,
.src_fields = 1,
.src = bcm56780_a0_lrd_bcmltx_pt_field_sel_src_field_desc_s0,
.dst_fields = 4,
.dst = bcm56780_a0_lrd_bcmltx_pt_field_sel_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0,
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_pt_field_sel_xfrm_handler_rev_s0_k0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_PT_FIELD_SEL_XFRM_HANDLER_REV_S0_K0_D0_ID,
.src_fields = 4,
.src = bcm56780_a0_lrd_bcmltx_pt_field_sel_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0,
.dst_fields = 1,
.dst = bcm56780_a0_lrd_bcmltx_pt_field_sel_src_field_desc_s0,
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_track_index_xfrm_handler_fwd_s2_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_TRACK_INDEX_XFRM_HANDLER_FWD_S2_D0_ID,
.src_fields = 3,
.src = bcm56780_a0_lrd_bcmltx_track_index_src_field_desc_s2,
.dst_fields = 1,
.dst = bcm56780_a0_lrd_bcmltx_track_index_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0,
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_track_index_xfrm_handler_rev_s2_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_TRACK_INDEX_XFRM_HANDLER_REV_S2_D0_ID,
.src_fields = 1,
.src = bcm56780_a0_lrd_bcmltx_track_index_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0,
.dst_fields = 3,
.dst = bcm56780_a0_lrd_bcmltx_track_index_src_field_desc_s2,
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_port_pt_suppress_xfrm_handler_fwd_s0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_PORT_PT_SUPPRESS_XFRM_HANDLER_FWD_S0_D0_ID,
.src_fields = 1,
.src = bcm56780_a0_lrd_bcmltx_port_pt_suppress_src_field_desc_s0,
.dst_fields = 1,
.dst = bcm56780_a0_lrd_bcmltx_port_pt_suppress_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0,
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_port_oper_state_xfrm_handler_rev_s0_k0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_PORT_OPER_STATE_XFRM_HANDLER_REV_S0_K0_D0_ID,
.src_fields = 0,
.src = NULL,
.dst_fields = 1,
.dst = bcm56780_a0_lrd_bcmltx_port_oper_state_src_field_desc_s0,
};
const bcmlrd_field_xfrm_desc_t
bcm56780_a0_lta_bcmltx_chip_port_sp_idx_xfrm_handler_fwd_s0_d0_x0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56780_A0_LTA_BCMLTX_CHIP_PORT_SP_IDX_XFRM_HANDLER_FWD_S0_D0_X0_ID,
.src_fields = 2,
.src = bcm56780_a0_lrd_bcmltx_chip_port_sp_idx_src_field_desc_s0,
.dst_fields = 2,
.dst = bcm56780_a0_lrd_bcmltx_chip_port_sp_idx_ctr_egr_tm_bst_port_service_pool_dst_field_desc_d0,
};
static const bcmlrd_map_entry_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_mmu_thdo_bst_shared_port_map_entry[] = {
{ /* 0 */
.entry_type = BCMLRD_MAP_ENTRY_FWD_KEY_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_chip_port_idx_xfrm_handler_fwd_s0_d0 */
.desc = &bcm56780_a0_lta_bcmltx_chip_port_idx_xfrm_handler_fwd_s0_d0_desc,
},
},
},
{ /* 1 */
.entry_type = BCMLRD_MAP_ENTRY_FWD_VALUE_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_pt_field_sel_xfrm_handler_fwd_s0_k0_d0 */
.desc = &bcm56780_a0_lta_bcmltx_pt_field_sel_xfrm_handler_fwd_s0_k0_d0_desc,
},
},
},
{ /* 2 */
.entry_type = BCMLRD_MAP_ENTRY_REV_VALUE_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_pt_field_sel_xfrm_handler_rev_s0_k0_d0 */
.desc = &bcm56780_a0_lta_bcmltx_pt_field_sel_xfrm_handler_rev_s0_k0_d0_desc,
},
},
},
};
static const bcmlrd_map_entry_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_mmu_thdo_bst_shared_portsp_mc_map_entry[] = {
{ /* 0 */
.entry_type = BCMLRD_MAP_ENTRY_MAPPED_VALUE,
.desc = {
.field_id = SHARED_COUNTf,
.field_idx = 0,
.minbit = 0,
.maxbit = 18,
.entry_idx = 0,
.reserved = 0
},
.u = {
.mapped = {
.src = {
.field_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt_MC_CELLSf,
.field_idx = 0,
.minbit = 0,
.maxbit = 18,
.entry_idx = 0,
.reserved = 0
}
}
},
},
{ /* 1 */
.entry_type = BCMLRD_MAP_ENTRY_FWD_KEY_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_track_index_xfrm_handler_fwd_s2_d0 */
.desc = &bcm56780_a0_lta_bcmltx_track_index_xfrm_handler_fwd_s2_d0_desc,
},
},
},
{ /* 2 */
.entry_type = BCMLRD_MAP_ENTRY_REV_KEY_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_track_index_xfrm_handler_rev_s2_d0 */
.desc = &bcm56780_a0_lta_bcmltx_track_index_xfrm_handler_rev_s2_d0_desc,
},
},
},
{ /* 3 */
.entry_type = BCMLRD_MAP_ENTRY_FWD_KEY_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_port_pt_suppress_xfrm_handler_fwd_s0_d0 */
.desc = &bcm56780_a0_lta_bcmltx_port_pt_suppress_xfrm_handler_fwd_s0_d0_desc,
},
},
},
{ /* 4 */
.entry_type = BCMLRD_MAP_ENTRY_ALWAYS_REV_VALUE_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_port_oper_state_xfrm_handler_rev_s0_k0_d0 */
.desc = &bcm56780_a0_lta_bcmltx_port_oper_state_xfrm_handler_rev_s0_k0_d0_desc,
},
},
},
{ /* 5 */
.entry_type = BCMLRD_MAP_ENTRY_FWD_KEY_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56780_a0_lta_bcmltx_chip_port_sp_idx_xfrm_handler_fwd_s0_d0_x0 */
.desc = &bcm56780_a0_lta_bcmltx_chip_port_sp_idx_xfrm_handler_fwd_s0_d0_x0_desc,
},
},
},
};
static const bcmlrd_map_entry_t
bcm56780_a0_lrd_bcmltx_ctr_egr_tm_bst_port_service_pool_validate_entry[] = {
{ /* 0 */
.entry_type = BCMLRD_MAP_ENTRY_VALUE_FIELD_VALIDATION,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
/* handler: bcm56780_a0_lta_bcmltx_ctr_egr_tm_bst_port_service_pool_std_val_fv_handler */
.handler_id = BCMLTD_VALIDATE_BCM56780_A0_LTA_BCMLTX_CTR_EGR_TM_BST_PORT_SERVICE_POOL_STD_VAL_FV_HANDLER_ID
}
},
};
static const bcmlrd_map_group_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map_group[] = {
{
.dest = {
.kind = BCMLRD_MAP_PHYSICAL,
.id = MMU_THDO_BST_SHARED_PORTm,
},
.entries = 3,
.entry = bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_mmu_thdo_bst_shared_port_map_entry
},
{
.dest = {
.kind = BCMLRD_MAP_PHYSICAL,
.id = MMU_THDO_BST_SHARED_PORTSP_MCm,
},
.entries = 6,
.entry = bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_mmu_thdo_bst_shared_portsp_mc_map_entry
},
{
.dest = {
.kind = BCMLRD_MAP_VALIDATION,
.id = 0,
},
.entries = 1,
.entry = bcm56780_a0_lrd_bcmltx_ctr_egr_tm_bst_port_service_pool_validate_entry
},
};
const bcmlrd_map_t bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map = {
.src_id = CTR_EGR_TM_BST_PORT_SERVICE_POOLt,
.field_data = &bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map_field_data,
.groups = 3,
.group = bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_pool_map_group,
.table_attr = &bcm56780_a0_lrd_ctr_egr_tm_bst_port_service_poolt_attr_group,
.entry_ops = BCMLRD_MAP_TABLE_ENTRY_OPERATION_LOOKUP | BCMLRD_MAP_TABLE_ENTRY_OPERATION_TRAVERSE | BCMLRD_MAP_TABLE_ENTRY_OPERATION_INSERT | BCMLRD_MAP_TABLE_ENTRY_OPERATION_UPDATE | BCMLRD_MAP_TABLE_ENTRY_OPERATION_DELETE
};
| 31.712171 | 226 | 0.619003 |
f49811ef69c457faf7f67bc07cdea007f79051a4 | 1,991 | c | C | bin/import/segy2css/decode.c | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 30 | 2015-02-20T21:44:29.000Z | 2021-09-27T02:53:14.000Z | bin/import/segy2css/decode.c | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 14 | 2015-07-07T19:17:24.000Z | 2020-12-19T19:18:53.000Z | bin/import/segy2css/decode.c | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 46 | 2015-02-06T16:22:41.000Z | 2022-03-30T11:46:37.000Z | /* @(#)decode.c 1.1 03/12/96 */
/********************************************************************
*
*
* sgycss/decode.c
*
* Program decode serial instrument code to the station name.
* The station names can be determined in .segy2css file
* or in any ASCII file which will be specified in
* the command line(see manual for details). Files should be in a format :
*
* INS_SER_NUM START_TIME END_TIME STA_NAME
*
* START_TIME and END_TIME should be in a format: YYYYDDD:HH:MM:SS.mSS.
* If for current serial instrument code station name was not
* determined, then make station name in form : 'snum', where
* snum - is serial instrument code.
*
*********************************************************************/
#include "segcss.h"
char *decode(num, dates, name, param, parnum)
int num;
struct data *dates;
char name[12];
struct conver *param;
int parnum;
{
struct conver tmp;
double stime;
double etime;
double crnt_time;
int get, j, i;
long date;
get = 0;
date = dates->yr * 1000 + dates->day;
/* Get start time for currend data file */
crnt_time = dtoepoch( date ) +
3600.0*dates->hour +
60.0*dates->min +
(double) dates->sec + (double)dates->msec/1000.0;
/* Check first do we have instrumen number conversion in file ".segy2css" */
if(parnum > 0) {
for(i = 0; i < parnum; i++) {
tmp = param[i];
stime = str2epoch(tmp.stime);
etime = str2epoch(tmp.etime);
if(num == tmp.sernum)
if( (crnt_time >= stime) && (crnt_time <= etime) ) {
strcpy(name, tmp.sname);
get = 1;
break;
}
}
} else get = 0;
/* The are not station name for current serial instrument code.
Make name as "num" - serial instrument code */
if(!get)
sprintf(name,"%d\0",num);
}
| 26.546667 | 77 | 0.526369 |
21c7da87ae747e38f873ebbeaf6aeb3af6456da3 | 3,882 | h | C | components/i2cdev/include/debug_cf.h | rberenguel/micropython-core2 | f06b961211bd0699794bcd604d4ae652d942d421 | [
"Apache-2.0"
] | null | null | null | components/i2cdev/include/debug_cf.h | rberenguel/micropython-core2 | f06b961211bd0699794bcd604d4ae652d942d421 | [
"Apache-2.0"
] | null | null | null | components/i2cdev/include/debug_cf.h | rberenguel/micropython-core2 | f06b961211bd0699794bcd604d4ae652d942d421 | [
"Apache-2.0"
] | null | null | null | /*
*
* ESP-Drone Firmware
*
* Copyright 2019-2020 Espressif Systems (Shanghai)
* Copyright (C) 2011-2012 Bitcraze AB
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, in version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* debug_cf.h - Debugging utility functions
*/
#ifndef _DEBUG_CF_H
#define _DEBUG_CF_H
#include "config.h"
//if enable, some message will print to remote client
//#define DEBUG_PRINT_ON_CONSOLE
#ifdef DEBUG_PRINT_ON_UART
#include "uart1.h"
#define uartPrintf uart1Printf
#endif
#ifdef DEBUG_PRINT_ON_SEGGER_RTT
#include "SEGGER_RTT.h"
#endif
#ifndef DEBUG_MODULE
#define DEBUG_MODULE "NULL"
#define DEBUG_FMT(fmt) (DEBUG_MODULE ": " fmt)
#else
#define DEBUG_FMT(fmt) (DEBUG_MODULE ": " fmt)
#endif
#ifndef DEBUG_FMT
#define DEBUG_FMT(fmt) fmt
#endif
void debugInit(void);
#include "esp_log.h"
#define DEBUG_PRINT_LOCAL(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINT_REMOT(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
#if defined(DEBUG_PRINT_ON_UART)
#define DEBUG_PRINT(fmt, ...) uartPrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
#define DEBUG_PRINT_OS(fmt, ...) uartPrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
#elif defined(DEBUG_PRINT_ON_SWO)
#define DEBUG_PRINT(fmt, ...) eprintf(ITM_SendChar, fmt, ## __VA_ARGS__)
#define DEBUG_PRINT_OS(fmt, ...) eprintf(ITM_SendChar, fmt, ## __VA_ARGS__)
#elif defined(DEBUG_PRINT_ON_SEGGER_RTT)
#define DEBUG_PRINT(fmt, ...) SEGGER_RTT_printf(0, fmt, ## __VA_ARGS__)
#define DEBUG_PRINT_OS(fmt, ...) SEGGER_RTT_printf(0, fmt, ## __VA_ARGS__)
#elif defined(DEBUG_PRINT_ON_CONSOLE)// Debug using radio or USB
#include "esp_log.h"
#define DEBUG_PRINT(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINTE(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
#define DEBUG_PRINTW(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
#define DEBUG_PRINTI(fmt, ...) consolePrintf(DEBUG_FMT(fmt), ##__VA_ARGS__)
#define DEBUG_PRINTD(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINTV(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_VERBOSE,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINT_OS(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#else
#define DEBUG_PRINT(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINTE(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_ERROR,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINTW(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_WARN,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINTI(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINTD(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINTV(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_VERBOSE,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#define DEBUG_PRINT_OS(fmt, ...) ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO,DEBUG_MODULE,fmt, ##__VA_ARGS__)
#endif
#ifndef PRINT_OS_DEBUG_INFO
#undef DEBUG_PRINT_OS
#define DEBUG_PRINT_OS(fmt, ...)
#endif
#ifdef TEST_PRINTS
#define TEST_AND_PRINT(e, msgOK, msgFail)\
if(e) { DEBUG_PRINT(msgOK); } else { DEBUG_PRINT(msgFail); }
#define FAIL_PRINT(msg) DEBUG_PRINT(msg)
#else
#define TEST_AND_PRINT(e, msgOK, msgFail)
#define FAIL_PRINT(msg)
#endif
#endif
| 37.68932 | 102 | 0.755281 |
2997462d38c4c2d05573178d3f61a22707ffca7d | 263 | h | C | HMModules/HomeMateModule/HomeMateModule/Classes/HMSDK/HMCmds/QueryDataFromMixPadCmd.h | kenny2006cen/GYXMPP | fdeaddde91c78b132f747501c09486b7c33ec5d4 | [
"MIT"
] | null | null | null | HMModules/HomeMateModule/HomeMateModule/Classes/HMSDK/HMCmds/QueryDataFromMixPadCmd.h | kenny2006cen/GYXMPP | fdeaddde91c78b132f747501c09486b7c33ec5d4 | [
"MIT"
] | null | null | null | HMModules/HomeMateModule/HomeMateModule/Classes/HMSDK/HMCmds/QueryDataFromMixPadCmd.h | kenny2006cen/GYXMPP | fdeaddde91c78b132f747501c09486b7c33ec5d4 | [
"MIT"
] | 1 | 2021-10-10T12:32:01.000Z | 2021-10-10T12:32:01.000Z | //
// QueryDataFromMixPadCmd.h
// HomeMateSDK
//
// Created by orvibo on 2019/1/5.
// Copyright © 2019 orvibo. All rights reserved.
//
#import "BaseCmd.h"
@interface QueryDataFromMixPadCmd : BaseCmd
@property (nonatomic,strong)NSDictionary *dataDic;
@end
| 16.4375 | 50 | 0.722433 |
2118705c956755587223fe0200896e65015361a4 | 2,842 | c | C | img-svg.c | richinfante/fbutils | cacfd8d1607e1026d6050d2b755c663a94ccb941 | [
"MIT"
] | 4 | 2020-05-30T17:40:18.000Z | 2022-01-16T01:16:10.000Z | img-svg.c | richinfante/fbutils | cacfd8d1607e1026d6050d2b755c663a94ccb941 | [
"MIT"
] | 1 | 2021-07-01T15:33:46.000Z | 2021-07-01T15:33:46.000Z | img-svg.c | richinfante/fbutils | cacfd8d1607e1026d6050d2b755c663a94ccb941 | [
"MIT"
] | 1 | 2020-03-31T22:26:32.000Z | 2020-03-31T22:26:32.000Z | #include <librsvg/rsvg.h>
#include <cairo.h>
#include <cairo-svg.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "draw.h"
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
image_t * read_svg_file(char* filename, int requested_width, int requested_height) {
struct stat stat;
int fd = open(filename, O_RDONLY);
fstat(fd, &stat);
unsigned char*file_contents = malloc(sizeof(char) * stat.st_size);
// Read contents
read(fd, file_contents, stat.st_size);
// Load from SVG data
GError *err = NULL;
RsvgHandle *svg = rsvg_handle_new_from_data (file_contents, stat.st_size, &err);
if(err != NULL) {
printf("SVG Load Error: %s", err->message);
}
// Get sizing data
RsvgDimensionData dimensions;
rsvg_handle_get_dimensions(svg, &dimensions);
//scale into the requested resolution
double width;
double height;
double scale_width = 1;
double scale_height = 1;
// Some auto-scaling logic for the image.
if (requested_width != 0 && requested_height != 0) {
// If both width and height are nonzero, draw using given size
width = requested_width;
height = requested_height;
scale_width = width / dimensions.width;
scale_height = height / dimensions.height;
} else if (requested_width == 0 && requested_height == 0) {
// If both are zero, autosize.
width = dimensions.width;
height = dimensions.height;
scale_width = 1;
scale_height = 1;
} else if (requested_width != 0) {
// Auto-scale the height if 0
width = requested_width;
height = round(dimensions.height * scale_height);
scale_width = width / dimensions.width;
scale_height = scale_width;
} else {
// Auto-scale the width if 0
width = round(dimensions.width * scale_width);
height = requested_height;
scale_height = height / dimensions.height;
scale_width = scale_height;
}
// Allocate an output image
image_t* out_image = malloc(sizeof(image_t));
out_image->data = malloc(sizeof(int) * width * height);
out_image->width = width;
out_image->height = height;
// Create a canvas
cairo_surface_t *canvas = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cairo_t *cr = cairo_create(canvas);
cairo_scale(cr, scale_width, scale_height);
// Render
if (!rsvg_handle_render_cairo(svg, cr)) {
printf("SVG Render Error!\n");
}
// Extract the image stride
int stride = cairo_image_surface_get_stride(canvas); //should be equal to width * channels
int size = stride * height;
// Flush + extract image
cairo_surface_flush(canvas);
memcpy(out_image->data, cairo_image_surface_get_data(canvas), size);
// Cleanup
g_object_unref(svg);
cairo_surface_destroy(canvas);
cairo_destroy(cr);
return out_image;
} | 28.707071 | 92 | 0.697044 |
f8e296214eabcfcce248097f45854593b1944a61 | 12,552 | c | C | kernel/modules/drivers/char/brcm/fuse_ril/bcm_kril_ioctl.c | foxsake/infuzion-sgp | 2b7e22ea2069e0d74a8721c9f5389378c29e709c | [
"Apache-2.0"
] | null | null | null | kernel/modules/drivers/char/brcm/fuse_ril/bcm_kril_ioctl.c | foxsake/infuzion-sgp | 2b7e22ea2069e0d74a8721c9f5389378c29e709c | [
"Apache-2.0"
] | null | null | null | kernel/modules/drivers/char/brcm/fuse_ril/bcm_kril_ioctl.c | foxsake/infuzion-sgp | 2b7e22ea2069e0d74a8721c9f5389378c29e709c | [
"Apache-2.0"
] | 1 | 2020-11-04T06:53:55.000Z | 2020-11-04T06:53:55.000Z | /****************************************************************************
*
* Copyright (c) 2009 Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2, available
* at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html (the "GPL").
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
****************************************************************************/
#include "bcm_kril_common.h"
#include "bcm_kril_cmd_handler.h"
#include "bcm_kril_ioctl.h"
#include "bcm_kril_main.h"
#define RESULT_NOT_EMPTY 255
extern KRIL_CmdQueue_t gKrilCmdQueue;
extern KRIL_Param_t gKrilParam;
extern KRIL_ResultQueue_t gKrilResultQueue;
// **FIXME** temporary until sysrpc is "modularized"
extern void PMU_BattADCReq( void );
bcm_kril_dev_result_t bcm_dev_results[TOTAL_BCMDEVICE_NUM] = {0};
int g_kril_initialised = 0;
/**
@fn Int32 KRIL_GetRsp()
*/
Int32 KRIL_GetRsp(struct file *filp, UInt32 cmd, UInt32 arg)
{
Int32 rv = 0;
KRIL_Param_t *priv = filp->private_data;
KRIL_Response_t rsp;
struct list_head *entry;
KRIL_ResultQueue_t *buf_handle = NULL;
UInt32 flags;
if (copy_from_user(&rsp, (KRIL_Response_t*)arg, sizeof(rsp)))
{
rv = -EFAULT;
return rv;
}
/* We claim a mutex because we don't want two
users getting something from the queue at a time.
Since we have to release the spinlock before we can
copy the data to the user, it's possible another
user will grab something from the queue, too. Then
the messages might get out of order if something
fails and the message gets put back onto the
queue. This mutex prevents that problem. */
mutex_lock(&priv->recv_mutex);
/* Grab the message off the list. */
spin_lock_irqsave(&(priv->recv_lock), flags);
if (list_empty(&(gKrilResultQueue.list)))
{
spin_unlock_irqrestore(&(priv->recv_lock), flags);
rv = -EAGAIN;
KRIL_DEBUG(DBG_ERROR, "ERROR: KRIL Result List is empty %p\n", &(gKrilResultQueue.list));
goto recv_err;
}
entry = gKrilResultQueue.list.next;
buf_handle = list_entry(entry, KRIL_ResultQueue_t, list);
list_del(entry);
spin_unlock_irqrestore(&(priv->recv_lock), flags);
if ((NULL == buf_handle->result_info.data) || (0 == buf_handle->result_info.datalen))
{
if ((NULL == buf_handle->result_info.data) != (0 == buf_handle->result_info.datalen))
{
KRIL_DEBUG(DBG_ERROR, "ERROR: KRIL Result data is Wrong %p, len %d\n", buf_handle->result_info.data, buf_handle->result_info.datalen);
//Must enter data abort here
goto recv_putback_on_err;
}
}
rsp.client = buf_handle->result_info.client;
rsp.t = buf_handle->result_info.t;
rsp.result = buf_handle->result_info.result;
rsp.CmdID = buf_handle->result_info.CmdID;
rsp.datalen = buf_handle->result_info.datalen;
if (0 != buf_handle->result_info.datalen)
{
if (copy_to_user(rsp.data, buf_handle->result_info.data, buf_handle->result_info.datalen))
{
rv = -EFAULT;
KRIL_DEBUG(DBG_ERROR, "ERROR: KRIL copy response dara to user Fail\n");
goto recv_putback_on_err;
}
}
if (copy_to_user(arg, &rsp, sizeof(KRIL_Response_t)))
{
rv = -EFAULT;
KRIL_DEBUG(DBG_ERROR, "ERROR: KRIL copy response infor to user Fail\n");
goto recv_putback_on_err;
}
if (0 != buf_handle->result_info.datalen && buf_handle->result_info.data )
{
kfree( buf_handle->result_info.data );
}
kfree(buf_handle);
buf_handle = NULL;
if (false == list_empty(&(gKrilResultQueue.list))) //not empty
{
KRIL_DEBUG(DBG_INFO, "rsp continue read list:%p, next:%p\n", &(gKrilResultQueue.list), gKrilResultQueue.list.next);
rv = RESULT_NOT_EMPTY;
}
mutex_unlock(&priv->recv_mutex);
return rv;
recv_putback_on_err:
/* If we got an error, put the message back onto
the head of the queue. */
//KRIL_DEBUG(DBG_INFO, "recv_putback_on_err handle s_addr:%p, d_addr:%p\n", entry, &(gKrilResultQueue.list));
spin_lock_irqsave(&(priv->recv_lock), flags);
list_add(entry, &(gKrilResultQueue.list));
spin_unlock_irqrestore(&(priv->recv_lock), flags);
mutex_unlock(&priv->recv_mutex);
return rv;
recv_err:
mutex_unlock(&priv->recv_mutex);
return rv;
}
Int32 KRIL_SendCmd(UInt32 cmd, UInt32 arg)
{
KRIL_CmdQueue_t *kril_cmd = NULL;
void *tdata = NULL;
//validate CMD
if (_IOC_TYPE(cmd) != BCM_RILIO_MAGIC)
{
KRIL_DEBUG(DBG_ERROR, "BCM_RILIO_MAGIC:0x%x _IOC_TYPE(cmd):0x%lx error!\n", BCM_RILIO_MAGIC, _IOC_TYPE(cmd));
return -ENOTTY;
}
kril_cmd = kmalloc(sizeof(KRIL_CmdQueue_t), GFP_KERNEL);
if(!kril_cmd)
{
KRIL_DEBUG(DBG_ERROR, "Unable to allocate kril_cmd memory\n");
}
else
{
kril_cmd->cmd = cmd;
kril_cmd->ril_cmd = kmalloc(sizeof(KRIL_Command_t), GFP_KERNEL);
if(!kril_cmd->ril_cmd) {
KRIL_DEBUG(DBG_ERROR, "Unable to allocate kril_cmd memory\n");
return 0;
}
if(copy_from_user(kril_cmd->ril_cmd, (KRIL_Command_t *)arg, sizeof(KRIL_Command_t))!=0)
{
KRIL_DEBUG(DBG_ERROR, "Copy cmd form user space is fail\n");
kfree(kril_cmd->ril_cmd);
kfree(kril_cmd);
return 0;
}
KRIL_DEBUG(DBG_INFO, "client:%d RIL_Token:%p CmdID:%d datalen:%d\n", kril_cmd->ril_cmd->client, kril_cmd->ril_cmd->t, kril_cmd->ril_cmd->CmdID, kril_cmd->ril_cmd->datalen);
if (0 != kril_cmd->ril_cmd->datalen)
{
tdata = kmalloc(kril_cmd->ril_cmd->datalen, GFP_KERNEL);
if(NULL == tdata)
{
KRIL_DEBUG(DBG_ERROR, "KRIL_SendCmd:copy_from_user is fail\n");
kfree(tdata);
kfree(kril_cmd->ril_cmd);
kfree(kril_cmd);
return 0;
}
else
{
copy_from_user(tdata, kril_cmd->ril_cmd->data, kril_cmd->ril_cmd->datalen);
KRIL_DEBUG(DBG_INFO, "tdata memory allocate success tdata:%p\n", kril_cmd->ril_cmd->data);
kril_cmd->ril_cmd->data = tdata;
}
}
else
{
KRIL_DEBUG(DBG_TRACE, "uril datalen is 0\n");
kril_cmd->ril_cmd->data = NULL;
}
mutex_lock(&gKrilCmdQueue.mutex);
list_add_tail(&kril_cmd->list, &gKrilCmdQueue.list);
mutex_unlock(&gKrilCmdQueue.mutex);
queue_work(gKrilCmdQueue.cmd_wq, &gKrilCmdQueue.commandq);
KRIL_DEBUG(DBG_INFO, "head cmd:%ld list:%p next:%p prev:%p\n", kril_cmd->cmd, &kril_cmd->list, kril_cmd->list.next, kril_cmd->list.prev);
}
return 0;
}
//******************************************************************************
//
// Function Name: KRIL_Register
//
// Description : For BCM device driver register
//
// PARAMETERS : clientID Device driver client ID
// : resultCb Function callback for receiving CAPI2 response
// : notifyCb Function callback for receiving unsolicited
// notifications
// : notifyid_list The notify ID list that device driver want
// to receive.
// Ex. UInt32 NotifyIdList[]={NotifyId1, NotifyId2, NotifyId3};
// : notifyid_list_len The number of notify ID in this list.
// Ex. sizeof(NotifyIdList)/sizeof(UInt32)
//
// RETURN : 1 register successfully ; 0 register failed
// Notes:
//
//******************************************************************************
int KRIL_Register(UInt32 clientID,
RILResponseCallbackFunc resultCb,
RILNotifyCallbackFunc notifyCb,
UInt32 *notifyid_list,
int notifyid_list_len)
{
KRIL_DEBUG(DBG_TRACE,"clientID:%lu register KRIL: notifyid_list_len:%d\n", clientID, notifyid_list_len);
if (TOTAL_BCMDEVICE_NUM < clientID)
{
KRIL_DEBUG(DBG_ERROR,"Invalid client ID:%lu\n", clientID);
return 0;
}
if(bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].registered == 1)
{
KRIL_DEBUG(DBG_ERROR,"Client ID:%lu has been registered\n", clientID);
return 0;
}
bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].resultCb = resultCb;
bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].notifyCb = notifyCb;
// Register Notify ID list
if(notifyid_list != NULL && notifyid_list_len != 0)
{
bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].notifyid_list = kmalloc(sizeof(UInt32)*notifyid_list_len, GFP_KERNEL);
if(!bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].notifyid_list)
{
KRIL_DEBUG(DBG_ERROR,"Allocate clientID:%ld notifyid_list memory failed\n",clientID);
return 0;
}
memcpy(bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].notifyid_list, notifyid_list, sizeof(UInt32)*notifyid_list_len);
bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].notifyid_list_len = notifyid_list_len;
}
bcm_dev_results[RIL_CLIENTID_INDEX(clientID)].registered = 1;
return 1;
}
//******************************************************************************
//
// Function Name: KRIL_DevSpecific_Cmd
//
// Description : For BCM device driver implement CAPI2 command
//
// PARAMETERS : clientID Device driver client ID.
// : CmdID The device specific command ID for CAPI2.
// : data Command data buffer point .
// : datalen Command data length.
//
// RETURN : 1 register successfully ; 0 register failed
// Notes:
//
//******************************************************************************
int KRIL_DevSpecific_Cmd(unsigned short client , UInt32 CmdID, void *data, size_t datalen)
{
KRIL_CmdQueue_t *kril_cmd = NULL;
if(!g_kril_initialised)
{
KRIL_DEBUG(DBG_ERROR,"kril is not yet initialised !!!\n");
return 0;
}
if(client != BCM_KRIL_CLIENT && !bcm_dev_results[RIL_CLIENTID_INDEX(client)].registered)
{
KRIL_DEBUG(DBG_ERROR,"device client:%u is not yet registered !!!\n", client);
return 0;
}
KRIL_DEBUG(DBG_TRACE,"client:%d CmdID:%lu(0x%lX)\n", client, CmdID, CmdID);
if ( (client == BCM_POWER_CLIENT) && (RIL_DEVSPECIFICPARAM_BCM_PMU_GET_BATT_ADC == CmdID) )
{
// temporary special case because PMU issues this request before KRIL driver
// has been opened by URIL... This will go away soon, as sysrpc will be made into
// a standalone module with a separate interface for PMU
PMU_BattADCReq();
return 1;
}
kril_cmd = kmalloc(sizeof(KRIL_CmdQueue_t), GFP_KERNEL);
if(!kril_cmd)
{
KRIL_DEBUG(DBG_ERROR,"Allocate kril_cmd memory failed\n");
return 0;
}
kril_cmd->cmd = 0XFF;
kril_cmd->ril_cmd = kmalloc(sizeof(KRIL_Command_t), GFP_KERNEL);
if(!kril_cmd->ril_cmd)
{
KRIL_DEBUG(DBG_ERROR,"Allocate ril_cmd memory failed\n");
goto Out;
}
kril_cmd->ril_cmd->client = client;
kril_cmd->ril_cmd->CmdID = CmdID;
kril_cmd->ril_cmd->datalen = datalen;
if(data != NULL && datalen != 0)
{
kril_cmd->ril_cmd->data = kmalloc(kril_cmd->ril_cmd->datalen, GFP_KERNEL);
if(!kril_cmd->ril_cmd->data)
{
KRIL_DEBUG(DBG_ERROR,"Allocate kril_cmd->ril_cmd->data memory failed\n");
goto Out_ril_cmd;
}
memcpy(kril_cmd->ril_cmd->data, data, datalen);
}
mutex_lock(&gKrilCmdQueue.mutex);
list_add_tail(&kril_cmd->list, &gKrilCmdQueue.list);
mutex_unlock(&gKrilCmdQueue.mutex);
queue_work(gKrilCmdQueue.cmd_wq, &gKrilCmdQueue.commandq);
return 1;
Out_ril_cmd:
kfree(kril_cmd->ril_cmd);
Out:
kfree(kril_cmd);
return 0;
}
| 35.558074 | 180 | 0.608748 |
5538527a5f9997378c2268e6d8aef9ec3961205c | 4,150 | h | C | glx/glxTrackball.h | MAPSWorks/bigView--bigView-glx-Examples-latlon.C | 099071d483f7b3d056f41c15424b2e3e93ffb22e | [
"NASA-1.3"
] | null | null | null | glx/glxTrackball.h | MAPSWorks/bigView--bigView-glx-Examples-latlon.C | 099071d483f7b3d056f41c15424b2e3e93ffb22e | [
"NASA-1.3"
] | null | null | null | glx/glxTrackball.h | MAPSWorks/bigView--bigView-glx-Examples-latlon.C | 099071d483f7b3d056f41c15424b2e3e93ffb22e | [
"NASA-1.3"
] | null | null | null | //////////////////////////////////////////////////////////////////////////
///////////////////////////// glxTrackball.h /////////////////////////////
//////////////////////////////////////////////////////////////////////////
#ifndef GLX_TRACKBALL_H
#define GLX_TRACKBALL_H
#include "GLX.h"
#include "glxVector.h"
#include "glxQuat.h"
namespace Glx {
extern void trackball(Glx::Quat& q,float p1x,float p1y,float p2x,float p2y);
/**
* class Trackball
*
* A class to provide 3D view adjustments within a glx window.
* Left mouse controls rotation.
* Middle mouse controls scale [zooming].
* Right mouse controls screen space translation [panning].
* Left/right bracket keys '[' and ']' dec/inc translation sensitivity.
* Hitting 'r' resets the view.
*/
class Trackball {
public:
/**
* CTOR for class Glx::Trackpad
* Register mouse/key event callbacks with env.
* @param env parent class
*/
Trackball(glx* env);
/**
* manually build projection and modelview matrixes
*/
void applyXforms(void);
/**
* enable/disable all responses to mouse motions
*/
void enable(bool enabled){itsEnabledFlag=enabled;}
/**
* enable/disable translations
*/
void enableTranslation(bool enabled){itsEnabledTransFlag=enabled;}
/**
* reset the view
*/
void reset(void);
/**
* specify this position in a matrix of screens
*/
void setSector(int col, int row, int cols, int rows,
int hgap=0, int vgap=0)
{
itsCol=col;
itsRow=row;
itsCols=cols;
itsRows=rows;
itsHgap=hgap;
itsVgap=vgap;
}
/**
* enable/disable spinning
*/
void enableSpin(bool enabled){spinning=enabled;}
/**
* sets spin amount
*/
void setSpin(float radians, float axis[3]){
spinQuat.set(radians,axis);
spinQuat.normalize();
}
//protected:
void viewAll(const double*, const double*);
static void setProjection(glx*, void*);
static void startRotate(glx*, int, int, void*);
static void processRotate(glx*, int, int, void*);
static void startScale(glx*, int, int, void*);
static void processScale(glx*, int, int, void*);
static void startTranslate(glx*, int, int, void*);
static void processTranslate(glx*, int, int, void*);
static void processKey(glx*,XEvent *,void*);
static double getNear(void* usr){
Glx::Trackball* _this = static_cast<Glx::Trackball*>(usr);
return _this->itsNear;
}
static double getFar(void* usr){
Glx::Trackball* _this = static_cast<Glx::Trackball*>(usr);
return _this->itsFar;
}
static double getFOV(void* usr){
Glx::Trackball* _this = static_cast<Glx::Trackball*>(usr);
return _this->itsFOV;
}
static double getProjH(void* usr){
Glx::Trackball* _this = static_cast<Glx::Trackball*>(usr);
return _this->itsNear * tan( _this->itsFOV/2.0 );
}
static double getProjW(void* usr){
Glx::Trackball* _this = static_cast<Glx::Trackball*>(usr);
return _this->getProjH(usr) * _this->itsEnv->aspect();
}
void saveView(std::string);
void loadView(std::string);
void setOrtho(bool enabled){
ortho=enabled;
if(ortho)
itsScale=savescale;
else
itsScale=1.;
}
bool getOrtho(void){return ortho;}
public:
glx* itsEnv;
double itsXtrans;
double itsYtrans;
double itsZtrans;
Glx::Vector itsCenter;
double savex,savey,savez,savescale;
double startTranslateX,startTranslateY,startTranslateZ;
double startRotateX,startRotateY;
double itsSensitivity;
double MIN_SCALE;
double MAX_SCALE;
Glx::Quat worldQuat;
Glx::Quat saveQuat;
bool itsEnabledFlag;
bool itsEnabledTransFlag;
int itsRow;
int itsCol;
int itsRows;
int itsCols;
int itsHgap;
int itsVgap;
double itsNear;
double itsFar;
double itsScale;
double itsFOV;
bool spinning;
Glx::Quat spinQuat;
double proj[16];
double view[16];
double frustum[6]; // l,r,b,t,near,far
bool ortho;
};
} // namespace Glx
#endif
| 25.304878 | 78 | 0.608193 |
51ac31b385f85af05572bbc05af2b7d9fe9cc3da | 2,007 | h | C | DPlusPlusExample/Include/Bot.h | pKiwky/DPlusPlus | 0c9ef9567426056c6d65fd175f5e94ad559ee059 | [
"MIT"
] | null | null | null | DPlusPlusExample/Include/Bot.h | pKiwky/DPlusPlus | 0c9ef9567426056c6d65fd175f5e94ad559ee059 | [
"MIT"
] | null | null | null | DPlusPlusExample/Include/Bot.h | pKiwky/DPlusPlus | 0c9ef9567426056c6d65fd175f5e94ad559ee059 | [
"MIT"
] | 1 | 2021-06-05T17:35:27.000Z | 2021-06-05T17:35:27.000Z | #pragma once
#include <Discord/DiscordClient.h>
#include <Entities/Common/DiscordApplication.h>
#include <Entities/Member/DiscordUser.h>
#include <Entities/Member/DiscordMember.h>
#include <Entities/Message/DiscordMessage.h>
#include <Entities/Message/DiscordEmoji.h>
#include <Entities/Guild/DiscordGuild.h>
#include <Entities/Guild/DiscordRole.h>
#include <Entities/Channel/DiscordChannel.h>
#include <Entities/Channel/DiscordInvite.h>
class Bot: public DPlusPlus::DiscordClient {
public:
void OnHello(int32_t interval) override;
void OnHeartbeat(time_t timestamp) override;
void OnReady(std::unique_ptr<const DPlusPlus::ReadyEventArgs> args) override;
void OnMessageCreate(std::unique_ptr<const DPlusPlus::MessageCreateEventArgs> args) override;
void OnMessageUpdate(std::unique_ptr<const DPlusPlus::MessageUpdateEventArgs> args) override;
void OnMessageDelete(std::unique_ptr<const DPlusPlus::MessageDeleteEventArgs> args) override;
void OnMessageReactionAdd(std::unique_ptr<const DPlusPlus::MessageReactionAddEventArgs> args) override;
void OnGuildCreate(std::unique_ptr<const DPlusPlus::GuildCreateEventArgs> args) override;
void OnGuildUpdate(std::unique_ptr<const DPlusPlus::GuildUpdateEventArgs> args) override;
void OnGuildRoleCreate(std::unique_ptr<const DPlusPlus::GuildRoleCreateEventArgs> args) override;
void OnGuildRoleUpdate(std::unique_ptr<const DPlusPlus::GuildRoleUpdateEventArgs> args) override;
void OnGuildRoleDelete(std::unique_ptr<const DPlusPlus::GuildRoleDeleteEventArgs> args) override;
void OnChannelCreate(std::unique_ptr<const DPlusPlus::ChannelCreateEventArgs> args) override;
void OnChannelUpdate(std::unique_ptr<const DPlusPlus::ChannelUpdateEventArgs> args) override;
void OnChannelDelete(std::unique_ptr<const DPlusPlus::ChannelDeleteEventArgs> args) override;
void OnChannelPinUpdate(std::unique_ptr<const DPlusPlus::ChannelPinUpdateEventArgs> args) override;
void OnInviteCreate(std::unique_ptr<const DPlusPlus::InviteCreateEventArgs> args);
}; | 51.461538 | 104 | 0.829098 |
99fbfcf73babfced3f85f59cee732cde3ac6217d | 668 | h | C | include/Rindow/OpenCL/Kernel.h | yuichiis/rindow-opencl | 15fc15f6670a951f692a689378d980d77023f533 | [
"BSD-3-Clause"
] | 4 | 2021-08-08T14:50:23.000Z | 2022-02-06T20:27:22.000Z | include/Rindow/OpenCL/Kernel.h | yuichiis/rindow-opencl | 15fc15f6670a951f692a689378d980d77023f533 | [
"BSD-3-Clause"
] | null | null | null | include/Rindow/OpenCL/Kernel.h | yuichiis/rindow-opencl | 15fc15f6670a951f692a689378d980d77023f533 | [
"BSD-3-Clause"
] | 1 | 2021-08-11T20:00:25.000Z | 2021-08-11T20:00:25.000Z | #ifndef PHP_RINDOW_OPENCL_KERNEL_H
# define PHP_RINDOW_OPENCL_KERNEL_H
#define PHP_RINDOW_OPENCL_KERNEL_CLASSNAME "Rindow\\OpenCL\\Kernel"
#define PHP_RINDOW_OPENCL_KERNEL_SIGNATURE 0x6c4b4c4377646e52 // "RndwCLKl"
typedef struct {
zend_long signature;
cl_kernel kernel;
zend_object std;
} php_rindow_opencl_kernel_t;
static inline php_rindow_opencl_kernel_t* php_rindow_opencl_kernel_fetch_object(zend_object* obj)
{
return (php_rindow_opencl_kernel_t*) ((char*) obj - XtOffsetOf(php_rindow_opencl_kernel_t, std));
}
#define Z_RINDOW_OPENCL_KERNEL_OBJ_P(zv) (php_rindow_opencl_kernel_fetch_object(Z_OBJ_P(zv)))
#endif /* PHP_RINDOW_OPENCL_KERNEL_H */
| 35.157895 | 98 | 0.829341 |
ab09493c650a95b29fc3e49c7a56040ec98196b1 | 105 | h | C | src/projcl_spheroid.h | evanmiller/ProjCL | d5f06df59bb6814a1c2742eb5f4e9692390dbf1b | [
"MIT"
] | 50 | 2015-01-08T19:38:25.000Z | 2021-12-29T05:04:56.000Z | src/projcl_spheroid.h | evanmiller/ProjCL | d5f06df59bb6814a1c2742eb5f4e9692390dbf1b | [
"MIT"
] | 14 | 2015-04-09T19:25:03.000Z | 2020-09-04T15:58:31.000Z | src/projcl_spheroid.h | evanmiller/ProjCL | d5f06df59bb6814a1c2742eb5f4e9692390dbf1b | [
"MIT"
] | 8 | 2015-03-13T20:42:42.000Z | 2020-09-22T00:23:34.000Z |
int _pl_spheroid_is_spherical(PLSpheroid ell);
PLSpheroidInfo _pl_get_spheroid_info(PLSpheroid pl_ell);
| 26.25 | 56 | 0.87619 |
79c8ec21d3e6ba373642004c93776792ec6f187b | 13,777 | c | C | libraries/Sensor_APIs/Material_for_Future_Work/VL6160X_Vendor/example/Nucleo/Projects/Multi/Examples/VL6180X/CodeSamples/src/main.c | LimiFrog/LimiFrog-SW | c5e7e5b0a0b8bbb163f64debcc40224eb003f3af | [
"MIT"
] | 15 | 2015-12-07T14:47:43.000Z | 2018-10-24T08:41:06.000Z | libraries/Sensor_APIs/Material_for_Future_Work/VL6160X_Vendor/example/Nucleo/Projects/Multi/Examples/VL6180X/CodeSamples/src/main.c | LimiFrog/LimiFrog-SW | c5e7e5b0a0b8bbb163f64debcc40224eb003f3af | [
"MIT"
] | 2 | 2015-12-09T16:51:49.000Z | 2016-03-07T00:22:53.000Z | libraries/Sensor_APIs/Material_for_Future_Work/VL6160X_Vendor/example/Nucleo/Projects/Multi/Examples/VL6180X/CodeSamples/src/main.c | LimiFrog/LimiFrog-SW | c5e7e5b0a0b8bbb163f64debcc40224eb003f3af | [
"MIT"
] | 2 | 2018-12-01T23:37:45.000Z | 2021-02-19T05:36:12.000Z | /**
******************************************************************************
* File Name : main.c
* Date : 21/10/2014 09:21:14
* Description : Main program body
******************************************************************************
*
* COPYRIGHT(c) 2014 STMicroelectronics
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
#include "stm32xxx_hal.h"
I2C_HandleTypeDef hi2c1;
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "vl6180x_api.h"
#include "x-nucleo-6180xa1.h"
#ifdef DEBUG
#include "diag/trace.h"
#define debug(msg, ...) trace_printf(msg,__VA_ARGS__)
#define trace_warn(msg,...) trace_printf("W %s %d" msg "\n", __func__, __LINE__, __VA_ARGS__)
#else
#define debug(msg, ...) (void)0
#endif
#define DigitDisplay_ms 1 /* ms each digit is kept on */
#define PressBPSwicthTime 1000 /* if user keep bp press more that this mean swicth mode else rooll over use c&se in mode */
void WaitMilliSec(int ms);
/**
* VL6180x CubeMX F401 i2c porting implementation
*/
#define theVL6180xDev 0x52 // what we use as "API device
#define i2c_bus (&hi2c1)
#define def_i2c_time_out 100
#if VL6180x_SINGLE_DEVICE_DRIVER
int VL6180x_I2CWrite(VL6180xDev_t addr, uint8_t *buff, uint8_t len) {
int status;
status = HAL_I2C_Master_Transmit(i2c_bus, addr, buff, len, def_i2c_time_out);
if (status) {
XNUCLEO6180XA1_I2C1_Init(&hi2c1);
}
return status;
}
int VL6180x_I2CRead(VL6180xDev_t addr, uint8_t *buff, uint8_t len) {
int status;
status = HAL_I2C_Master_Receive(i2c_bus, addr, buff, len, def_i2c_time_out);
if (status) {
XNUCLEO6180XA1_I2C1_Init(&hi2c1);
}
return status;
}
#else
int VL6180x_I2CWrite(VL6180xDev_t dev, uint8_t *buff, uint8_t len) {
int status;
status = HAL_I2C_Master_Transmit(i2c_bus, dev->I2cAddr, buff, len, def_i2c_time_out);
if (status) {
XNUCLEO6180XA1_I2C1_Init(&hi2c1);
}
return status;
}
int VL6180x_I2CRead(VL6180xDev_t dev, uint8_t *buff, uint8_t len) {
int status;
status = HAL_I2C_Master_Receive(i2c_bus, dev->I2cAddr, buff, len, def_i2c_time_out);
if (status) {
XNUCLEO6180XA1_I2C1_Init(&hi2c1);
}
return status;
}
#endif
/**
* platform and application specific for VL6180x_Shield
*/
void XNUCLEO6180XA1_WaitMilliSec(int n) {
WaitMilliSec(n);
}
volatile int IntrFired = 0;
void XNUCLEO6180XA1_UserIntHandler(void) {
IntrFired++;
}
/**
* DISPLAY public
*/
/*************** DISPLAY PUBLIC *********************/
const char *DISP_NextString;
/*************** DISPLAY PRIVATE *********************/
static char DISP_CurString[10];
static int DISP_Loop = 0;
uint32_t TimeStarted; /* various display and mode delay starting time */
void DISP_ExecLoopBody(void) {
if (DISP_NextString != NULL) {
strncpy(DISP_CurString, DISP_NextString, sizeof(DISP_CurString) - 1);
DISP_CurString[sizeof(DISP_CurString) - 1] = 0;
DISP_NextString = NULL;
}
XNUCLEO6180XA1_DisplayString(DISP_CurString, DigitDisplay_ms);
DISP_Loop++;
}
/**
* Nucleo board specific
*
*/
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
XNUCLEO6180XA1_EXTI_CallBackHandle(GPIO_Pin);
}
volatile uint32_t g_TickCnt;
void HAL_SYSTICK_Callback(void){
g_TickCnt++;
}
#define BSP_BP_PORT GPIOC
#define BSP_BP_PIN GPIO_PIN_13
int BSP_GetPushButton(void) {
GPIO_PinState state;
state = HAL_GPIO_ReadPin(BSP_BP_PORT, BSP_BP_PIN);
return state;
}
void SetDisplayString(const char *msg) {
DISP_NextString = msg;
}
void WaitMilliSec(int ms) {
HAL_Delay(ms); /* it's milli sec cos we do set systick to 1KHz */
}
/**
* call in the main loop
* when running under debugger it enable doing direct vl6180x reg access
* After breaking at entrance
* change the the local index/data and cmd variable to do what needed
* reg_cmd -1 wr byte -2wr word -3 wr dword
* reg_cmd 1 rd byte 2 rd word 3 rd dword
* step to last statement before return and read variable to get rd result exit
*/
void debug_stuff(void) {
int reg_cmd = 0;
static uint32_t reg_data;
static uint16_t reg_index;
if (reg_cmd) {
switch (reg_cmd) {
case -1:
VL6180x_WrByte(theVL6180xDev, reg_index, reg_data);
debug("Wr B 0x%X = %d", reg_index, (int)reg_data);
break;
case -2:
VL6180x_WrWord(theVL6180xDev, reg_index, reg_data);
debug("Wr W 0x%X = %d", reg_index, (int) reg_data);
break;
case -3:
VL6180x_WrDWord(theVL6180xDev, reg_index, reg_data);
debug("WrDW 0x%X = %d", reg_index, (int)reg_data);
break;
case 1:
reg_data = 0;
VL6180x_RdByte(theVL6180xDev, reg_index, (uint8_t*) ®_data);
debug("RD B 0x%X = %d", reg_index, (int)reg_data);
break;
case 2:
reg_data = 0;
VL6180x_RdWord(theVL6180xDev, reg_index, (uint16_t*) ®_data);
debug("RD W 0x%X = %d", reg_index, (int)reg_data);
break;
case 3:
VL6180x_RdDWord(theVL6180xDev, reg_index, ®_data);
debug("RD DW 0x%X = %d", reg_index, (int)reg_data);
break;
default:
debug("Invalid command %d", reg_cmd);
/* nothing to do*/
;
}
}
}
/**
* When button is already pressed it Wait for user to release it
* if button remain pressed for given time it return true
* These is used to detect mode switch by long press on blue Push Button
*
* As soon as time is elapsed -rb- is displayed to let user know order
* the request to switch mode is taken into account
*
* @return True if button remain pressed more than specified time
*/
int PusbButton_WaitUnPress(void) {
uint32_t TimeStarted = HAL_GetTick();
uint32_t tick;
while (!BSP_GetPushButton()) {
; /* debounce */
DISP_ExecLoopBody();
tick = HAL_GetTick();
if (-TimeStarted > PressBPSwicthTime) {
SetDisplayString(" rb ");
}
}
return tick - TimeStarted > PressBPSwicthTime;
}
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
void Sample_FreeRunningRanging(void);
void Sample_SimpleRanging(void);
void Sample_SimpleAls(void);
uint8_t Sample_OffsetCalibrate(void);
void Sample_XTalkCalibrate(int initDevice);
void Sample_AlternateRangeAls(void);
void Sample_Interrupt(void);
int main(void) {
uint8_t offset;
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* System interrupt init*/
/* Sets the priority grouping field */
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_0);
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_I2C1_Init();
/* these almost just redo what already done just above by CubeMx Init */
XNUCLEO6180XA1_GPIO_Init();
XNUCLEO6180XA1_I2C1_Init(&hi2c1);
/* SysTick end of count event each 1ms */
SysTick_Config(HAL_RCC_GetHCLKFreq() / 1000);
while (1) {
Sample_SimpleRanging();
Sample_FreeRunningRanging();
Sample_SimpleAls();
Sample_AlternateRangeAls();
offset = Sample_OffsetCalibrate();
Sample_XTalkCalibrate(offset);
Sample_Interrupt();
}
/* USER CODE END 3 */
}
/** System Clock Configuration
*/
void SystemClock_Config(void) {
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_OscInitTypeDef RCC_OscInitStruct;
__PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = 6;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 16;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
RCC_OscInitStruct.PLL.PLLQ = 7;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2);
}
/* I2C1 init function */
void MX_I2C1_Init(void) {
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 400000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLED;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLED;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLED;
HAL_I2C_Init(&hi2c1);
}
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
void MX_GPIO_Init(void) {
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
__GPIOC_CLK_ENABLE();
__GPIOH_CLK_ENABLE();
__GPIOA_CLK_ENABLE();
__GPIOB_CLK_ENABLE();
/*Configure GPIO pin : PC13 */
GPIO_InitStruct.Pin = GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pins : PA0 PA1 PA4 PA5
PA8 PA9 */
GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_8 | GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PA2 PA3 */
GPIO_InitStruct.Pin = GPIO_PIN_2 | GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
GPIO_InitStruct.Alternate = GPIO_AF7_USART2;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PA6 PA7 */
GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PB0 PB10 PB4 PB5
PB6 */
GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_10 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : PC7 */
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* USER CODE BEGIN 6 */
trace_printf("assert_param() failed: file \"%s\", line %d\n", file, line);
exit(1);
/* USER CODE END 6 */
}
#endif
| 31.454338 | 126 | 0.65065 |
edf35388d3f5c0427c8b948606e134880d8bad0f | 9,296 | h | C | defaultdol/include/gc/revolution/os/OSContext.h | knight-ryu12/StarFoxAdventures | 83648dabda9777d7de5da1bf9b83ddb82d7dd2a0 | [
"MIT"
] | 22 | 2019-11-29T21:20:59.000Z | 2022-01-25T06:39:02.000Z | defaultdol/include/gc/revolution/os/OSContext.h | knight-ryu12/StarFoxAdventures | 83648dabda9777d7de5da1bf9b83ddb82d7dd2a0 | [
"MIT"
] | 7 | 2021-01-26T11:57:25.000Z | 2022-02-07T11:00:06.000Z | defaultdol/include/gc/revolution/os/OSContext.h | knight-ryu12/StarFoxAdventures | 83648dabda9777d7de5da1bf9b83ddb82d7dd2a0 | [
"MIT"
] | 3 | 2021-01-03T23:47:37.000Z | 2021-08-06T09:02:11.000Z | /*---------------------------------------------------------------------------*
Project: Dolphin OS Context API
File: OSContext.h
Copyright 1998-2001 Nintendo. All rights reserved.
These coded instructions, statements, and computer programs contain
proprietary information of Nintendo of America Inc. and/or Nintendo
Company Ltd., and are protected by Federal copyright law. They may
not be disclosed to third parties or copied or duplicated in any form,
in whole or in part, without the prior written consent of Nintendo.
$Log: OSContext.h,v $
Revision 1.3 2006/08/23 10:40:51 kawaset
Added OSSwitchFiberEx().
Revision 1.2 2006/02/04 11:56:47 hashida
(none)
Revision 1.1.1.1 2005/12/29 06:53:28 hiratsu
Initial import.
Revision 1.1.1.1 2005/05/12 02:41:07 yasuh-to
Ported from dolphin source tree.
10 2002/08/12 15:17 Shiki
Added psf_pad field to OSContext{}.
9 2001/03/16 16:16 Shiki
Clean up.
8 2000/08/23 6:40p Shiki
Added OSGetStackPointer().
7 2000/07/20 7:52p Shiki
Added OSSwitchStack() and OSSwitchFiber().
6 2000/02/22 3:10p Tian
Removed ifdef GEKKO. Full gekko context structure is always used.
5 2000/01/17 6:23p Shiki
Replaced OSContext.fpSaved with .state for future thread support.
4 2000/01/14 2:31p Tian
Fixed bugs in the #defines for the Gekko registers.
3 1999/11/29 5:51p Tian
Added PSF defines, and increased size of context frame for Gekko
2 1999/11/29 2:22p Tian
Added Gekko GQRs (graphics quantization registers). Will need to
update frame size if we really need extra FPR array for save/restore of
paired singles.
8 1999/08/03 4:13p Shiki
Removed #ifdef _DEBUG for OSDumpContext().
7 1999/08/03 3:54p Shiki
Removed dsisr and dar from OSContext.
6 1999/07/16 3:17p Shiki
Removed the definition of OS_CONTEXT_MODE_MORIBUND.
5 1999/07/13 9:37p Shiki
Added fpscr_pad member in OSContext so that FPSCR register can be
saved/restored properly.
4 1999/07/12 10:01p Shiki
Added OSFillFPUContext().
3 1999/05/11 4:43p Shiki
Refreshed include tree.
1 1999/04/30 12:49p Tianli01
7 1999/04/21 8:06p Shiki
Moved to _DEBUG (avoid DEBUG)
6 1999/04/13 5:49p Tianli01
Fixed FPU saving/loading APIs to conform to spec.
5 1999/04/06 2:58p Tianli01
Added FPU state saving constants and routines. Note that FPU saving
API is not yet to spec.
4 1999/04/02 5:29p Tianli01
Changed OSContext to use array. Added DumpNVRegisters.
3 1999/04/01 7:53p Tianli01
Added floating point saved bit in OSContext
2 1999/03/31 6:09p Tianli01
Fixed bugs in field offsets. Added PPC APIs and OSDumpContext for
exceptions.
1 1999/03/26 2:08p Tianli01
Broken up from previous OS.h.
$NoKeywords: $
*---------------------------------------------------------------------------*/
#ifndef __OSCONTEXT_H__
#define __OSCONTEXT_H__
#include <revolution/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/*---------------------------------------------------------------------------*
Context API
*---------------------------------------------------------------------------*/
// Floating point context modes
#define OS_CONTEXT_MODE_FPU 0x01u
#define OS_CONTEXT_MODE_PSFP 0x02u
// Context status
#define OS_CONTEXT_STATE_FPSAVED 0x01u // set if FPU is saved
#define OS_CONTEXT_STATE_EXC 0x02u // set if saved by exception
typedef struct OSContext
{
// General-purpose registers
u32 gpr[32];
u32 cr;
u32 lr;
u32 ctr;
u32 xer;
// Floating-point registers
f64 fpr[32];
u32 fpscr_pad;
u32 fpscr;
// Exception handling registers
u32 srr0;
u32 srr1;
// Context mode
u16 mode; // since UIMM is 16 bits in PPC
u16 state; // OR-ed OS_CONTEXT_STATE_*
// Place Gekko regs at the end so we have minimal changes to
// existing code
u32 gqr[8];
u32 psf_pad;
f64 psf[32];
} OSContext;
// Size of context frame on stack.
// This constant should reflect a large enough number to hold
// an entire context and padding for the stack frame header.
#define __OS_CONTEXT_FRAME 768
#define OS_CONTEXT_R0 0
#define OS_CONTEXT_R1 4
#define OS_CONTEXT_R2 8
#define OS_CONTEXT_R3 12
#define OS_CONTEXT_R4 16
#define OS_CONTEXT_R5 20
#define OS_CONTEXT_R6 24
#define OS_CONTEXT_R7 28
#define OS_CONTEXT_R8 32
#define OS_CONTEXT_R9 36
#define OS_CONTEXT_R10 40
#define OS_CONTEXT_R11 44
#define OS_CONTEXT_R12 48
#define OS_CONTEXT_R13 52
#define OS_CONTEXT_R14 56
#define OS_CONTEXT_R15 60
#define OS_CONTEXT_R16 64
#define OS_CONTEXT_R17 68
#define OS_CONTEXT_R18 72
#define OS_CONTEXT_R19 76
#define OS_CONTEXT_R20 80
#define OS_CONTEXT_R21 84
#define OS_CONTEXT_R22 88
#define OS_CONTEXT_R23 92
#define OS_CONTEXT_R24 96
#define OS_CONTEXT_R25 100
#define OS_CONTEXT_R26 104
#define OS_CONTEXT_R27 108
#define OS_CONTEXT_R28 112
#define OS_CONTEXT_R29 116
#define OS_CONTEXT_R30 120
#define OS_CONTEXT_R31 124
#define OS_CONTEXT_CR 128
#define OS_CONTEXT_LR 132
#define OS_CONTEXT_CTR 136
#define OS_CONTEXT_XER 140
#define OS_CONTEXT_FPR0 144
#define OS_CONTEXT_FPR1 152
#define OS_CONTEXT_FPR2 160
#define OS_CONTEXT_FPR3 168
#define OS_CONTEXT_FPR4 176
#define OS_CONTEXT_FPR5 184
#define OS_CONTEXT_FPR6 192
#define OS_CONTEXT_FPR7 200
#define OS_CONTEXT_FPR8 208
#define OS_CONTEXT_FPR9 216
#define OS_CONTEXT_FPR10 224
#define OS_CONTEXT_FPR11 232
#define OS_CONTEXT_FPR12 240
#define OS_CONTEXT_FPR13 248
#define OS_CONTEXT_FPR14 256
#define OS_CONTEXT_FPR15 264
#define OS_CONTEXT_FPR16 272
#define OS_CONTEXT_FPR17 280
#define OS_CONTEXT_FPR18 288
#define OS_CONTEXT_FPR19 296
#define OS_CONTEXT_FPR20 304
#define OS_CONTEXT_FPR21 312
#define OS_CONTEXT_FPR22 320
#define OS_CONTEXT_FPR23 328
#define OS_CONTEXT_FPR24 336
#define OS_CONTEXT_FPR25 344
#define OS_CONTEXT_FPR26 352
#define OS_CONTEXT_FPR27 360
#define OS_CONTEXT_FPR28 368
#define OS_CONTEXT_FPR29 376
#define OS_CONTEXT_FPR30 384
#define OS_CONTEXT_FPR31 392
#define OS_CONTEXT_FPSCR 400 // 8 bytes including padding
#define OS_CONTEXT_SRR0 408
#define OS_CONTEXT_SRR1 412
#define OS_CONTEXT_MODE 416 // only 2 bytes
#define OS_CONTEXT_STATE 418 // only 2 bytes
#define OS_CONTEXT_GQR0 420
#define OS_CONTEXT_GQR1 424
#define OS_CONTEXT_GQR2 428
#define OS_CONTEXT_GQR3 432
#define OS_CONTEXT_GQR4 436
#define OS_CONTEXT_GQR5 440
#define OS_CONTEXT_GQR6 444
#define OS_CONTEXT_GQR7 448
#define __OSCONTEXT_PADDING 452 // double word alignment for the 64 bit psf
#define OS_CONTEXT_PSF0 456
#define OS_CONTEXT_PSF1 464
#define OS_CONTEXT_PSF2 472
#define OS_CONTEXT_PSF3 480
#define OS_CONTEXT_PSF4 488
#define OS_CONTEXT_PSF5 496
#define OS_CONTEXT_PSF6 504
#define OS_CONTEXT_PSF7 512
#define OS_CONTEXT_PSF8 520
#define OS_CONTEXT_PSF9 528
#define OS_CONTEXT_PSF10 536
#define OS_CONTEXT_PSF11 544
#define OS_CONTEXT_PSF12 552
#define OS_CONTEXT_PSF13 560
#define OS_CONTEXT_PSF14 568
#define OS_CONTEXT_PSF15 576
#define OS_CONTEXT_PSF16 584
#define OS_CONTEXT_PSF17 592
#define OS_CONTEXT_PSF18 600
#define OS_CONTEXT_PSF19 608
#define OS_CONTEXT_PSF20 616
#define OS_CONTEXT_PSF21 624
#define OS_CONTEXT_PSF22 632
#define OS_CONTEXT_PSF23 640
#define OS_CONTEXT_PSF24 648
#define OS_CONTEXT_PSF25 656
#define OS_CONTEXT_PSF26 664
#define OS_CONTEXT_PSF27 672
#define OS_CONTEXT_PSF28 680
#define OS_CONTEXT_PSF29 688
#define OS_CONTEXT_PSF30 696
#define OS_CONTEXT_PSF31 704
u32 OSGetStackPointer ( void );
u32 OSSwitchStack ( u32 newsp );
int OSSwitchFiber ( u32 pc, u32 newsp );
int OSSwitchFiberEx ( u32 arg0, u32 arg1, u32 arg2, u32 arg3, u32 pc, u32 newsp );
void OSSetCurrentContext ( OSContext* context );
OSContext* OSGetCurrentContext ( void );
u32 OSSaveContext ( OSContext* context );
void OSLoadContext ( OSContext* context );
void OSClearContext ( OSContext* context );
void OSInitContext ( OSContext* context, u32 pc, u32 sp );
void OSLoadFPUContext ( OSContext* context );
void OSSaveFPUContext ( OSContext* context );
void OSFillFPUContext ( OSContext* context );
void OSDumpContext ( OSContext* context );
#ifdef __cplusplus
}
#endif
#endif // __OSCONTEXT_H__
| 30.28013 | 95 | 0.651571 |
056a8eb5c0adfbd0ffb4b05db17d2b42fca7b942 | 4,911 | c | C | asp3/tecsgen/tecs/TECSInfo/nTECSInfo_tCellInfo.c | robotan0921/mruby_on_tinet-tecs | f5dcb3955de4c9a863a1f3776911497bb4e16091 | [
"MIT"
] | 1 | 2018-04-03T08:52:05.000Z | 2018-04-03T08:52:05.000Z | asp3/tecsgen/tecs/TECSInfo/nTECSInfo_tCellInfo.c | robotan0921/mruby_on_tinet-tecs | f5dcb3955de4c9a863a1f3776911497bb4e16091 | [
"MIT"
] | null | null | null | asp3/tecsgen/tecs/TECSInfo/nTECSInfo_tCellInfo.c | robotan0921/mruby_on_tinet-tecs | f5dcb3955de4c9a863a1f3776911497bb4e16091 | [
"MIT"
] | 1 | 2018-04-16T07:17:55.000Z | 2018-04-16T07:17:55.000Z | /*
* Copyright (C) 2008-2017 by TOPPERS Project
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* @(#) $Id: nTECSInfo_tCellInfo.c 2640 2017-06-03 11:27:12Z okuma-top $
*/
/* #[<PREAMBLE>]#
* #[<...>]# から #[</...>]# で囲まれたコメントは編集しないでください
* tecsmerge によるマージに使用されます
*
* 属性アクセスマクロ #_CAAM_#
* name char_t* ATTR_name
* cbp void* ATTR_cbp
* inibp void* ATTR_inibp
*
* 呼び口関数 #_TCPF_#
* call port: cCelltypeInfo signature: nTECSInfo_sCelltypeInfo context:task
* ER cCelltypeInfo_getName( char_t* name, int_t max_len );
* void cCelltypeInfo_getNameLength( uint16_t* len );
* void cCelltypeInfo_getNAttr( int32_t* nAttr );
* void cCelltypeInfo_getAttrInfo( int32_t ith, Descriptor( nTECSInfo_sAttrVarInfo )* desc );
* void cCelltypeInfo_getNVar( int32_t* nVar );
* void cCelltypeInfo_getVarInfo( int32_t ith, Descriptor( nTECSInfo_sAttrVarInfo )* desc );
* void cCelltypeInfo_getNCall( int32_t* nCall );
* void cCelltypeInfo_getCallInfo( int32_t ith, Descriptor( nTECSInfo_sCallInfo )* desc );
* void cCelltypeInfo_getNEntry( int32_t* nEntry );
* void cCelltypeInfo_getEntryInfo( int32_t ith, Descriptor( nTECSInfo_sEntryInfo )* desc );
* bool_t cCelltypeInfo_isSingleton( );
* bool_t cCelltypeInfo_isIDX_is_ID( );
* bool_t cCelltypeInfo_hasCB( );
* bool_t cCelltypeInfo_hasINIB( );
* [ref_desc]
* Descriptor( nTECSInfo_sCelltypeInfo ) cCelltypeInfo_refer_to_descriptor();
* Descriptor( nTECSInfo_sCelltypeInfo ) cCelltypeInfo_ref_desc() (same as above; abbreviated version);
*
* #[</PREAMBLE>]# */
/* Put prototype declaration and/or variale definition here #_PAC_# */
#include "nTECSInfo_tCellInfo_tecsgen.h"
#ifndef E_OK
#define E_OK 0 /* success */
#define E_ID (-18) /* illegal ID */
#endif
/* entry port function #_TEPF_# */
/* #[<ENTRY_PORT>]# eCellInfo
* entry port: eCellInfo
* signature: nTECSInfo_sCellInfo
* context: task
* #[</ENTRY_PORT>]# */
/* #[<ENTRY_FUNC>]# eCellInfo_getName
* name: eCellInfo_getName
* global_name: nTECSInfo_tCellInfo_eCellInfo_getName
* oneway: false
* #[</ENTRY_FUNC>]# */
ER
eCellInfo_getName(CELLIDX idx, char_t* name, int_t max_len)
{
ER ercd = E_OK;
CELLCB *p_cellcb;
if (VALID_IDX(idx)) {
p_cellcb = GET_CELLCB(idx);
}
else {
return(E_ID);
} /* end if VALID_IDX(idx) */
/* Put statements here #_TEFB_# */
return(ercd);
}
/* #[<ENTRY_FUNC>]# eCellInfo_getCelltypeInfo
* name: eCellInfo_getCelltypeInfo
* global_name: nTECSInfo_tCellInfo_eCellInfo_getCelltypeInfo
* oneway: false
* #[</ENTRY_FUNC>]# */
void
eCellInfo_getCelltypeInfo(CELLIDX idx, Descriptor( nTECSInfo_sCelltypeInfo )* desc)
{
CELLCB *p_cellcb;
if (VALID_IDX(idx)) {
p_cellcb = GET_CELLCB(idx);
}
else {
/* Write error processing code here */
} /* end if VALID_IDX(idx) */
/* Put statements here #_TEFB_# */
}
/* #[<ENTRY_FUNC>]# eCellInfo_getCBP
* name: eCellInfo_getCBP
* global_name: nTECSInfo_tCellInfo_eCellInfo_getCBP
* oneway: false
* #[</ENTRY_FUNC>]# */
void
eCellInfo_getCBP(CELLIDX idx, void** cbp)
{
CELLCB *p_cellcb;
if (VALID_IDX(idx)) {
p_cellcb = GET_CELLCB(idx);
}
else {
/* Write error processing code here */
} /* end if VALID_IDX(idx) */
/* Put statements here #_TEFB_# */
}
/* #[<ENTRY_FUNC>]# eCellInfo_getINIBP
* name: eCellInfo_getINIBP
* global_name: nTECSInfo_tCellInfo_eCellInfo_getINIBP
* oneway: false
* #[</ENTRY_FUNC>]# */
void
eCellInfo_getINIBP(CELLIDX idx, void** inibp)
{
CELLCB *p_cellcb;
if (VALID_IDX(idx)) {
p_cellcb = GET_CELLCB(idx);
}
else {
/* Write error processing code here */
} /* end if VALID_IDX(idx) */
/* Put statements here #_TEFB_# */
}
/* #[<POSTAMBLE>]#
* これより下に非受け口関数を書きます
* #[</POSTAMBLE>]#*/
| 29.407186 | 113 | 0.660354 |
01f647f4d7b649d5df498b862f6bf9894ad54984 | 1,459 | c | C | src/shell/sub_system/env/environment.c | TomWeimer/Minishell | 65aae63ec77e4e7b5fdbd1d94e00fea20868e016 | [
"MIT"
] | null | null | null | src/shell/sub_system/env/environment.c | TomWeimer/Minishell | 65aae63ec77e4e7b5fdbd1d94e00fea20868e016 | [
"MIT"
] | null | null | null | src/shell/sub_system/env/environment.c | TomWeimer/Minishell | 65aae63ec77e4e7b5fdbd1d94e00fea20868e016 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* environment.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tchappui <tchappui@student.42lausanne.c +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/19 18:19:00 by tchappui #+# #+# */
/* Updated: 2022/06/13 14:57:42 by tchappui ### ########.fr */
/* */
/* ************************************************************************** */
#include "environment/env.h"
#include "minishell.h"
void ft_env(t_list **env, char **envp)
{
int i;
i = 0;
while (envp[i] != 0)
{
ft_lstadd_back(env, ft_lstnew(envp[i]));
i++;
}
}
void printenv(t_list *lst)
{
while (lst != NULL)
{
write(1, lst->content, ft_strlen(lst->content));
write(1, "\n", 1);
lst = lst->next;
}
g_data.exit_status = 0;
}
void clean_env(t_list *lst)
{
t_list *actual;
t_list *to_delete;
to_delete = NULL;
actual = lst;
while (actual != NULL)
{
to_delete = actual;
actual = actual->next;
free(to_delete);
}
}
| 27.528302 | 80 | 0.31597 |
c9d548951dc0fc2daf0f66889824786e58740a8c | 55,471 | c | C | standard-deviation-algo/memory.c | LDonoughe/Agent-Signalling | 2ebf855b12b6abfbf6790c6e46fdee0614f38d00 | [
"MIT"
] | null | null | null | standard-deviation-algo/memory.c | LDonoughe/Agent-Signalling | 2ebf855b12b6abfbf6790c6e46fdee0614f38d00 | [
"MIT"
] | null | null | null | standard-deviation-algo/memory.c | LDonoughe/Agent-Signalling | 2ebf855b12b6abfbf6790c6e46fdee0614f38d00 | [
"MIT"
] | null | null | null | /**
* \file memory.c
* \brief Holds memory functions.
*/
#include "header.h"
void unittest_b_receive_messages_01_end()
{
int rc;
rc = MB_Iterator_CreateFiltered(b_PurchaseQuality, &i_PurchaseQuality, &FLAME_filter_buyer_b_receive_messages_01_end_PurchaseQuality, current_xmachine_buyer);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not create Iterator for 'PurchaseQuality'\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'PurchaseQuality' board is invalid\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'PurchaseQuality' board is locked\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
}
}
#endif
//return b_receive_messages();
}
void unittest_b_send_message_start_01()
{
//return b_send_message();
}
void unittest_f_send_message_02_03()
{
//return f_send_message();
}
void unittest_f_idle_start_01()
{
//return f_idle();
}
void unittest_f_receive_messages_01_02()
{
int rc;
rc = MB_Iterator_CreateFiltered(b_Purchase, &i_Purchase, &FLAME_filter_firm_f_receive_messages_01_02_Purchase, current_xmachine_firm);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not create Iterator for 'Purchase'\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'Purchase' board is invalid\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'Purchase' board is locked\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
}
}
#endif
//return f_receive_messages();
}
void unittest_f_receive_strategy_03_end()
{
int rc;
rc = MB_Iterator_CreateFiltered(b_StrategyAdjustment, &i_StrategyAdjustment, &FLAME_filter_firm_f_receive_strategy_03_end_StrategyAdjustment, current_xmachine_firm);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not create Iterator for 'StrategyAdjustment'\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'StrategyAdjustment' board is invalid\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'StrategyAdjustment' board is locked\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
}
}
#endif
//return f_receive_strategy();
}
void unittest_o_receive_messages_start_01()
{
int rc;
rc = MB_Iterator_Create(b_PurchaseQuality, &i_PurchaseQuality);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not create Iterator for 'PurchaseQuality'\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'PurchaseQuality' board is invalid\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'PurchaseQuality' board is locked\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
}
}
#endif
//return o_receive_messages();
}
void unittest_o_send_message_01_end()
{
//return o_send_message();
}
void unittest_o_idle_01_end()
{
//return o_idle();
}
void free_messages()
{
int rc;
rc = MB_Clear(b_PurchaseQuality);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not clear 'PurchaseQuality' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'PurchaseQuality' board is invalid\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'PurchaseQuality' board is locked\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Clear returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
rc = MB_Clear(b_Purchase);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not clear 'Purchase' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'Purchase' board is invalid\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'Purchase' board is locked\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Clear returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
rc = MB_Clear(b_StrategyAdjustment);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not clear 'StrategyAdjustment' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'StrategyAdjustment' board is invalid\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'StrategyAdjustment' board is locked\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Clear returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
}
/** \fn void initialise_pointers()
* \brief Initialises pointers to xmachine, message, and node lists.
*/
void initialise_pointers()
{
int rc;
/* Initialise message sync composite params as NULL */
FLAME_m_PurchaseQuality_composite_params = NULL;
rc = MB_Create(&b_PurchaseQuality, sizeof(m_PurchaseQuality));
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not create 'PurchaseQuality' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: Invalid message size\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Create returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
/* Initialise message sync composite params as NULL */
FLAME_m_Purchase_composite_params = NULL;
rc = MB_Create(&b_Purchase, sizeof(m_Purchase));
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not create 'Purchase' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: Invalid message size\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Create returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
/* Initialise message sync composite params as NULL */
FLAME_m_StrategyAdjustment_composite_params = NULL;
rc = MB_Create(&b_StrategyAdjustment, sizeof(m_StrategyAdjustment));
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not create 'StrategyAdjustment' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: Invalid message size\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Create returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
buyer_start_state = init_buyer_state();
buyer_end_state = init_buyer_state();
buyer_01_state = init_buyer_state();
firm_end_state = init_firm_state();
firm_01_state = init_firm_state();
firm_start_state = init_firm_state();
firm_03_state = init_firm_state();
firm_02_state = init_firm_state();
overseer_end_state = init_overseer_state();
overseer_01_state = init_overseer_state();
overseer_start_state = init_overseer_state();
temp_node_info = NULL;
p_node_info = &temp_node_info;
}
/** \fn void initialise_unit_testing()
* \brief Initialises framework for unit testing.
*/
void initialise_unit_testing()
{
int rc;
rc = MB_Env_Init();
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Failed to initialise Message Board environment\n");
switch(rc) {
case MB_ERR_MPI:
fprintf(stderr, "\t reason: MPI library not initialised\n");
break;
case MB_ERR_MEMALLOC:
fprintf(stderr, "\t reason: out of memory\n");
break;
default:
fprintf(stderr, "\t MB_Env_Init returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
initialise_pointers();
}
FLAME_output * add_FLAME_output(FLAME_output ** outputs)
{
FLAME_output * current;
current = (FLAME_output *)malloc(sizeof(FLAME_output));
CHECK_POINTER(current);
current->next = *outputs;
*outputs = current;
current->type = -1;
current->format = -1;
current->location = NULL;
current->period = -1;
current->phase = -1;
current->flag = 0;
return current;
}
void free_FLAME_outputs(FLAME_output ** outputs)
{
FLAME_output * current, * next;
current = *outputs;
while(current)
{
next = current->next;
free(current->location);
free(current);
current = next;
}
*outputs = NULL;
}
/* add_location */
/** \fn void add_location(double point, location ** p_location)
* \brief Adds a location in order into the location list.
* \param point Position of an agent.
* \param p_location Pointer Pointer to the location list.
*/
void add_location(double point, location ** p_location)
{
location * current = *p_location;
location * tmp = NULL;
location * newlocation = NULL;
int found = 0;
while(found == 0)
{
if(current == NULL) found = 1;
else if(point > current->point) found = 1;
else
{
tmp = current;
current = current->next;
}
}
newlocation = (location *)malloc(sizeof(location));
CHECK_POINTER(newlocation);
if(tmp)
{
tmp->next = newlocation;
}
else
{
*p_location = newlocation;
}
newlocation->next = current;
newlocation->point = point;
}
/* freelocations */
/** \fn void freelocations(location ** p_location)
* \brief Free locations from the location list.
* \param p_location Pointer Pointer to the location list.
*/
void freelocations(location ** p_location)
{
location * head = *p_location;
location * tmp = NULL;
while(head)
{
tmp = head->next;
free(head);
head = tmp;
}
*p_location = NULL;
}
void init_int_static_array(/*@out@*/ int * array, int size)
{
int i;
for(i = 0; i < size; i++) array[i] = 0;
}
void init_float_static_array(/*@out@*/ float * array, int size)
{
int i;
for(i = 0; i < size; i++) array[i] = 0.0;
}
void init_double_static_array(/*@out@*/ double* array, int size)
{
int i;
for(i = 0; i < size; i++) array[i] = 0.0;
}
void init_char_static_array(/*@out@*/ char * array, int size)
{
int i;
for(i = 0; i < size; i++) array[i] = '\0';
}
xmachine_memory_buyer_state * init_buyer_state()
{
xmachine_memory_buyer_state * current = (xmachine_memory_buyer_state *)malloc(sizeof(xmachine_memory_buyer_state));
CHECK_POINTER(current);
current->agents = NULL;
current->count = 0;
return current;
}
xmachine_memory_buyer * init_buyer_agent()
{
xmachine_memory_buyer * current = (xmachine_memory_buyer *)malloc(sizeof(xmachine_memory_buyer));
CHECK_POINTER(current);
current->my_id = 0;
current->firm_id = 0;
current->my_qual = 0;
return current;
}
void free_buyer_agent(xmachine_memory_buyer_holder * tmp, xmachine_memory_buyer_state * state)
{
if(tmp->prev == NULL) state->agents = tmp->next;
else tmp->prev->next = tmp->next;
if(tmp->next != NULL) tmp->next->prev = tmp->prev;
free(tmp->agent);
free(tmp);
}
void unittest_init_buyer_agent()
{
current_xmachine_buyer = (xmachine_memory_buyer *)malloc(sizeof(xmachine_memory_buyer));
CHECK_POINTER(current);
current_xmachine_buyer->my_id = 0;
current_xmachine_buyer->firm_id = 0;
current_xmachine_buyer->my_qual = 0;
}
void unittest_free_buyer_agent()
{
free(current_xmachine_buyer);
}
void free_buyer_agents()
{
current_xmachine_buyer_holder = buyer_start_state->agents;
while(current_xmachine_buyer_holder)
{
temp_xmachine_buyer_holder = current_xmachine_buyer_holder->next;
free_buyer_agent(current_xmachine_buyer_holder, buyer_start_state);
current_xmachine_buyer_holder = temp_xmachine_buyer_holder;
}
buyer_start_state->count = 0;
current_xmachine_buyer_holder = buyer_end_state->agents;
while(current_xmachine_buyer_holder)
{
temp_xmachine_buyer_holder = current_xmachine_buyer_holder->next;
free_buyer_agent(current_xmachine_buyer_holder, buyer_end_state);
current_xmachine_buyer_holder = temp_xmachine_buyer_holder;
}
buyer_end_state->count = 0;
current_xmachine_buyer_holder = buyer_01_state->agents;
while(current_xmachine_buyer_holder)
{
temp_xmachine_buyer_holder = current_xmachine_buyer_holder->next;
free_buyer_agent(current_xmachine_buyer_holder, buyer_01_state);
current_xmachine_buyer_holder = temp_xmachine_buyer_holder;
}
buyer_01_state->count = 0;
}
void free_buyer_states()
{
free(buyer_start_state);
free(buyer_end_state);
free(buyer_01_state);
}
void transition_buyer_agent(xmachine_memory_buyer_holder * tmp, xmachine_memory_buyer_state * from_state, xmachine_memory_buyer_state * to_state)
{
if(tmp->prev == NULL) from_state->agents = tmp->next;
else tmp->prev->next = tmp->next;
if(tmp->next != NULL) tmp->next->prev = tmp->prev;
add_buyer_agent_internal(tmp->agent, to_state);
free(tmp);
}
void add_buyer_agent_internal(xmachine_memory_buyer * agent, xmachine_memory_buyer_state * state)
{
xmachine_memory_buyer_holder * current = (xmachine_memory_buyer_holder *)malloc(sizeof(xmachine_memory_buyer_holder));
CHECK_POINTER(current);
current->next = state->agents;
current->prev = NULL;
state->agents = current;
if(current->next != NULL) current->next->prev = current;
current->agent = agent;
state->count++;
}
/** \fn void add_buyer_agent(int my_id, int firm_id, int my_qual)
* \brief Add buyer X-machine to the current being used X-machine list.
* \param my_id Variable for the X-machine memory.
* \param firm_id Variable for the X-machine memory.
* \param my_qual Variable for the X-machine memory.
*/
void add_buyer_agent(int my_id, int firm_id, int my_qual)
{
xmachine_memory_buyer * current;
current = init_buyer_agent();
/* new line added to handle dynamic agent creation*/
current_xmachine_buyer_next_state = buyer_start_state;
add_buyer_agent_internal(current, current_xmachine_buyer_next_state);
current->my_id = my_id;
current->firm_id = firm_id;
current->my_qual = my_qual;
}
xmachine_memory_firm_state * init_firm_state()
{
xmachine_memory_firm_state * current = (xmachine_memory_firm_state *)malloc(sizeof(xmachine_memory_firm_state));
CHECK_POINTER(current);
current->agents = NULL;
current->count = 0;
return current;
}
xmachine_memory_firm * init_firm_agent()
{
xmachine_memory_firm * current = (xmachine_memory_firm *)malloc(sizeof(xmachine_memory_firm));
CHECK_POINTER(current);
init_int_static_array(current->buyer_ids, 100);
current->my_id = 0;
current->quality = 0.0;
current->stored_id = 0;
return current;
}
void free_firm_agent(xmachine_memory_firm_holder * tmp, xmachine_memory_firm_state * state)
{
if(tmp->prev == NULL) state->agents = tmp->next;
else tmp->prev->next = tmp->next;
if(tmp->next != NULL) tmp->next->prev = tmp->prev;
free(tmp->agent);
free(tmp);
}
void unittest_init_firm_agent()
{
current_xmachine_firm = (xmachine_memory_firm *)malloc(sizeof(xmachine_memory_firm));
CHECK_POINTER(current);
init_int_static_array(current_xmachine_firm->buyer_ids, 100);
current_xmachine_firm->my_id = 0;
current_xmachine_firm->quality = 0.0;
current_xmachine_firm->stored_id = 0;
}
void unittest_free_firm_agent()
{
free(current_xmachine_firm);
}
void free_firm_agents()
{
current_xmachine_firm_holder = firm_end_state->agents;
while(current_xmachine_firm_holder)
{
temp_xmachine_firm_holder = current_xmachine_firm_holder->next;
free_firm_agent(current_xmachine_firm_holder, firm_end_state);
current_xmachine_firm_holder = temp_xmachine_firm_holder;
}
firm_end_state->count = 0;
current_xmachine_firm_holder = firm_01_state->agents;
while(current_xmachine_firm_holder)
{
temp_xmachine_firm_holder = current_xmachine_firm_holder->next;
free_firm_agent(current_xmachine_firm_holder, firm_01_state);
current_xmachine_firm_holder = temp_xmachine_firm_holder;
}
firm_01_state->count = 0;
current_xmachine_firm_holder = firm_start_state->agents;
while(current_xmachine_firm_holder)
{
temp_xmachine_firm_holder = current_xmachine_firm_holder->next;
free_firm_agent(current_xmachine_firm_holder, firm_start_state);
current_xmachine_firm_holder = temp_xmachine_firm_holder;
}
firm_start_state->count = 0;
current_xmachine_firm_holder = firm_03_state->agents;
while(current_xmachine_firm_holder)
{
temp_xmachine_firm_holder = current_xmachine_firm_holder->next;
free_firm_agent(current_xmachine_firm_holder, firm_03_state);
current_xmachine_firm_holder = temp_xmachine_firm_holder;
}
firm_03_state->count = 0;
current_xmachine_firm_holder = firm_02_state->agents;
while(current_xmachine_firm_holder)
{
temp_xmachine_firm_holder = current_xmachine_firm_holder->next;
free_firm_agent(current_xmachine_firm_holder, firm_02_state);
current_xmachine_firm_holder = temp_xmachine_firm_holder;
}
firm_02_state->count = 0;
}
void free_firm_states()
{
free(firm_end_state);
free(firm_01_state);
free(firm_start_state);
free(firm_03_state);
free(firm_02_state);
}
void transition_firm_agent(xmachine_memory_firm_holder * tmp, xmachine_memory_firm_state * from_state, xmachine_memory_firm_state * to_state)
{
if(tmp->prev == NULL) from_state->agents = tmp->next;
else tmp->prev->next = tmp->next;
if(tmp->next != NULL) tmp->next->prev = tmp->prev;
add_firm_agent_internal(tmp->agent, to_state);
free(tmp);
}
void add_firm_agent_internal(xmachine_memory_firm * agent, xmachine_memory_firm_state * state)
{
xmachine_memory_firm_holder * current = (xmachine_memory_firm_holder *)malloc(sizeof(xmachine_memory_firm_holder));
CHECK_POINTER(current);
current->next = state->agents;
current->prev = NULL;
state->agents = current;
if(current->next != NULL) current->next->prev = current;
current->agent = agent;
state->count++;
}
/** \fn void add_firm_agent(int buyer_ids[], int my_id, float quality, int stored_id)
* \brief Add firm X-machine to the current being used X-machine list.
* \param buyer_ids Variable for the X-machine memory.
* \param my_id Variable for the X-machine memory.
* \param quality Variable for the X-machine memory.
* \param stored_id Variable for the X-machine memory.
*/
void add_firm_agent(int buyer_ids[], int my_id, float quality, int stored_id)
{
xmachine_memory_firm * current;
current = init_firm_agent();
/* new line added to handle dynamic agent creation*/
current_xmachine_firm_next_state = firm_start_state;
add_firm_agent_internal(current, current_xmachine_firm_next_state);
memcpy(current->buyer_ids, buyer_ids, 100*sizeof(int));
current->my_id = my_id;
current->quality = quality;
current->stored_id = stored_id;
}
xmachine_memory_overseer_state * init_overseer_state()
{
xmachine_memory_overseer_state * current = (xmachine_memory_overseer_state *)malloc(sizeof(xmachine_memory_overseer_state));
CHECK_POINTER(current);
current->agents = NULL;
current->count = 0;
return current;
}
xmachine_memory_overseer * init_overseer_agent()
{
xmachine_memory_overseer * current = (xmachine_memory_overseer *)malloc(sizeof(xmachine_memory_overseer));
CHECK_POINTER(current);
init_int_static_array(current->firm_revenues, 10);
init_float_static_array(current->firm_strategies, 10);
return current;
}
void free_overseer_agent(xmachine_memory_overseer_holder * tmp, xmachine_memory_overseer_state * state)
{
if(tmp->prev == NULL) state->agents = tmp->next;
else tmp->prev->next = tmp->next;
if(tmp->next != NULL) tmp->next->prev = tmp->prev;
free(tmp->agent);
free(tmp);
}
void unittest_init_overseer_agent()
{
current_xmachine_overseer = (xmachine_memory_overseer *)malloc(sizeof(xmachine_memory_overseer));
CHECK_POINTER(current);
init_int_static_array(current_xmachine_overseer->firm_revenues, 10);
init_float_static_array(current_xmachine_overseer->firm_strategies, 10);
}
void unittest_free_overseer_agent()
{
free(current_xmachine_overseer);
}
void free_overseer_agents()
{
current_xmachine_overseer_holder = overseer_end_state->agents;
while(current_xmachine_overseer_holder)
{
temp_xmachine_overseer_holder = current_xmachine_overseer_holder->next;
free_overseer_agent(current_xmachine_overseer_holder, overseer_end_state);
current_xmachine_overseer_holder = temp_xmachine_overseer_holder;
}
overseer_end_state->count = 0;
current_xmachine_overseer_holder = overseer_01_state->agents;
while(current_xmachine_overseer_holder)
{
temp_xmachine_overseer_holder = current_xmachine_overseer_holder->next;
free_overseer_agent(current_xmachine_overseer_holder, overseer_01_state);
current_xmachine_overseer_holder = temp_xmachine_overseer_holder;
}
overseer_01_state->count = 0;
current_xmachine_overseer_holder = overseer_start_state->agents;
while(current_xmachine_overseer_holder)
{
temp_xmachine_overseer_holder = current_xmachine_overseer_holder->next;
free_overseer_agent(current_xmachine_overseer_holder, overseer_start_state);
current_xmachine_overseer_holder = temp_xmachine_overseer_holder;
}
overseer_start_state->count = 0;
}
void free_overseer_states()
{
free(overseer_end_state);
free(overseer_01_state);
free(overseer_start_state);
}
void transition_overseer_agent(xmachine_memory_overseer_holder * tmp, xmachine_memory_overseer_state * from_state, xmachine_memory_overseer_state * to_state)
{
if(tmp->prev == NULL) from_state->agents = tmp->next;
else tmp->prev->next = tmp->next;
if(tmp->next != NULL) tmp->next->prev = tmp->prev;
add_overseer_agent_internal(tmp->agent, to_state);
free(tmp);
}
void add_overseer_agent_internal(xmachine_memory_overseer * agent, xmachine_memory_overseer_state * state)
{
xmachine_memory_overseer_holder * current = (xmachine_memory_overseer_holder *)malloc(sizeof(xmachine_memory_overseer_holder));
CHECK_POINTER(current);
current->next = state->agents;
current->prev = NULL;
state->agents = current;
if(current->next != NULL) current->next->prev = current;
current->agent = agent;
state->count++;
}
/** \fn void add_overseer_agent(int firm_revenues[], float firm_strategies[])
* \brief Add overseer X-machine to the current being used X-machine list.
* \param firm_revenues Variable for the X-machine memory.
* \param firm_strategies Variable for the X-machine memory.
*/
void add_overseer_agent(int firm_revenues[], float firm_strategies[])
{
xmachine_memory_overseer * current;
current = init_overseer_agent();
/* new line added to handle dynamic agent creation*/
current_xmachine_overseer_next_state = overseer_start_state;
add_overseer_agent_internal(current, current_xmachine_overseer_next_state);
memcpy(current->firm_revenues, firm_revenues, 10*sizeof(int));
memcpy(current->firm_strategies, firm_strategies, 10*sizeof(float));
}
/* freexmachines */
/** \fn void freexmachines()
* \brief Free the currently being used X-machine list.
*/
void freexmachines()
{
free_buyer_agents();
free_firm_agents();
free_overseer_agents();
}
/** \fn void set_my_id(int my_id)
* \brief Set my_id memory variable for current X-machine.
* \param my_id New value for variable.
*/
void set_my_id(int my_id)
{
if(current_xmachine->xmachine_buyer) (*current_xmachine->xmachine_buyer).my_id = my_id;
if(current_xmachine->xmachine_firm) (*current_xmachine->xmachine_firm).my_id = my_id;
}
/** \fn int get_my_id()
* \brief Get my_id memory variable from current X-machine.
* \return Value for variable.
*/
int get_my_id()
{
if(current_xmachine->xmachine_buyer) return (*current_xmachine->xmachine_buyer).my_id;
if(current_xmachine->xmachine_firm) return (*current_xmachine->xmachine_firm).my_id;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return (int)0;
}
/** \fn void set_firm_id(int firm_id)
* \brief Set firm_id memory variable for current X-machine.
* \param firm_id New value for variable.
*/
void set_firm_id(int firm_id)
{
if(current_xmachine->xmachine_buyer) (*current_xmachine->xmachine_buyer).firm_id = firm_id;
}
/** \fn int get_firm_id()
* \brief Get firm_id memory variable from current X-machine.
* \return Value for variable.
*/
int get_firm_id()
{
if(current_xmachine->xmachine_buyer) return (*current_xmachine->xmachine_buyer).firm_id;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return (int)0;
}
/** \fn void set_my_qual(int my_qual)
* \brief Set my_qual memory variable for current X-machine.
* \param my_qual New value for variable.
*/
void set_my_qual(int my_qual)
{
if(current_xmachine->xmachine_buyer) (*current_xmachine->xmachine_buyer).my_qual = my_qual;
}
/** \fn int get_my_qual()
* \brief Get my_qual memory variable from current X-machine.
* \return Value for variable.
*/
int get_my_qual()
{
if(current_xmachine->xmachine_buyer) return (*current_xmachine->xmachine_buyer).my_qual;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return (int)0;
}
/** \fn int get_buyer_ids()
* \brief Get buyer_ids memory variable from current X-machine.
* \return Value for variable.
*/
int * get_buyer_ids()
{
if(current_xmachine->xmachine_firm) return (*current_xmachine->xmachine_firm).buyer_ids;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return NULL;
}
/** \fn void set_quality(float quality)
* \brief Set quality memory variable for current X-machine.
* \param quality New value for variable.
*/
void set_quality(float quality)
{
if(current_xmachine->xmachine_firm) (*current_xmachine->xmachine_firm).quality = quality;
}
/** \fn float get_quality()
* \brief Get quality memory variable from current X-machine.
* \return Value for variable.
*/
float get_quality()
{
if(current_xmachine->xmachine_firm) return (*current_xmachine->xmachine_firm).quality;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return (float)0;
}
/** \fn void set_stored_id(int stored_id)
* \brief Set stored_id memory variable for current X-machine.
* \param stored_id New value for variable.
*/
void set_stored_id(int stored_id)
{
if(current_xmachine->xmachine_firm) (*current_xmachine->xmachine_firm).stored_id = stored_id;
}
/** \fn int get_stored_id()
* \brief Get stored_id memory variable from current X-machine.
* \return Value for variable.
*/
int get_stored_id()
{
if(current_xmachine->xmachine_firm) return (*current_xmachine->xmachine_firm).stored_id;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return (int)0;
}
/** \fn int get_firm_revenues()
* \brief Get firm_revenues memory variable from current X-machine.
* \return Value for variable.
*/
int * get_firm_revenues()
{
if(current_xmachine->xmachine_overseer) return (*current_xmachine->xmachine_overseer).firm_revenues;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return NULL;
}
/** \fn float get_firm_strategies()
* \brief Get firm_strategies memory variable from current X-machine.
* \return Value for variable.
*/
float * get_firm_strategies()
{
if(current_xmachine->xmachine_overseer) return (*current_xmachine->xmachine_overseer).firm_strategies;
// suppress compiler warning by returning dummy value /
// this statement should rightfully NEVER be reached /
return NULL;
}
/** \fn double agent_get_range()
* \brief Fixed routine to get the range from current X-machine
* \return Value of range
*/
double agent_get_range()
{
double value = 0.0;
/*if (current_xmachine->xmachine_buyer) value = current_xmachine->xmachine_buyer->;*/
/*if (current_xmachine->xmachine_firm) value = current_xmachine->xmachine_firm->;*/
/*if (current_xmachine->xmachine_overseer) value = current_xmachine->xmachine_overseer->;*/
return value;
}
/** \fn int agent_get_id()
* \brief Fixed routine to get the id for the current X-machine
* \return Value of agent id
*/
int agent_get_id()
{
int value = 0;
/*if (current_xmachine->xmachine_buyer) value = current_xmachine->xmachine_buyer->;*/
/*if (current_xmachine->xmachine_firm) value = current_xmachine->xmachine_firm->;*/
/*if (current_xmachine->xmachine_overseer) value = current_xmachine->xmachine_overseer->;*/
return value;
}
/** \fn double agent_get_x()
* \brief Fixed routine to get the x coordinate from current X-machine
* \return Value of x coordinate
*/
double agent_get_x()
{
double value = 0.0;
/*if (current_xmachine->xmachine_buyer) value = current_xmachine->xmachine_buyer->0.0;*/
/*if (current_xmachine->xmachine_firm) value = current_xmachine->xmachine_firm->0.0;*/
/*if (current_xmachine->xmachine_overseer) value = current_xmachine->xmachine_overseer->0.0;*/
return value;
}
/** \fn double agent_get_y()
* \brief Fixed routine to get the y coordinate from current X-machine
* \return Value of y coordinate
*/
double agent_get_y()
{
double value = 0.0;
/*if (current_xmachine->xmachine_buyer) value = current_xmachine->xmachine_buyer->0.0;*/
/*if (current_xmachine->xmachine_firm) value = current_xmachine->xmachine_firm->0.0;*/
/*if (current_xmachine->xmachine_overseer) value = current_xmachine->xmachine_overseer->0.0;*/
return value;
}
/** \fn double agent_get_z()
* \brief Fixed routine to get the z coordinate from current X-machine
* \return Value of z coordinate
*/
double agent_get_z()
{
double value = 0.0;
return value;
}
/** \fn void add_node(int node_id, double minx, double maxx, double miny, double maxy, double minz, double maxz)
* \brief Add a node to the node list.
* \param node_id The node ID.
* \param minx The minumum value on the x-axis of the bounding volume.
* \param maxx The maximum value on the x-axis of the bounding volume.
* \param miny The minumum value on the y-axis of the bounding volume.
* \param maxy The maximum value on the y-axis of the bounding volume.
* \param minz The minumum value on the z-axis of the bounding volume.
* \param maxz The maximum value on the z-axis of the bounding volume.
*/
void add_node(int node_id, double minx, double maxx, double miny, double maxy, double minz, double maxz)
{
node_information * current = *p_node_info;
node_information * tmp = NULL;
while(current)
{
tmp = current;
current = current->next;
}
current = (node_information *)malloc(sizeof(node_information));
CHECK_POINTER(current);
if(tmp)
{
tmp->next = current;
}
else
{
*p_node_info = current;
}
current->next = NULL;
current->node_id = node_id;
current->agents_in_halo = 0;
current->agent_total = 0;
current->agents = NULL;
current->PurchaseQuality_messages = NULL;
current->Purchase_messages = NULL;
current->StrategyAdjustment_messages = NULL;
current->partition_data[0] = minx;
current->partition_data[1] = maxx;
current->partition_data[2] = miny;
current->partition_data[3] = maxy;
current->partition_data[4] = minz;
current->partition_data[5] = maxz;
}
/**\fn void free_node_info()
* \brief Free the node list.
*/
void free_node_info()
{
node_information * tmp, * head;
head = *p_node_info;
while(head)
{
tmp = head->next;
free(head);
head = tmp;
}
*p_node_info = NULL;
}
/** \fn void clean_up(int code)
* \brief Add a node to the node list.
* \param code The error code (zero is no error).
*/
void clean_up(int code)
{
int rc;
FILE *file;
char data[100];
free(current_xmachine);
/* Free x-machine memory */
freexmachines();
/* Free space partitions linked list */
free_node_info();
/* Free output list */
free_FLAME_outputs(&FLAME_outputs);
/* Free agent states */
free_buyer_states();
free_firm_states();
free_overseer_states();
/* Free index maps */
/* Free message boards */
rc = MB_Delete(&b_PurchaseQuality);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not delete 'PurchaseQuality' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'PurchaseQuality' board has not been created?\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'PurchaseQuality' board is locked\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Delete returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
rc = MB_Delete(&b_Purchase);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not delete 'Purchase' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'Purchase' board has not been created?\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'Purchase' board is locked\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Delete returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
rc = MB_Delete(&b_StrategyAdjustment);
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not delete 'StrategyAdjustment' board\n");
switch(rc) {
case MB_ERR_INVALID:
fprintf(stderr, "\t reason: 'StrategyAdjustment' board has not been created?\n");
break;
case MB_ERR_LOCKED:
fprintf(stderr, "\t reason: 'StrategyAdjustment' board is locked\n");
break;
case MB_ERR_INTERNAL:
fprintf(stderr, "\t reason: internal error. Recompile libmoard in debug mode for more info \n");
break;
default:
fprintf(stderr, "\t MB_Delete returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
rc = MB_Env_Finalise();
#ifdef ERRCHECK
if (rc != MB_SUCCESS)
{
fprintf(stderr, "ERROR: Could not finalise MB environment\n");
switch(rc) {
case MB_ERR_ENV:
fprintf(stderr, "\t reason: MB environment not yet started?\n");
break;
default:
fprintf(stderr, "\t MB_Env_Finalise returned error code: %d (see libmboard docs for details)\n", rc);
break;
}
exit(rc);
}
#endif
/* Write log file */
sprintf(data, "%slog.xml", outputpath);
file = fopen(data, "a");
fputs("<!-- <totaltime> unit: seconds -->\n", file);
fputs("<totaltime>", file);
sprintf(data, "%.3f", total_time);
fputs(data, file);
fputs("</totaltime>\n", file);
/*fputs("<totalmessages>", file);
sprintf(data, "%i", total_messages);
fputs(data, file);
fputs("</totalmessages>", file);*/
fputs("</model_run>", file);
fclose(file);
if(code != 0)
{
printf("*** Error: ");
if(code == 100) printf("cannot handle specified number of space partitions");
if(code == 101) printf("could not find number of space partitions config in file");
printf(" ***");
exit(0);
}
}
/** \fn void propagate_agents()
* \brief Check agent positions to see if any need to be moved to a another node.
*/
void propagate_agents()
{
/* node_information * node_info;
xmachine * before_xmachine, * temp_xmachine;
xmachine ** p_temp_xmachine;
double x_xmachine, y_xmachine, z_xmachine;
current_xmachine = *p_xmachine;
before_xmachine = NULL;
while(current_xmachine)
{
if(current_xmachine->xmachine_buyer != NULL)
{
x_xmachine = current_xmachine->xmachine_buyer->0.0;
y_xmachine = current_xmachine->xmachine_buyer->0.0;
z_xmachine = 0.0;
}
else if(current_xmachine->xmachine_firm != NULL)
{
x_xmachine = current_xmachine->xmachine_firm->0.0;
y_xmachine = current_xmachine->xmachine_firm->0.0;
z_xmachine = 0.0;
}
else if(current_xmachine->xmachine_overseer != NULL)
{
x_xmachine = current_xmachine->xmachine_overseer->0.0;
y_xmachine = current_xmachine->xmachine_overseer->0.0;
z_xmachine = 0.0;
}
if(x_xmachine < current_node->partition_data[0] ||
x_xmachine > current_node->partition_data[1] ||
y_xmachine < current_node->partition_data[2] ||
y_xmachine > current_node->partition_data[3] ||
z_xmachine < current_node->partition_data[4] ||
z_xmachine > current_node->partition_data[5])
{
node_info = *p_node_info;
while(node_info)
{
if(node_info->node_id != current_node->node_id &&
node_info->partition_data[0] < x_xmachine && node_info->partition_data[1] > x_xmachine &&
node_info->partition_data[2] < y_xmachine && node_info->partition_data[3] > y_xmachine &&
node_info->partition_data[4] < z_xmachine && node_info->partition_data[5] > z_xmachine)
{
// Remove agent
if(before_xmachine) before_xmachine->next = current_xmachine->next;
else *p_xmachine = current_xmachine->next;
current_node->agent_total--;
// Add agent
p_temp_xmachine = &node_info->agents;
temp_xmachine = *p_temp_xmachine;
current_xmachine->next = temp_xmachine;
*p_temp_xmachine = current_xmachine;
node_info->agent_total++;
node_info = NULL;
}
else node_info = node_info->next;
}
}
else before_xmachine = current_xmachine;
if(before_xmachine) current_xmachine = before_xmachine->next;
else current_xmachine = NULL;
}*/
}
/** \fn int_array * init_int_array()
* \brief Allocate memory for a dynamic integer array.
* \return int_array Pointer to the new dynamic integer array.
*/
void init_int_array(int_array * array)
{
(*array).size = 0;
(*array).total_size = ARRAY_BLOCK_SIZE;
(*array).array = (int *)malloc(ARRAY_BLOCK_SIZE * sizeof(int));
CHECK_POINTER((*array).array);
}
/** \fn void reset_int_array(int_array * array)
* \brief Reset the int array to hold nothing.
* \param array Pointer to the dynamic integer array.
*/
void reset_int_array(int_array * array)
{
(*array).size = 0;
}
/** \fn void free_int_array(int_array * array)
* \brief Free the memory of a dynamic integer array.
* \param array Pointer to the dynamic integer array.
*/
void free_int_array(int_array * array)
{
free((*array).array);
}
void copy_int_array(int_array * from, int_array * to)
{
int i;
//to = init_int_array();
for (i = 0; i < (*from).size; i++)
{
add_int(to, (*from).array[i]);
}
}
/** \fn void sort_int_array(int_array * array)
* \brief Sort the elements of a dynamic integer array with smallest first.
* \param array Pointer to the dynamic integer array.
*/
/*void sort_int_array(int_array * array)
{
int i, j, temp;
for(i=0; i<((*array).size-1); i++)
{
for(j=0; j<((*array).size-1)-i; j++)
{
if(*((*array).array+j+1) < *((*array).array+j))
{
temp = *((*array).(*array)+j);
*((*array).array+j) = *((*array).array+j+1);
*((*array).array+j+1) = temp;
}
}
}
}*/
/** \fn int quicksort_int(int *array, int elements)
* \brief Sorts the elements of the integer array in ascending order.
* \param Pointer to integer array
* \param Number of elements that must be sorted
* \return integer value indicating success(0) or failure(1)
*/
/*int quicksort_int(int array, int elements)
{
#define LEVEL 1000
int pivot, begin[LEVEL], end[LEVEL], i=0, left, right ;
begin[0]=0; end[0]=elements;
while (i>=0)
{
left=begin[i]; right=end[i]-1;
if (left<right)
{
pivot=array[left]; if (i==LEVEL-1) return 1;
while (left<right)
{
while (array[right]>=pivot && left<right) right--;
if (left<right) array[left++]=array[right];
while (array[left]<=pivot && left<right) left++;
if (left<right) array[right--]=array[left];
}
array[left]=pivot;
begin[i+1]=left+1;
end[i+1]=end[i];
end[i++]=left;
}
else
{
i--;
}
}
return 0;
}*/
/** \fn void add_int(int_array * array, int new_int)
* \brief Add an integer to the dynamic integer array.
* \param array Pointer to the dynamic integer array.
* \param new_int The integer to add
*/
void add_int(int_array * array, int new_int)
{
if((*array).size == (*array).total_size)
{
(*array).total_size = (int)((*array).total_size * ARRAY_GROWTH_RATE);
(*array).array = (int *)realloc((*array).array, ((*array).total_size * sizeof(int)));
}
(*array).array[(*array).size] = new_int;
(*array).size++;
}
/** \fn void remove_int(int_array * array, int index)
* \brief Remove an integer from a dynamic integer array.
* \param array Pointer to the dynamic integer array.
* \param index The index of the integer to remove.
*/
void remove_int(int_array * array, int index)
{
int i;
if(index < (*array).size)
{
/* memcopy?? */
for(i = index; i < (*array).size - 1; i++)
{
(*array).array[i] = (*array).array[i+1];
}
(*array).size--;
}
}
/** \fn void print_int_array(int_array * array)
* \brief Print the elements of a dynamic integer array.
* \param array Pointer to the dynamic integer array.
*/
void print_int_array(int_array * array)
{
int i;
for(i=0; i<(*array).size; i++)
{
printf("%d> %d", i, (*array).array[i]);
}
}
/** \fn float_array * init_float_array()
* \brief Allocate memory for a dynamic float array.
* \return float_array Pointer to the new dynamic float array.
*/
void init_float_array(float_array * array)
{
(*array).size = 0;
(*array).total_size = ARRAY_BLOCK_SIZE;
(*array).array = (float *)malloc(ARRAY_BLOCK_SIZE * sizeof(float));
CHECK_POINTER((*array).array);
}
/** \fn void reset_float_array(float_array * array)
* \brief Reset the float array to hold nothing.
* \param array Pointer to the dynamic float array.
*/
void reset_float_array(float_array * array)
{
(*array).size = 0;
}
/** \fn void free_float_array(float_array * array)
* \brief Free the memory of a dynamic float array.
* \param array Pointer to the dynamic float array.
*/
void free_float_array(float_array * array)
{
free((*array).array);
}
void copy_float_array(float_array * from, float_array * to)
{
int i;
//to = init_float_array();
for (i = 0; i < (*from).size; i++)
{
add_float(to, (*from).array[i]);
}
}
/** \fn void sort_float_array(float_array * array)
* \brief Sort the elements of a dynamic float array with smallest first.
* \param array Pointer to the dynamic float array.
*/
/*void sort_float_array(float_array array)
{
int i, j;
float temp;
// Using bubble sorts nested loops //
for(i=0; i<(array.size-1); i++)
{
for(j=0; j<(array.size-1)-i; j++)
{
// Comparing the values between neighbours //
if(*(array.array+j+1) < *(array.array+j))
{
// Swap neighbours //
temp = *(array.array+j);
*(array.array+j) = *(array.array+j+1);
*(array.array+j+1) = temp;
}
}
}
}*/
/** \fn int quicksort_float(float *array, int elements)
* \brief Sorts the elements of the float array in ascending order.
* \param Pointer to float array
* \param Number of elements that must be sorted
* \return integer value indicating success(0) or failure(1)
*/
/*int quicksort_float(float array, int elements)
{
#define LEVEL 1000
int i=0, left, right ;
float pivot, begin[LEVEL], end[LEVEL];
begin[0]=0; end[0]=elements;
while (i>=0)
{
left=begin[i]; right=end[i]-1;
if (left<right)
{
pivot=array[left]; if (i==LEVEL-1) return 1;
while (left<right)
{
while (array[right]>=pivot && left<right) right--;
if (left<right) array[left++]=array[right];
while (array[left]<=pivot && left<right) left++;
if (left<right) array[right--]=array[left];
}
array[left]=pivot;
begin[i+1]=left+1;
end[i+1]=end[i];
end[i++]=left;
}
else
{
i--;
}
}
return 0;
}*/
/** \fn void add_float(float_array * array, float new_float)
* \brief Add an floateger to the dynamic float array.
* \param array Pointer to the dynamic float array.
* \param new_float The float to add
*/
void add_float(float_array * array, float new_float)
{
if((*array).size == (*array).total_size)
{
(*array).total_size = (int)((*array).total_size * ARRAY_GROWTH_RATE);
(*array).array = (float *)realloc((*array).array, ((*array).total_size * sizeof(float)));
}
(*array).array[(*array).size] = new_float;
(*array).size++;
}
/** \fn void remove_float(float_array * array, int index)
* \brief Remove an floateger from a dynamic float array.
* \param array Pointer to the dynamic float array.
* \param index The index of the float to remove.
*/
void remove_float(float_array * array, int index)
{
int i;
if(index < (*array).size)
{
/* memcopy?? */
for(i = index; i < (*array).size - 1; i++)
{
(*array).array[i] = (*array).array[i+1];
}
(*array).size--;
}
}
/** \fn void print_float_array(float_array * array)
* \brief Print the elements of a dynamic float array.
* \param array Pointer to the dynamic float array.
*/
void print_float_array(float_array * array)
{
int i;
/* printf(""); // compiler does not like empty prfloats */
for(i=0; i<(*array).size; i++)
{
printf("%d> %f", i, (*array).array[i]);
}
}
/** \fn double_array * init_double_array()
* \brief Allocate memory for a dynamic double array.
* \return double_array Pointer to the new dynamic double array.
*/
void init_double_array(double_array * array)
{
(*array).size = 0;
(*array).total_size = ARRAY_BLOCK_SIZE;
(*array).array = (double *)malloc(ARRAY_BLOCK_SIZE * sizeof(double));
CHECK_POINTER((*array).array);
}
/** \fn void reset_double_array(double_array * array)
* \brief Reset the double array to hold nothing.
* \param array Pointer to the dynamic double array.
*/
void reset_double_array(double_array * array)
{
(*array).size = 0;
}
/** \fn void free_double_array(double_array * array)
* \brief Free the memory of a dynamic double array.
* \param array Pointer to the dynamic double array.
*/
void free_double_array(double_array * array)
{
free((*array).array);
}
void copy_double_array(double_array * from, double_array * to)
{
int i;
//to = init_double_array();
for (i = 0; i < (*from).size; i++)
{
add_double(to, (*from).array[i]);
}
}
/** \fn void sort_double_array(double_array * array)
* \brief Sort the elements of a dynamic double array with smallest first.
* \param array Pointer to the dynamic double array.
*/
/*void sort_double_array(double_array array)
{
int i, j;
double temp;
// Using bubble sorts nested loops //
for(i=0; i<(array.size-1); i++)
{
for(j=0; j<(array.size-1)-i; j++)
{
// Comparing the values between neighbours //
if(*(array.array+j+1) < *(array.array+j))
{
// Swap neighbours //
temp = *(array.array+j);
*(array.array+j) = *(array.array+j+1);
*(array.array+j+1) = temp;
}
}
}
}*/
/** \fn int quicksort_double(double *array, int elements)
* \brief Sorts the elements of the double array in ascending order.
* \param Pointer to double array
* \param Number of elements that must be sorted
* \return integer value indicating success(0) or failure(1)
*/
/*int quicksort_double(double array, int elements)
{
#define LEVEL 1000
double pivot, begin[LEVEL], end[LEVEL];
int i=0, left, right ;
begin[0]=0; end[0]=elements;
while (i>=0)
{
left=begin[i]; right=end[i]-1;
if (left<right)
{
pivot=array[left]; if (i==LEVEL-1) return 1;
while (left<right)
{
while (array[right]>=pivot && left<right) right--;
if (left<right) array[left++]=array[right];
while (array[left]<=pivot && left<right) left++;
if (left<right) array[right--]=array[left];
}
array[left]=pivot;
begin[i+1]=left+1;
end[i+1]=end[i];
end[i++]=left;
}
else
{
i--;
}
}
return 0;
}*/
/** \fn void add_double(double_array * array, double new_double)
* \brief Add an double to the dynamic double array.
* \param array Pointer to the dynamic double array.
* \param new_double The double to add
*/
void add_double(double_array * array, double new_double)
{
if((*array).size == (*array).total_size)
{
(*array).total_size = (int)((*array).total_size * ARRAY_GROWTH_RATE);
(*array).array = (double *)realloc((*array).array, ((*array).total_size * sizeof(double)));
}
(*array).array[(*array).size] = new_double;
(*array).size++;
}
/** \fn void remove_double(double_array * array, int index)
* \brief Remove an double from a dynamic double array.
* \param array Pointer to the dynamic double array.
* \param index The index of the double to remove.
*/
void remove_double(double_array * array, int index)
{
int i;
if(index < (*array).size)
{
/* memcopy?? */
for(i = index; i < (*array).size - 1; i++)
{
(*array).array[i] = (*array).array[i+1];
}
(*array).size--;
}
}
/** \fn void print_double_array(double_array * array)
* \brief Print the elements of a dynamic double array.
* \param array Pointer to the dynamic double array.
*/
void print_double_array(double_array * array)
{
int i;
for(i=0; i<(*array).size; i++)
{
printf("%d> %f", i, (*array).array[i]);
}
}
/** \fn char_array * init_char_array()
* \brief Allocate memory for a dynamic char array.
* \return char_array Pointer to the new dynamic char array.
*/
void init_char_array(char_array * array)
{
(*array).size = 0;
(*array).total_size = ARRAY_BLOCK_SIZE;
(*array).array = (char *)malloc(ARRAY_BLOCK_SIZE * sizeof(char));
CHECK_POINTER((*array).array);
(*array).array[0] = '\0';
}
/** \fn void reset_char_array(char_array * array)
* \brief Reset the char array to hold nothing.
* \param array Pointer to the dynamic char array.
*/
void reset_char_array(char_array * array)
{
(*array).size = 0;
}
/** \fn void free_char_array(char_array * array)
* \brief Free the memory of a dynamic char array.
* \param array Pointer to the dynamic char array.
*/
void free_char_array(char_array * array)
{
free((*array).array);
}
void copy_char_array(char_array * from, char_array * to)
{
int i;
for (i = 0; i < (*from).size; i++)
{
add_char(to, (*from).array[i]);
}
}
/** \fn void add_char(char_array * array, char new_char)
* \brief Add an char to the dynamic char array.
* \param array Pointer to the dynamic char array.
* \param new_char The char to add
*/
void add_char(char_array * array, char new_char)
{
if((*array).size + 1 == (*array).total_size)
{
(*array).total_size = (int)((*array).total_size * ARRAY_GROWTH_RATE);
(*array).array = (char *)realloc((*array).array, ((*array).total_size * sizeof(char)));
}
(*array).array[(*array).size] = new_char;
(*array).array[(*array).size + 1] = '\0';
(*array).size++;
}
/** \fn void remove_char(char_array * array, int index)
* \brief Remove an char from a dynamic char array.
* \param array Pointer to the dynamic char array.
* \param index The index of the char to remove.
*/
void remove_char(char_array * array, int index)
{
int i;
if(index < (*array).size)
{
/* memcopy?? */
for(i = index; i < (*array).size - 1; i++)
{
(*array).array[i] = (*array).array[i+1];
}
(*array).size--;
}
}
/** \fn char * copy_array_to_str(char_array * array)
* \brief Return pointer to string from a char_array.
* \param array Pointer to the dynamic integer array.
* \return char Pointer to the new string.
*/
char * copy_array_to_str(char_array * array)
{
char * new_string = (char *)malloc( ((*array).size + 1) * sizeof(char));
CHECK_POINTER(new_string);
return strcpy(new_string, (*array).array);
}
/** \fn void print_char_array(char_array * array)
* \brief Print the elements of a dynamic char array.
* \param array Pointer to the dynamic char array.
*/
void print_char_array(char_array * array)
{
printf("%s", (*array).array);
}
/** \fn int idle()
* \brief an idle function for use by agents.
*/
int idle()
{
return 0;
}
| 27.406621 | 166 | 0.673415 |
db4eeedd8f16f7c460cdd15c726b6b51de643139 | 2,704 | h | C | src/core/server.h | icerwings/libmv | dfdc4d4932a0cb623975a256f84b452f42ce50ee | [
"MIT"
] | 2 | 2017-09-21T02:51:56.000Z | 2018-02-28T07:31:40.000Z | src/core/server.h | icerwings/libmv | dfdc4d4932a0cb623975a256f84b452f42ce50ee | [
"MIT"
] | null | null | null | src/core/server.h | icerwings/libmv | dfdc4d4932a0cb623975a256f84b452f42ce50ee | [
"MIT"
] | null | null | null | /* Copyright Hengfeng Lang. Inspiredd by libuv link: http://www.libuv.org
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), toi
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef __server_h__
#define __server_h__
#include <sys/types.h>
#include <string>
#include <vector>
#include <functional>
#include "io.h"
using namespace std;
class Tcp;
class Buff;
class Signalfd;
class Server: public IO {
public:
Server();
virtual ~Server();
int Open(uint16_t port, uint32_t poolsize = 0);
void SetIoReadFunc(function<int(Buff *, Tcp *)> svrcb);
void SetIoCloseFunc(function<void(Tcp *)> ioclosecb);
void SetIoAcceptFunc(function<int(Tcp *)> ioacceptcb);
void SetCloseFunc(function<void()> closecb);
void SetExitSig(int exitsig);
void SetExitFunc(function<void()> exitcb);
int Run();
protected:
virtual void OnIoClose() override;
virtual int OnIoRead() override;
private:
int OpenSpareFile(const string & path);
void OnEmfile();
int Accept(struct sockaddr *remote = nullptr);
Epoll *m_epoll;
Signalfd *m_signalfd;
int m_sockfd;
function<int(Buff *, Tcp *)> m_svrcb;
function<void(Tcp *)> m_ioclosecb;
function<int(Tcp *)> m_ioacceptcb;
function<void()> m_closecb;
int m_emfile;
vector<Epoll *> m_pool;
int m_exitsig;
};
#endif
| 38.084507 | 80 | 0.617973 |
9ca4f143f1c973ed21cf60cfbffdfc4f029f4123 | 8,963 | h | C | sdk-6.5.20/src/bcm/esw/pktio/bcmpkt/include/bcmpkt/bcmpkt_rxpmd_flex_defs.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/bcm/esw/pktio/bcmpkt/include/bcmpkt/bcmpkt_rxpmd_flex_defs.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/bcm/esw/pktio/bcmpkt/include/bcmpkt/bcmpkt_rxpmd_flex_defs.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | #ifndef BCMPKT_RXPMD_FLEX_DEFS_H
#define BCMPKT_RXPMD_FLEX_DEFS_H
/*****************************************************************
*
* DO NOT EDIT THIS FILE!
* This file is auto-generated by xfc_map_parser
* from the NPL output file(s) map.yml.
* Edits to this file will be lost when it is regenerated.
*
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
* All Rights Reserved.$
*
* Tool Path: $SDK/INTERNAL/fltg/xfc_map_parser
*/
/*!
* \name RX flex metadata field IDs.
* \anchor BCMPKT_RXPMD_FLEX_XXX
*/
#define BCMPKT_RXPMD_FLEX_ING_TIMESTAMP_15_0 0
#define BCMPKT_RXPMD_FLEX_L3_IIF_13_0 1
#define BCMPKT_RXPMD_FLEX_EVENT_TRACE_VECTOR_15_0 2
#define BCMPKT_RXPMD_FLEX_NHOP_INDEX_1_14_0 3
#define BCMPKT_RXPMD_FLEX_VFI_15_0 4
#define BCMPKT_RXPMD_FLEX_L2_OIF_10_0 5
#define BCMPKT_RXPMD_FLEX_I2E_CLASS_ID_15_0 6
#define BCMPKT_RXPMD_FLEX_PKT_MISC_CTRL_0_3_0 7
#define BCMPKT_RXPMD_FLEX_DLB_ECMP_DESTINATION_15_0 8
#define BCMPKT_RXPMD_FLEX_SVP_NETWORK_GROUP_BITMAP_3_0 9
#define BCMPKT_RXPMD_FLEX_SYSTEM_DESTINATION_15_0 10
#define BCMPKT_RXPMD_FLEX_L2_IIF_10_0 11
#define BCMPKT_RXPMD_FLEX_NHOP_2_OR_ECMP_GROUP_INDEX_1_14_0 12
#define BCMPKT_RXPMD_FLEX_L3_OIF_1_13_0 13
#define BCMPKT_RXPMD_FLEX_DVP_15_0 14
#define BCMPKT_RXPMD_FLEX_EVENT_TRACE_VECTOR_47_32 15
#define BCMPKT_RXPMD_FLEX_ENTROPY_LABEL_LOW_15_0 16
#define BCMPKT_RXPMD_FLEX_SYSTEM_OPCODE_3_0 17
#define BCMPKT_RXPMD_FLEX_ING_TIMESTAMP_31_16 18
#define BCMPKT_RXPMD_FLEX_SYSTEM_SOURCE_15_0 19
#define BCMPKT_RXPMD_FLEX_ENTROPY_LABEL_HIGH_3_0 20
#define BCMPKT_RXPMD_FLEX_L2_IIF_QOS_REMARK_CTRL_3_0 21
#define BCMPKT_RXPMD_FLEX_TIMESTAMP_CTRL_3_0 22
#define BCMPKT_RXPMD_FLEX_EVENT_TRACE_VECTOR_31_16 23
#define BCMPKT_RXPMD_FLEX_INGRESS_PP_PORT_7_0 24
#define BCMPKT_RXPMD_FLEX_IFP_TS_CONTROL_ACTION_3_0 25
#define BCMPKT_RXPMD_FLEX_EFFECTIVE_TTL_7_0 26
#define BCMPKT_RXPMD_FLEX_SVP_15_0 27
#define BCMPKT_RXPMD_FLEX_DROP_CODE_15_0 28
#define BCMPKT_RXPMD_FLEX_INT_PRI_3_0 29
#define BCMPKT_RXPMD_FLEX_TUNNEL_PROCESSING_RESULTS_1_3_0 30
#define BCMPKT_RXPMD_FLEX_PARSER_VHLEN_0_15_0 31
#define BCMPKT_RXPMD_FLEX_VLAN_TAG_PRESERVE_CTRL_1_0 32
#define BCMPKT_RXPMD_FLEX_IFP_IOAM_ACTION_3_0 33
#define BCMPKT_RXPMD_FLEX_MPLS_LABEL_DECAP_COUNT_3_0 34
#define BCMPKT_RXPMD_FLEX_L3_DNAT_INDEX_15_0 35
#define BCMPKT_RXPMD_FLEX_NAT_CTRL_3_0 36
#define BCMPKT_RXPMD_FLEX_L3_SNAT_INDEX_15_0 37
#define BCMPKT_RXPMD_FLEX_FID_COUNT 38
#define BCMPKT_RXPMD_FLEX_FID_START 0
#define BCMPKT_RXPMD_FLEX_FID_END 37
#define BCMPKT_RXPMD_FLEX_I_REASON 0
#define BCMPKT_RXPMD_FLEX_FID_INVALID -1
#define BCMPKT_RXPMD_FLEX_REASON_COUNT 19
#define BCMPKT_RXPMD_FLEX_REASON_NONE 0
/*!
* \name Packet Flex Reason Types.
* \anchor BCMPKT_RXPMD_FLEX_REASON_XXX
*/
#define BCMPKT_RXPMD_FLEX_REASON_CML_FLAGS 0
#define BCMPKT_RXPMD_FLEX_REASON_L2_SRC_STATIC_MOVE 1
#define BCMPKT_RXPMD_FLEX_REASON_PKT_INTEGRITY_CHECK_FAILED 2
#define BCMPKT_RXPMD_FLEX_REASON_PROTOCOL_PKT 3
#define BCMPKT_RXPMD_FLEX_REASON_L2_DST_LOOKUP_MISS 4
#define BCMPKT_RXPMD_FLEX_REASON_L2_DST_LOOKUP 5
#define BCMPKT_RXPMD_FLEX_REASON_L3_DST_LOOKUP_MISS 6
#define BCMPKT_RXPMD_FLEX_REASON_L3_DST_LOOKUP 7
#define BCMPKT_RXPMD_FLEX_REASON_L3_HDR_ERROR 8
#define BCMPKT_RXPMD_FLEX_REASON_L3_TTL_ERROR 9
#define BCMPKT_RXPMD_FLEX_REASON_IPMC_L3_IIF_OR_RPA_ID_CHECK_FAILED 10
#define BCMPKT_RXPMD_FLEX_REASON_LEARN_CACHE_FULL 11
#define BCMPKT_RXPMD_FLEX_REASON_VFP 12
#define BCMPKT_RXPMD_FLEX_REASON_IFP 13
#define BCMPKT_RXPMD_FLEX_REASON_IFP_METER 14
#define BCMPKT_RXPMD_FLEX_REASON_DST_FP 15
#define BCMPKT_RXPMD_FLEX_REASON_SVP 16
#define BCMPKT_RXPMD_FLEX_REASON_EM_FT 17
#define BCMPKT_RXPMD_FLEX_REASON_IVXLT 18
#define BCMPKT_RXPMD_FLEX_FIELD_NAME_MAP_INIT \
{"ING_TIMESTAMP_15_0", BCMPKT_RXPMD_FLEX_ING_TIMESTAMP_15_0},\
{"L3_IIF_13_0", BCMPKT_RXPMD_FLEX_L3_IIF_13_0},\
{"EVENT_TRACE_VECTOR_15_0", BCMPKT_RXPMD_FLEX_EVENT_TRACE_VECTOR_15_0},\
{"NHOP_INDEX_1_14_0", BCMPKT_RXPMD_FLEX_NHOP_INDEX_1_14_0},\
{"VFI_15_0", BCMPKT_RXPMD_FLEX_VFI_15_0},\
{"L2_OIF_10_0", BCMPKT_RXPMD_FLEX_L2_OIF_10_0},\
{"I2E_CLASS_ID_15_0", BCMPKT_RXPMD_FLEX_I2E_CLASS_ID_15_0},\
{"PKT_MISC_CTRL_0_3_0", BCMPKT_RXPMD_FLEX_PKT_MISC_CTRL_0_3_0},\
{"DLB_ECMP_DESTINATION_15_0", BCMPKT_RXPMD_FLEX_DLB_ECMP_DESTINATION_15_0},\
{"SVP_NETWORK_GROUP_BITMAP_3_0", BCMPKT_RXPMD_FLEX_SVP_NETWORK_GROUP_BITMAP_3_0},\
{"SYSTEM_DESTINATION_15_0", BCMPKT_RXPMD_FLEX_SYSTEM_DESTINATION_15_0},\
{"L2_IIF_10_0", BCMPKT_RXPMD_FLEX_L2_IIF_10_0},\
{"NHOP_2_OR_ECMP_GROUP_INDEX_1_14_0", BCMPKT_RXPMD_FLEX_NHOP_2_OR_ECMP_GROUP_INDEX_1_14_0},\
{"L3_OIF_1_13_0", BCMPKT_RXPMD_FLEX_L3_OIF_1_13_0},\
{"DVP_15_0", BCMPKT_RXPMD_FLEX_DVP_15_0},\
{"EVENT_TRACE_VECTOR_47_32", BCMPKT_RXPMD_FLEX_EVENT_TRACE_VECTOR_47_32},\
{"ENTROPY_LABEL_LOW_15_0", BCMPKT_RXPMD_FLEX_ENTROPY_LABEL_LOW_15_0},\
{"SYSTEM_OPCODE_3_0", BCMPKT_RXPMD_FLEX_SYSTEM_OPCODE_3_0},\
{"ING_TIMESTAMP_31_16", BCMPKT_RXPMD_FLEX_ING_TIMESTAMP_31_16},\
{"SYSTEM_SOURCE_15_0", BCMPKT_RXPMD_FLEX_SYSTEM_SOURCE_15_0},\
{"ENTROPY_LABEL_HIGH_3_0", BCMPKT_RXPMD_FLEX_ENTROPY_LABEL_HIGH_3_0},\
{"L2_IIF_QOS_REMARK_CTRL_3_0", BCMPKT_RXPMD_FLEX_L2_IIF_QOS_REMARK_CTRL_3_0},\
{"TIMESTAMP_CTRL_3_0", BCMPKT_RXPMD_FLEX_TIMESTAMP_CTRL_3_0},\
{"EVENT_TRACE_VECTOR_31_16", BCMPKT_RXPMD_FLEX_EVENT_TRACE_VECTOR_31_16},\
{"INGRESS_PP_PORT_7_0", BCMPKT_RXPMD_FLEX_INGRESS_PP_PORT_7_0},\
{"IFP_TS_CONTROL_ACTION_3_0", BCMPKT_RXPMD_FLEX_IFP_TS_CONTROL_ACTION_3_0},\
{"EFFECTIVE_TTL_7_0", BCMPKT_RXPMD_FLEX_EFFECTIVE_TTL_7_0},\
{"SVP_15_0", BCMPKT_RXPMD_FLEX_SVP_15_0},\
{"DROP_CODE_15_0", BCMPKT_RXPMD_FLEX_DROP_CODE_15_0},\
{"INT_PRI_3_0", BCMPKT_RXPMD_FLEX_INT_PRI_3_0},\
{"TUNNEL_PROCESSING_RESULTS_1_3_0", BCMPKT_RXPMD_FLEX_TUNNEL_PROCESSING_RESULTS_1_3_0},\
{"PARSER_VHLEN_0_15_0", BCMPKT_RXPMD_FLEX_PARSER_VHLEN_0_15_0},\
{"VLAN_TAG_PRESERVE_CTRL_1_0", BCMPKT_RXPMD_FLEX_VLAN_TAG_PRESERVE_CTRL_1_0},\
{"IFP_IOAM_ACTION_3_0", BCMPKT_RXPMD_FLEX_IFP_IOAM_ACTION_3_0},\
{"MPLS_LABEL_DECAP_COUNT_3_0", BCMPKT_RXPMD_FLEX_MPLS_LABEL_DECAP_COUNT_3_0},\
{"L3_DNAT_INDEX_15_0", BCMPKT_RXPMD_FLEX_L3_DNAT_INDEX_15_0},\
{"NAT_CTRL_3_0", BCMPKT_RXPMD_FLEX_NAT_CTRL_3_0},\
{"L3_SNAT_INDEX_15_0", BCMPKT_RXPMD_FLEX_L3_SNAT_INDEX_15_0},\
{"flex pmd fid count", BCMPKT_RXPMD_FLEX_FID_COUNT}
#define BCMPKT_RXPMD_FLEX_REASON_NAME_MAP_INIT \
{"CML_FLAGS", BCMPKT_RXPMD_FLEX_REASON_CML_FLAGS},\
{"L2_SRC_STATIC_MOVE", BCMPKT_RXPMD_FLEX_REASON_L2_SRC_STATIC_MOVE},\
{"PKT_INTEGRITY_CHECK_FAILED", BCMPKT_RXPMD_FLEX_REASON_PKT_INTEGRITY_CHECK_FAILED},\
{"PROTOCOL_PKT", BCMPKT_RXPMD_FLEX_REASON_PROTOCOL_PKT},\
{"L2_DST_LOOKUP_MISS", BCMPKT_RXPMD_FLEX_REASON_L2_DST_LOOKUP_MISS},\
{"L2_DST_LOOKUP", BCMPKT_RXPMD_FLEX_REASON_L2_DST_LOOKUP},\
{"L3_DST_LOOKUP_MISS", BCMPKT_RXPMD_FLEX_REASON_L3_DST_LOOKUP_MISS},\
{"L3_DST_LOOKUP", BCMPKT_RXPMD_FLEX_REASON_L3_DST_LOOKUP},\
{"L3_HDR_ERROR", BCMPKT_RXPMD_FLEX_REASON_L3_HDR_ERROR},\
{"L3_TTL_ERROR", BCMPKT_RXPMD_FLEX_REASON_L3_TTL_ERROR},\
{"IPMC_L3_IIF_OR_RPA_ID_CHECK_FAILED", BCMPKT_RXPMD_FLEX_REASON_IPMC_L3_IIF_OR_RPA_ID_CHECK_FAILED},\
{"LEARN_CACHE_FULL", BCMPKT_RXPMD_FLEX_REASON_LEARN_CACHE_FULL},\
{"VFP", BCMPKT_RXPMD_FLEX_REASON_VFP},\
{"IFP", BCMPKT_RXPMD_FLEX_REASON_IFP},\
{"IFP_METER", BCMPKT_RXPMD_FLEX_REASON_IFP_METER},\
{"DST_FP", BCMPKT_RXPMD_FLEX_REASON_DST_FP},\
{"SVP", BCMPKT_RXPMD_FLEX_REASON_SVP},\
{"EM_FT", BCMPKT_RXPMD_FLEX_REASON_EM_FT},\
{"IVXLT", BCMPKT_RXPMD_FLEX_REASON_IVXLT},\
{"flex reason count", BCMPKT_RXPMD_FLEX_REASON_COUNT}
#endif /* BCMPKT_RXPMD_FLEX_DEFS_H */
| 56.727848 | 134 | 0.732902 |
27f16be974ef2ec25db9ec1306de7ce441f8d1b7 | 169 | c | C | tce/newlib-1.17.0/newlib/libc/syscalls/syskill.c | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 453 | 2016-07-29T23:26:30.000Z | 2022-02-21T01:09:13.000Z | libs/newlib-2.1.0/newlib/libc/syscalls/syskill.c | ker2x/zymology | 29bf8913efbd0469ae636ba3af823158e390cfd9 | [
"MIT"
] | 79 | 2015-11-19T09:23:08.000Z | 2022-01-12T14:15:16.000Z | libs/newlib-2.1.0/newlib/libc/syscalls/syskill.c | ker2x/zymology | 29bf8913efbd0469ae636ba3af823158e390cfd9 | [
"MIT"
] | 57 | 2016-07-29T23:34:09.000Z | 2021-07-13T18:17:02.000Z | /* connector for kill */
#include <reent.h>
#include <signal.h>
int
_DEFUN (kill, (pid, sig),
int pid _AND
int sig)
{
return _kill_r (_REENT, pid, sig);
}
| 13 | 36 | 0.609467 |
7eb764f9052a09b321fb6c4dff188b3391f25210 | 614 | h | C | src/GDExtensionBind/GDnetwork.h | SueHeir/Godot-4.0-Neural-Networks | 5762c1914b338b503b0d1df87fe26c42f4400864 | [
"MIT"
] | 4 | 2021-12-30T23:35:42.000Z | 2022-03-17T21:26:26.000Z | src/GDExtensionBind/GDnetwork.h | SueHeir/Godot-4.0-Neural-Networks | 5762c1914b338b503b0d1df87fe26c42f4400864 | [
"MIT"
] | null | null | null | src/GDExtensionBind/GDnetwork.h | SueHeir/Godot-4.0-Neural-Networks | 5762c1914b338b503b0d1df87fe26c42f4400864 | [
"MIT"
] | 1 | 2022-02-16T11:40:23.000Z | 2022-02-16T11:40:23.000Z | #ifndef _G_GDNETWORK
#define _G_GDNETWORK
#include <godot_cpp/godot.hpp>
#include "../GD/GDnetwork.h"
#include "GDLayer.h"
#include "network.h"
namespace godot
{
class GDNetwork : public Network
{
GDCLASS(GDNetwork , Network)
protected:
static void _bind_methods();
public:
NN::GDNetwork *gdnetwork = nullptr;
GDNetwork();
void _init();
void add_layer(int);
void init();
GDLayer* get_layer(int);
double get_wlr();
void set_wlr(double);
double get_blr();
void set_blr(double);
Array train(Array input, Array target);
void scan(String);
};
}
#endif | 13.954545 | 43 | 0.666124 |
24f37cf702df3376db37c916fd57f2d8a27e03e0 | 1,233 | h | C | custom/common/cgen/inc/audio/mt6589_phone_720p/audio_volume_custom_default.h | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | custom/common/cgen/inc/audio/mt6589_phone_720p/audio_volume_custom_default.h | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | custom/common/cgen/inc/audio/mt6589_phone_720p/audio_volume_custom_default.h | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | #ifndef AUDIO_VOLUME_CUSTOM_DEFAULT_H
#define AUDIO_VOLUME_CUSTOM_DEFAULT_H
#define AUD_VOLUME_RING \
0, 32, 64, 96, 128, 160, 192, \
0, 32, 64, 96, 128, 132, 144, \
0, 43, 85, 128, 171, 213, 255
#define AUD_VOLUME_KEY \
0, 43, 85, 128, 171, 213, 255, \
0, 43, 85, 128, 171, 213, 255, \
0, 43, 85, 128, 171, 213, 255
#define AUD_VOLUME_MIC \
64, 255, 255, 164, 255, 255, 160, \
255, 192, 192, 176, 255, 192, 172, \
255, 208, 208, 164, 255, 208, 172
#define AUD_VOLUME_FMR \
16, 80, 112, 144, 176, 208, 240, \
16, 80, 112, 144, 176, 208, 240, \
112, 136, 160, 184, 208, 232, 255
#define AUD_VOLUME_SPH \
80, 88, 100, 116, 124, 132, 140, \
84, 96, 112, 124, 132, 140, 148, \
80, 88, 100, 116, 124, 132, 140
#define AUD_VOLUME_SID \
0, 0, 16, 0, 0, 0, 0, \
0, 0, 32, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 0
#define AUD_VOLUME_MEDIA \
100, 148, 148, 148, 128, 148, 148, \
112, 128, 140, 152, 176, 212, 255, \
112, 128, 140, 152, 176, 212, 255
#define AUD_VOLUME_MATV \
0, 32, 64, 92, 128, 160, 192, \
0, 32, 64, 92, 128, 160, 192, \
112, 136, 160, 184, 208, 232, 255
#endif
| 27.4 | 44 | 0.532036 |
f19b00e3717dbff6010c58c17e28b2f120b2e0ca | 116 | h | C | include/reg/parser.h | txus/libreg | 409694bb775d0f7dbabe7fba375c8a5a8468d412 | [
"MIT"
] | 2 | 2017-12-13T06:41:22.000Z | 2019-08-11T09:31:50.000Z | include/reg/parser.h | txus/libreg | 409694bb775d0f7dbabe7fba375c8a5a8468d412 | [
"MIT"
] | null | null | null | include/reg/parser.h | txus/libreg | 409694bb775d0f7dbabe7fba375c8a5a8468d412 | [
"MIT"
] | null | null | null | #ifndef _LIBREG_PARSER_H_
#define _LIBREG_PARSER_H_
#include <reg/syntax.h>
ASTNode* parse(char *string);
#endif
| 12.888889 | 29 | 0.775862 |
cc70b1b11cea512362236904f69ce0acb36105d0 | 182 | h | C | Example/Pods/Target Support Files/Pods-EZTamperDetection_Example/Pods-EZTamperDetection_Example-umbrella.h | effzehn/EZTamperDetection | b2ec2196edd951219e5255e43c60bc9ae231ba91 | [
"MIT"
] | 4 | 2016-03-30T16:58:41.000Z | 2019-10-05T17:44:26.000Z | Example/Pods/Target Support Files/Pods-EZTamperDetection_Example/Pods-EZTamperDetection_Example-umbrella.h | effzehn/EZTamperDetection | b2ec2196edd951219e5255e43c60bc9ae231ba91 | [
"MIT"
] | 1 | 2016-03-31T11:36:42.000Z | 2020-01-14T12:04:56.000Z | Example/Pods/Target Support Files/Pods-EZTamperDetection_Example/Pods-EZTamperDetection_Example-umbrella.h | effzehn/EZTamperDetection | b2ec2196edd951219e5255e43c60bc9ae231ba91 | [
"MIT"
] | 1 | 2022-02-26T14:35:53.000Z | 2022-02-26T14:35:53.000Z | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_EZTamperDetection_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_EZTamperDetection_ExampleVersionString[];
| 26 | 84 | 0.879121 |
44674f28972a0252a560c5b357528edea06462fc | 2,734 | h | C | PELocal-DataUI/PEListViewController.h | evanspa/PELocal-DataUI | 71046365d58995d0e43794b25b5ab4288abd3f78 | [
"MIT"
] | null | null | null | PELocal-DataUI/PEListViewController.h | evanspa/PELocal-DataUI | 71046365d58995d0e43794b25b5ab4288abd3f78 | [
"MIT"
] | null | null | null | PELocal-DataUI/PEListViewController.h | evanspa/PELocal-DataUI | 71046365d58995d0e43794b25b5ab4288abd3f78 | [
"MIT"
] | null | null | null | //
// PEListViewController.h
// PELocal-DataUI
//
// Created by Evans, Paul on 9/19/14.
// Copyright (c) 2014 Paul Evans. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "PEUIDefs.h"
#import "PEAddViewEditController.h"
@class PEListViewController;
@interface PEListViewController : UIViewController <UITableViewDataSource,
UITableViewDelegate, MBProgressHUDDelegate>
#pragma mark - Initializers
- (id)initWithClassOfDataSourceObjects:(Class)classOfDataSourceObjects
title:(NSString *)title
isPaginatedDataSource:(BOOL)isPaginatedDataSource
tableCellStyler:(PETableCellContentViewStyler)tableCellStyler
itemSelectedAction:(PEItemSelectedAction)itemSelectedAction
initialSelectedItem:(id)initialSelectedItem
addItemAction:(void(^)(PEListViewController *, PEItemAddedBlk))addItemActionBlk
cellIdentifier:(NSString *)cellIdentifier
initialObjects:(NSArray *)initialObjects
pageLoader:(PEPageLoaderBlk)pageLoaderBlk
heightForCellsBlk:(CGFloat(^)(void))heightForCellsBlk
detailViewMaker:(PEDetailViewMaker)detailViewMaker
uitoolkit:(PEUIToolkit *)uitoolkit
doesEntityBelongToThisListView:(PEDoesEntityBelongToListView)doesEntityBelongToThisListView
wouldBeIndexOfEntity:(PEWouldBeIndexOfEntity)wouldBeIndexOfEntity
isAuthenticated:(PEIsAuthenticatedBlk)isAuthenticated
isUserLoggedIn:(PEIsLoggedInBlk)isUserLoggedIn
itemChildrenCounter:(PEItemChildrenCounter)itemChildrenCounter
itemChildrenMsgsBlk:(PEItemChildrenMsgsBlk)itemChildrenMsgsBlk
itemDeleter:(PEItemDeleter)itemDeleter
itemLocalDeleter:(PEItemLocalDeleter)itemLocalDeleter
isEntityType:(BOOL)isEntityType
viewDidAppearBlk:(PEViewDidAppearBlk)viewDidAppearBlk
entityAddedNotificationName:(NSString *)entityAddedNotificationName
entityUpdatedNotificationName:(NSString *)entityUpdatedNotificationName
entityRemovedNotificationName:(NSString *)entityRemovedNotificationName;
#pragma mark - Properties
@property (nonatomic, readonly) NSMutableArray *dataSource;
@property (nonatomic) UITableView *tableView;
#pragma mark - Entity changed methods
- (BOOL)handleUpdatedEntity:(PELMMainSupport *)updatedEntity;
- (BOOL)handleRemovedEntity:(PELMMainSupport *)removedEntity;
- (BOOL)handleAddedEntity:(PELMMainSupport *)addedEntity;
@end
| 44.096774 | 105 | 0.694221 |
4f2e6724a59c5f997cb5b260e012463d9d589d7f | 1,214 | h | C | COMP310 FALL 2020/A2/queue.h | Seibaah/McGill-COMP | 9e9ead8167aead2337c8731dcbe6b541d9ee231b | [
"Unlicense"
] | null | null | null | COMP310 FALL 2020/A2/queue.h | Seibaah/McGill-COMP | 9e9ead8167aead2337c8731dcbe6b541d9ee231b | [
"Unlicense"
] | null | null | null | COMP310 FALL 2020/A2/queue.h | Seibaah/McGill-COMP | 9e9ead8167aead2337c8731dcbe6b541d9ee231b | [
"Unlicense"
] | null | null | null | #ifndef COMP310_A2_Q
#define COMP310_A2_Q
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/queue.h>
struct queue_entry {
void *data;
STAILQ_ENTRY(queue_entry) entries;
};
STAILQ_HEAD(queue, queue_entry);
struct queue queue_create() {
struct queue q = STAILQ_HEAD_INITIALIZER(q);
return q;
}
void queue_init(struct queue *q) {
STAILQ_INIT(q);
}
void queue_error() {
fprintf(stderr, "Fatal error in queue operations\n");
exit(1);
}
struct queue_entry *queue_new_node(void *data) {
struct queue_entry *entry = (struct queue_entry*) malloc(sizeof(struct queue_entry));
if(!entry) {
queue_error();
}
entry->data = data;
return entry;
}
void queue_insert_head(struct queue *q, struct queue_entry *e) {
STAILQ_INSERT_HEAD(q, e, entries);
}
void queue_insert_tail(struct queue *q, struct queue_entry *e) {
STAILQ_INSERT_TAIL(q, e, entries);
}
struct queue_entry *queue_peek_front(struct queue *q) {
return STAILQ_FIRST(q);
}
struct queue_entry *queue_pop_head(struct queue *q) {
struct queue_entry *elem = queue_peek_front(q);
if(elem) {
STAILQ_REMOVE_HEAD(q, entries);
}
return elem;
}
#endif
| 20.233333 | 89 | 0.689456 |
4de790ca9915eb5a8169a354c983af0344a6ce2c | 565 | h | C | installer/dev/pch.h | Andrea-MariaDB-2/WindowsAppSDK | 5a6b4064f7dc23a548c9f3a4065c12a5ee9f15c7 | [
"CC-BY-4.0",
"MIT"
] | 2,002 | 2020-05-19T15:16:02.000Z | 2021-06-24T13:28:05.000Z | installer/dev/pch.h | oldnewthing/WindowsAppSDK | e82f072c131807765efd84f4d55ab4de3ecbb75c | [
"CC-BY-4.0",
"MIT"
] | 1,065 | 2021-06-24T16:08:11.000Z | 2022-03-31T23:12:32.000Z | installer/dev/pch.h | oldnewthing/WindowsAppSDK | e82f072c131807765efd84f4d55ab4de3ecbb75c | [
"CC-BY-4.0",
"MIT"
] | 106 | 2020-05-19T15:20:00.000Z | 2021-06-24T15:03:57.000Z | #pragma once
#include <wil/result.h>
#include <wil/resource.h>
#include <wil/com.h>
#include <wil/win32_helpers.h>
#include <iostream>
#include <filesystem>
#include <processenv.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <WinBase.h>
#include <AppxPackaging.h>
#include <string_view>
#include <winrt/Windows.ApplicationModel.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Management.Deployment.h>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.System.h>
| 28.25 | 50 | 0.741593 |
b11f3cb1d5952cc81b60c6345ea182983e27a1bd | 5,679 | c | C | src/util/src/key_util.c | twblamer/hse | cc32a9f9991859f19dec93c0292b31f0895c4de1 | [
"Apache-2.0"
] | 1 | 2022-03-20T11:47:02.000Z | 2022-03-20T11:47:02.000Z | src/util/src/key_util.c | kyoungho-koo/hse | b792476354cb9e636ce9026f2137b1a5e6bdad1e | [
"Apache-2.0"
] | null | null | null | src/util/src/key_util.c | kyoungho-koo/hse | b792476354cb9e636ce9026f2137b1a5e6bdad1e | [
"Apache-2.0"
] | null | null | null | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright (C) 2015-2020 Micron Technology, Inc. All rights reserved.
*/
#include <hse_util/platform.h>
#include <hse_util/minmax.h>
#include <hse_util/key_util.h>
#include <hse/hse_limits.h>
/* If you change the size of struct key_immediate then you'll need to update
* key_immediate_init(), key_imm_klen(), and key_immediate_cmp_full().
*/
_Static_assert(sizeof(struct key_immediate) == 32,
"size of key_immediate changed");
/* If HSE_KVS_COUNT_MAX becomes larger than 256 then you'll need
* to update key_immediate_init() and key_immediate_index().
*/
_Static_assert(HSE_KVS_COUNT_MAX <= 256,
"HSE_KVS_COUNT_MAX larger than expected");
/* This function may look expensive, but since the size of ki_data[]
* is known, fixed, and small the optimizer won't generate any calls
* to memset nor memcpy.
*/
void
key_immediate_init(const void *key, size_t klen, u16 index, struct key_immediate *imm)
{
size_t dlen = klen;
if (dlen > KI_DLEN_MAX)
dlen = KI_DLEN_MAX;
memset(imm, 0, sizeof(*imm));
memcpy((char *)imm->ki_data + 1, key, dlen);
imm->ki_data[0] = be64toh(imm->ki_data[0]);
imm->ki_data[1] = be64toh(imm->ki_data[1]);
imm->ki_data[2] = be64toh(imm->ki_data[2]);
imm->ki_data[3] = be64toh(imm->ki_data[3]);
imm->ki_data[0] |= (u64)index << 56;
imm->ki_data[3] |= (dlen << 16) | klen;
}
s32
key_immediate_cmp_full(const struct key_immediate *imm0, const struct key_immediate *imm1)
{
/* The first comparison includes the skidx.
*/
if (imm0->ki_data[0] != imm1->ki_data[0])
return (imm0->ki_data[0] < imm1->ki_data[0]) ? -1 : 1;
if (imm0->ki_data[1] != imm1->ki_data[1])
return (imm0->ki_data[1] < imm1->ki_data[1]) ? -1 : 1;
if (imm0->ki_data[2] != imm1->ki_data[2])
return (imm0->ki_data[2] < imm1->ki_data[2]) ? -1 : 1;
/* The final comparison includes the d-length but not the k-length.
*/
if ((imm0->ki_data[3] >> 16) != (imm1->ki_data[3] >> 16))
return ((imm0->ki_data[3] >> 16) < (imm1->ki_data[3] >> 16)) ? -1 : 1;
/* If there is more to compare, tell the caller by returning S32_MIN.
* Since keys are limited to 1023 bytes at this layer, this can't
* be a return value from this function other than in this case.
*/
if (key_imm_klen(imm0) > KI_DLEN_MAX &&
key_imm_klen(imm1) > KI_DLEN_MAX)
return S32_MIN;
/* Otherwise, the result comes down to the key lengths. */
return (key_imm_klen(imm0) - key_imm_klen(imm1));
}
/* If you change the size of struct key_disc then you'll need
* to update key_disc_init() and key_disc_cmp().
*/
_Static_assert(sizeof(struct key_disc) == 32,
"size of key_disc changed");
void
key_disc_init(const void *key, size_t len, struct key_disc *kdisc)
{
if (len > sizeof(kdisc->kdisc))
len = sizeof(kdisc->kdisc);
memset(kdisc, 0, sizeof(*kdisc));
memcpy(kdisc->kdisc, key, len);
kdisc->kdisc[0] = be64toh(kdisc->kdisc[0]);
kdisc->kdisc[1] = be64toh(kdisc->kdisc[1]);
kdisc->kdisc[2] = be64toh(kdisc->kdisc[2]);
kdisc->kdisc[3] = be64toh(kdisc->kdisc[3]);
}
int
key_disc_cmp(const struct key_disc *lhs, const struct key_disc *rhs)
{
if (lhs->kdisc[0] != rhs->kdisc[0])
return (lhs->kdisc[0] < rhs->kdisc[0]) ? -1 : 1;
if (lhs->kdisc[1] != rhs->kdisc[1])
return (lhs->kdisc[1] < rhs->kdisc[1]) ? -1 : 1;
if (lhs->kdisc[2] != rhs->kdisc[2])
return (lhs->kdisc[2] < rhs->kdisc[2]) ? -1 : 1;
if (lhs->kdisc[3] != rhs->kdisc[3])
return (lhs->kdisc[3] < rhs->kdisc[3]) ? -1 : 1;
return 0;
}
BullseyeCoverageSaveOff
#if __amd64__
size_t
memlcp(const void *s1, const void *s2, size_t len)
{
size_t rc;
/* TODO: Don't directly access rcx...
*/
__asm__("movq %1, %0 \n\t" /* rc = len; */
"cld \n\t"
"movq %1, %%rcx \n\t" /* rcx = len; */
"jrcxz 1f \n\t" /* if (rcx == 0) goto 1; */
"repz \n\t" /* while (rcx-- > 0 && */
"cmpsb \n\t" /* *s1++ == *s2++) */
"je 1f \n\t" /* if (ZF) goto 1; */
"subq %%rcx, %0 \n\t" /* rc -= rcx; */
"dec %0 \n\t" /* rc -= 1; */
"1: \n\t"
: "=rax"(rc)
: "rdx"(len)
: "rdi", "rsi", "rcx", "memory");
return rc;
}
size_t
memlcpq(const void *s1, const void *s2, size_t len)
{
size_t rc;
/* TODO: Don't directly access rcx...
*/
__asm__("movq %1, %0 \n\t" /* rc = len; */
"shrq $3, %0 \n\t" /* rc /= 8; */
"cld \n\t"
"movq %0, %%rcx \n\t" /* rcx = rc; */
"jrcxz 1f \n\t" /* if (rcx == 0) goto 1; */
"repz \n\t" /* while (rcx-- > 0 && */
"cmpsq \n\t" /* *s1++ == *s2++) */
"je 1f \n\t" /* if (ZF) goto 1; */
"subq %%rcx, %0 \n\t" /* rc -= rcx; */
"dec %0 \n\t" /* rc -= 1; */
"1: \n\t"
"shlq $3, %0 \n\t" /* rc *= 8; */
: "=rax"(rc)
: "rdx"(len)
: "rdi", "rsi", "rdx", "rcx", "memory");
return rc;
}
#else
#error memlcp() not implemented for this architecture
#endif
BullseyeCoverageRestore
| 32.084746 | 90 | 0.517521 |
b123b60b0597e4dc6af0e092a537e18345b57950 | 2,433 | h | C | src/htc/RewriteControlFlow.h | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | src/htc/RewriteControlFlow.h | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | src/htc/RewriteControlFlow.h | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | /* Copyright (c) 2015 Convey Computer Corporation
*
* This file is part of the OpenHT toolset located at:
*
* https://github.com/TonyBrewer/OpenHT
*
* Use and distribution licensed under the BSD 3-clause license.
* See the LICENSE file for the complete license text.
*/
#ifndef HTC_REWRITE_CONTROL_FLOW_H
#define HTC_REWRITE_CONTROL_FLOW_H
#include <rose.h>
#include <map>
#include "HtcAttributes.h"
extern void RewriteControlFlowPreparation(SgProject *);
//
// RewriteControlFlowPass1Visitor.
//
// Flatten structured control flow into unstructured control flow.
// This eliminates structured loop nests, 'break', and 'continue'.
//
class RewriteControlFlowPass1Visitor : public AstSimpleProcessing {
private:
void visit(SgNode *S) {
switch (S->variantT()) {
case V_SgForStatement:
visitSgForStatement(dynamic_cast<SgForStatement *>(S));
break;
case V_SgWhileStmt:
visitSgWhileStmt(dynamic_cast<SgWhileStmt *>(S));
break;
case V_SgDoWhileStmt:
visitSgDoWhileStmt(dynamic_cast<SgDoWhileStmt *>(S));
break;
default:
break;
}
}
void visitSgForStatement(SgForStatement *S);
void visitSgWhileStmt(SgWhileStmt *S);
void visitSgDoWhileStmt(SgDoWhileStmt *S);
};
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
class AssignNodeOpensState : public AstBottomUpProcessing<bool>
{
public:
virtual bool evaluateSynthesizedAttribute(SgNode *n,
SynthesizedAttributesList childAttributes);
};
//
// RewriteControlFlowPass2Visitor.
//
// Flatten conditional structured control flow into unstructured control
// flow. This eliminates if-then-else and switch statements.
//
class RewriteControlFlowPass2Visitor : public AstSimpleProcessing {
public:
RewriteControlFlowPass2Visitor(SgProject *project) {
AssignNodeOpensState v;
v.traverseInputFiles(project);
}
private:
RewriteControlFlowPass2Visitor();
void visit(SgNode *S) {
switch (S->variantT()) {
case V_SgIfStmt:
visitSgIfStmt(dynamic_cast<SgIfStmt *>(S));
break;
case V_SgSwitchStatement:
visitSgSwitchStatement(dynamic_cast<SgSwitchStatement *>(S));
break;
default:
break;
}
}
void visitSgIfStmt(SgIfStmt *S);
void visitSgSwitchStatement(SgSwitchStatement *S);
};
#endif // HTC_REWRITE_CONTROL_FLOW_H
| 23.394231 | 75 | 0.685984 |
7f47c3fa5f23f661ae05a9d4b3a451add4487dc5 | 1,644 | h | C | api/core/react-native/LibLedgerCore/ios/Sources/RCTCoreLGWalletPool.h | marpme/lib-ledger-core | df688cf1923049ae5450b9e1e90c3223b1bc96bf | [
"MIT"
] | null | null | null | api/core/react-native/LibLedgerCore/ios/Sources/RCTCoreLGWalletPool.h | marpme/lib-ledger-core | df688cf1923049ae5450b9e1e90c3223b1bc96bf | [
"MIT"
] | null | null | null | api/core/react-native/LibLedgerCore/ios/Sources/RCTCoreLGWalletPool.h | marpme/lib-ledger-core | df688cf1923049ae5450b9e1e90c3223b1bc96bf | [
"MIT"
] | null | null | null | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from wallet_pool.djinni
#import "LGBlockCallback.h"
#import "LGCurrency.h"
#import "LGCurrencyCallback.h"
#import "LGCurrencyListCallback.h"
#import "LGDatabaseBackend.h"
#import "LGDynamicObject.h"
#import "LGErrorCodeCallback.h"
#import "LGEventBus.h"
#import "LGHttpClient.h"
#import "LGI32Callback.h"
#import "LGLogPrinter.h"
#import "LGLogger.h"
#import "LGPathResolver.h"
#import "LGPreferences.h"
#import "LGRandomNumberGenerator.h"
#import "LGThreadDispatcher.h"
#import "LGWalletCallback.h"
#import "LGWalletListCallback.h"
#import "LGWalletPool.h"
#import "LGWebSocketClient.h"
#import "RCTCoreLGBlockCallback.h"
#import "RCTCoreLGCurrency.h"
#import "RCTCoreLGCurrencyCallback.h"
#import "RCTCoreLGCurrencyListCallback.h"
#import "RCTCoreLGDatabaseBackend.h"
#import "RCTCoreLGDynamicObject.h"
#import "RCTCoreLGErrorCodeCallback.h"
#import "RCTCoreLGEventBus.h"
#import "RCTCoreLGHttpClient.h"
#import "RCTCoreLGI32Callback.h"
#import "RCTCoreLGLogPrinter.h"
#import "RCTCoreLGLogger.h"
#import "RCTCoreLGPathResolver.h"
#import "RCTCoreLGPreferences.h"
#import "RCTCoreLGRandomNumberGenerator.h"
#import "RCTCoreLGThreadDispatcher.h"
#import "RCTCoreLGWalletCallback.h"
#import "RCTCoreLGWalletListCallback.h"
#import "RCTCoreLGWalletPool.h"
#import "RCTCoreLGWebSocketClient.h"
#import <Foundation/Foundation.h>
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
/**Class respresenting a pool of wallets */
@interface RCTCoreLGWalletPool : NSObject <RCTBridgeModule>
@property (nonatomic, strong) NSMutableDictionary *objcImplementations;
@end
| 31.018868 | 71 | 0.805353 |
9a7a2445a86f9497d74670c3955b70dcaf52b272 | 34 | h | C | tools/clang/test/Index/Inputs/base_module_needs_vfs.h | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | tools/clang/test/Index/Inputs/base_module_needs_vfs.h | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | tools/clang/test/Index/Inputs/base_module_needs_vfs.h | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | void base_module_needs_vfs(void);
| 17 | 33 | 0.852941 |
d6355e6671b3bdbce060ad17c16948e02643a867 | 1,425 | c | C | Example Code/C/rgb_led/ws2812.c | fapplin/MAKER-PI-PICO | 33bac308b6c45fdb43173c0417d15a8ebe7256f8 | [
"MIT"
] | 1 | 2021-04-23T04:59:20.000Z | 2021-04-23T04:59:20.000Z | Example Code/C/rgb_led/ws2812.c | fapplin/MAKER-PI-PICO | 33bac308b6c45fdb43173c0417d15a8ebe7256f8 | [
"MIT"
] | null | null | null | Example Code/C/rgb_led/ws2812.c | fapplin/MAKER-PI-PICO | 33bac308b6c45fdb43173c0417d15a8ebe7256f8 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdio.h>
#include <stdlib.h>
#include "pico/stdlib.h"
#include "hardware/pio.h"
#include "hardware/clocks.h"
#include "ws2812.pio.h"
static inline void put_pixel(uint32_t pixel_grb) {
pio_sm_put_blocking(pio0, 0, pixel_grb << 8u);
} //end put_pixel
static inline uint32_t urgb_u32(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)(r) << 8) |
((uint32_t)(g) << 16) |
(uint32_t)(b);
} //end urgb_u32
const int PIN_TX = 28;
int main()
{
stdio_init_all();
PIO pio = pio0;
int sm = 0;
uint offset = pio_add_program(pio, &ws2812_program);
ws2812_program_init(pio, sm, offset, PIN_TX, 800000, true);
put_pixel(urgb_u32(0xff, 0, 0)); // Red
sleep_ms(500);
put_pixel(urgb_u32(0, 0xff, 0)); // Green
sleep_ms(500);
put_pixel(urgb_u32(0, 0, 0xff)); // Blue
sleep_ms(500);
put_pixel(urgb_u32(0xff, 0xff, 0)); // Purple
sleep_ms(500);
put_pixel(urgb_u32(0, 0xff, 0xff)); // Cyan
sleep_ms(500);
put_pixel(urgb_u32(0xff, 0xff, 0xff)); // White
sleep_ms(500);
put_pixel(urgb_u32(0, 0, 0)); // Black or off
sleep_ms(500);
sleep_ms(1000);
// Clear all pixels
for (int i = 0; i <= 60; i++) {
put_pixel(urgb_u32(0, 0, 0)); // Black or off
} //end for
sleep_ms(1000);
} //end main | 23.75 | 66 | 0.614035 |
965edee76ccbd3bccb1a8041e4486032026632db | 6,476 | h | C | src/hmm/hmm-topology.h | vimalmanohar/kaldi-tfmask | 592c784f582e3d19a8cc1fe1071eac4c7e0c4833 | [
"Apache-2.0"
] | 2 | 2017-05-02T15:45:03.000Z | 2017-07-06T06:34:51.000Z | src/hmm/hmm-topology.h | vimalmanohar/kaldi-tfmask | 592c784f582e3d19a8cc1fe1071eac4c7e0c4833 | [
"Apache-2.0"
] | null | null | null | src/hmm/hmm-topology.h | vimalmanohar/kaldi-tfmask | 592c784f582e3d19a8cc1fe1071eac4c7e0c4833 | [
"Apache-2.0"
] | null | null | null | // hmm/hmm-topology.h
// Copyright 2009-2011 Microsoft Corporation
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_HMM_HMM_TOPOLOGY_H_
#define KALDI_HMM_HMM_TOPOLOGY_H_
#include "base/kaldi-common.h"
#include "tree/context-dep.h"
#include "util/const-integer-set.h"
namespace kaldi {
/// \addtogroup hmm_group
/// @{
/*
// The following would be the text form for the "normal" HMM topology.
// Note that the first state is the start state, and the final state,
// which must have no output transitions and must be nonemitting, has
// an exit probability of one (no other state can have nonzero exit
// probability; you can treat the transition probability to the final
// state as an exit probability).
// Note also that it's valid to omit the "<PdfClass>" entry of the <State>, which
// will mean we won't have a pdf on that state [non-emitting state]. This is equivalent
// to setting the <PdfClass> to -1. We do this normally just for the final state.
// The Topology object can have multiple <TopologyEntry> blocks.
// This is useful if there are multiple types of topology in the system.
<Topology>
<TopologyEntry>
<ForPhones> 1 2 3 4 5 6 7 8 </ForPhones>
<State> 0 <PdfClass> 0
<Transition> 0 0.5
<Transition> 1 0.5
</State>
<State> 1 <PdfClass> 1
<Transition> 1 0.5
<Transition> 2 0.5
</State>
<State> 2 <PdfClass> 2
<Transition> 2 0.5
<Transition> 3 0.5
<Final> 0.5
</State>
<State> 3
</State>
</TopologyEntry>
</Topology>
*/
// kNoPdf is used where pdf_class or pdf would be used, to indicate,
// none is there. Mainly useful in skippable models, but also used
// for end states.
// A caveat with nonemitting states is that their out-transitions
// are not trainable, due to technical issues with the way
// we decided to accumulate the stats. Any transitions arising from (*)
// HMM states with "kNoPdf" as the label are second-class transitions,
// They do not have "transition-states" or "transition-ids" associated
// with them. They are used to create the FST version of the
// HMMs, where they lead to epsilon arcs.
// (*) "arising from" is a bit of a technical term here, due to the way
// (if reorder == true), we put the transition-id associated with the
// outward arcs of the state, on the input transition to the state.
/// A constant used in the HmmTopology class as the \ref pdf_class "pdf-class"
/// kNoPdf, which is used when a HMM-state is nonemitting (has no associated
/// PDF).
static const int32 kNoPdf = -1;
/// A class for storing topology information for phones. See \ref hmm for context.
/// This object is sometimes accessed in a file by itself, but more often
/// as a class member of the Transition class (this is for convenience to reduce
/// the number of files programs have to access).
class HmmTopology {
public:
/// A structure defined inside HmmTopology to represent a HMM state.
struct HmmState {
/// The \ref pdf_class pdf-class, typically 0, 1 or 2 (the same as the HMM-state index),
/// but may be different to enable us to hardwire sharing of state, and may be
/// equal to \ref kNoPdf == -1 in order to specify nonemitting states (unusual).
int32 pdf_class;
/// A list of transitions. The first member of each pair is the index of
/// the next HmmState, and the second is the default transition probability
/// (before training).
std::vector<std::pair<int32, BaseFloat> > transitions;
explicit HmmState(int32 p): pdf_class(p) { }
bool operator == (const HmmState &other) const {
return (pdf_class == other.pdf_class && transitions == other.transitions);
}
HmmState(): pdf_class(-1) { }
};
/// TopologyEntry is a typedef that represents the topology of
/// a single (prototype) state.
typedef std::vector<HmmState> TopologyEntry;
void Read(std::istream &is, bool binary);
void Write(std::ostream &os, bool binary) const;
// Checks that the object is valid, and throw exception otherwise.
void Check();
/// Returns the topology entry (i.e. vector of HmmState) for this phone;
/// will throw exception if phone not covered by the topology.
const TopologyEntry &TopologyForPhone(int32 phone) const;
/// Returns the number of \ref pdf_class "pdf-classes" for this phone;
/// throws exception if phone not covered by this topology.
int32 NumPdfClasses(int32 phone) const;
/// Returns a reference to a sorted, unique list of phones covered by
/// the topology (these phones will be positive integers, and usually
/// contiguous and starting from one but the toolkit doesn't assume
/// they are contiguous).
const std::vector<int32> &GetPhones() const { return phones_; };
/// Outputs a vector of int32, indexed by phone, that gives the
/// number of \ref pdf_class pdf-classes for the phones; this is
/// used by tree-building code such as BuildTree().
void GetPhoneToNumPdfClasses(std::vector<int32> *phone2num_pdf_classes) const;
HmmTopology() {}
/// Copy constructor
explicit HmmTopology(const HmmTopology &other): phones_(other.phones_),
phone2idx_(other.phone2idx_),
entries_(other.entries_) { }
bool operator == (const HmmTopology &other) const {
return phones_ == other.phones_ && phone2idx_ == other.phone2idx_
&& entries_ == other.entries_;
}
private:
std::vector<int32> phones_; // list of all phones we have topology for. Sorted, uniq. no epsilon (zero) phone.
std::vector<int32> phone2idx_; // map from phones to indexes into the entries vector (or -1 for not present).
std::vector<TopologyEntry> entries_;
HmmTopology &operator =(const HmmTopology &other); // Disallow assignment.
};
/// @} end "addtogroup hmm_group"
} // end namespace kaldi
#endif
| 37.433526 | 115 | 0.705683 |
a96af0290b256e29963a1916e34b5c871728b891 | 974 | c | C | third_party/gofrontend/libgo/runtime/go-type-string.c | prattmic/llgo-embedded | 41cfecea0e1e9132930c497cf38321df4bb9ae91 | [
"MIT"
] | null | null | null | third_party/gofrontend/libgo/runtime/go-type-string.c | prattmic/llgo-embedded | 41cfecea0e1e9132930c497cf38321df4bb9ae91 | [
"MIT"
] | null | null | null | third_party/gofrontend/libgo/runtime/go-type-string.c | prattmic/llgo-embedded | 41cfecea0e1e9132930c497cf38321df4bb9ae91 | [
"MIT"
] | null | null | null | /* go-type-string.c -- hash and equality string functions.
Copyright 2009 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file. */
#include "runtime.h"
#include "go-type.h"
#include "go-string.h"
/* A string hash function for a map. */
uintptr_t
__go_type_hash_string (const void *vkey,
uintptr_t key_size __attribute__ ((unused)))
{
uintptr_t ret;
const String *key;
intgo len;
intgo i;
const byte *p;
ret = 5381;
key = (const String *) vkey;
len = key->len;
for (i = 0, p = key->str; i < len; i++, p++)
ret = ret * 33 + *p;
return ret;
}
/* A string equality function for a map. */
_Bool
__go_type_equal_string (const void *vk1, const void *vk2,
uintptr_t key_size __attribute__ ((unused)))
{
const String *k1;
const String *k2;
k1 = (const String *) vk1;
k2 = (const String *) vk2;
return __go_ptr_strings_equal (k1, k2);
}
| 22.136364 | 58 | 0.656057 |
a9c840ac457c58619e63ff4408712a7ac22df8ba | 8,647 | h | C | Kernel/OSTask.h | camel5/TINIUX | fa1054b09914ac23faf0de89dcff29862daa10b7 | [
"MIT"
] | null | null | null | Kernel/OSTask.h | camel5/TINIUX | fa1054b09914ac23faf0de89dcff29862daa10b7 | [
"MIT"
] | null | null | null | Kernel/OSTask.h | camel5/TINIUX | fa1054b09914ac23faf0de89dcff29862daa10b7 | [
"MIT"
] | 1 | 2019-06-17T07:34:05.000Z | 2019-06-17T07:34:05.000Z | /**********************************************************************************************************
TINIUX - A tiny and efficient embedded real time operating system (RTOS)
Copyright (C) SenseRate.com All rights reserved.
http://www.tiniux.org -- Documentation, latest information, license and contact details.
http://www.tiniux.com -- Commercial support, development, porting, licensing and training services.
--------------------------------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------------------------------
Notice of Export Control Law
--------------------------------------------------------------------------------------------------------
TINIUX may be subject to applicable export control laws and regulations, which might
include those applicable to TINIUX of U.S. and the country in which you are located.
Import, export and usage of TINIUX in any manner by you shall be in compliance with such
applicable export control laws and regulations.
***********************************************************************************************************/
#ifndef __OS_TASK_H_
#define __OS_TASK_H_
#include "OSType.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
eTaskStateRuning = 0,
eTaskStateReady ,
eTaskStateSuspended ,
eTaskStateBlocked ,
eTaskStateRecycle ,
eTaskStateNum
}eOSTaskState_t;
#define SCHEDULER_LOCKED ( ( sOSBase_t ) 0 )
#define SCHEDULER_NOT_STARTED ( ( sOSBase_t ) 1 )
#define SCHEDULER_RUNNING ( ( sOSBase_t ) 2 )
#define OSIntLock() FitIntLock()
#define OSIntUnlock() FitIntUnlock()
#define OSIntMaskFromISR() FitIntMaskFromISR()
#define OSIntUnmaskFromISR( x ) FitIntUnmaskFromISR( x )
#define OSIntMask() FitIntMask()
#define OSIntUnmask( x ) FitIntUnmask( x )
#define OSSchedule() FitSchedule()
#define OSScheduleFromISR( b ) FitScheduleFromISR( b )
#define OSIsInsideISR() FitIsInsideISR()
/*
* Task control block. A task control block (TCB) is allocated for each task,
* and stores task state information, including a pointer to the task's context
* (the task's run time environment, including register values)
*/
typedef struct OSTaskControlBlock
{
volatile uOSStack_t* puxTopOfStack; /*< Points to the location of the last item placed on the task stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */
tOSListItem_t tTaskListItem; /*< Used to reference a task from an Ready/Timer/Suspended/Recycle list. */
tOSListItem_t tEventListItem; /*< Used to reference a task from an PendingReady/Event list. */
uOSBase_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */
uOSStack_t* puxStartStack; /*< Points to the start of the stack. */
char pcTaskName[ OSNAME_MAX_LEN ];
#if ( OSSTACK_GROWTH > 0 )
uOSBase_t* puxEndOfStack; /*< Points to the end of the stack on architectures where the stack grows up from low memory. */
#endif
#if ( OS_MUTEX_ON == 1 )
uOSBase_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */
uOSBase_t uxMutexHoldNum;
#endif
sOSBase_t xID;
#if ( OS_TASK_SIGNAL_ON == 1 )
uOSBase_t uxSigType; /*< Task signal type: SEM_SIG MSG_SIG MSG_SIG_OVERWRITE. */
uOSBase_t uxSigState; /*< Task signal state: NotWaiting Waiting GotSignal. */
sOSBase_t xSigValue; /*< Task signal value: Msg or count. */
#endif
} tOSTCB_t;
typedef tOSTCB_t* OSTaskHandle_t;
uOS16_t OSStart( void ) TINIUX_FUNCTION;
uOSTick_t OSGetTickCount( void ) TINIUX_FUNCTION;
uOSTick_t OSGetTickCountFromISR( void ) TINIUX_FUNCTION;
void OSScheduleLock( void ) TINIUX_FUNCTION;
uOSBool_t OSScheduleUnlock( void ) TINIUX_FUNCTION;
sOSBase_t OSGetScheduleState( void ) TINIUX_FUNCTION;
OSTaskHandle_t OSGetCurrentTaskHandle( void ) TINIUX_FUNCTION;
OSTaskHandle_t OSTaskCreate(OSTaskFunction_t pxTaskFunction,
void* pvParameter,
const uOS16_t usStackDepth,
uOSBase_t uxPriority,
sOS8_t* pcTaskName) TINIUX_FUNCTION;
void OSTaskDelete( OSTaskHandle_t xTaskToDelete ) TINIUX_FUNCTION;
void OSTaskSleep( const uOSTick_t uxTicksToSleep ) TINIUX_FUNCTION;
sOSBase_t OSTaskSetID(OSTaskHandle_t const TaskHandle, sOSBase_t xID) TINIUX_FUNCTION;
sOSBase_t OSTaskGetID(OSTaskHandle_t const TaskHandle) TINIUX_FUNCTION;
void OSTaskListEventAdd( tOSList_t * const ptEventList, const uOSTick_t uxTicksToWait ) TINIUX_FUNCTION;
uOSBool_t OSTaskListEventRemove( const tOSList_t * const ptEventList ) TINIUX_FUNCTION;
uOSBool_t OSTaskIncrementTick( void ) TINIUX_FUNCTION;
void OSTaskNeedSchedule( void ) TINIUX_FUNCTION;
void OSTaskSwitchContext( void ) TINIUX_FUNCTION;
void OSTaskSetTimeOutState( tOSTimeOut_t * const ptTimeOut ) TINIUX_FUNCTION;
uOSBool_t OSTaskGetTimeOutState( tOSTimeOut_t * const ptTimeOut, uOSTick_t * const puxTicksToWait ) TINIUX_FUNCTION;
void OSTaskSuspend( OSTaskHandle_t TaskHandle ) TINIUX_FUNCTION;
void OSTaskResume( OSTaskHandle_t TaskHandle ) TINIUX_FUNCTION;
sOSBase_t OSTaskResumeFromISR( OSTaskHandle_t TaskHandle ) TINIUX_FUNCTION;
#if ( OS_MUTEX_ON == 1 )
void * OSTaskGetMutexHolder( void ) TINIUX_FUNCTION;
uOSBool_t OSTaskPriorityInherit( OSTaskHandle_t const MutexHolderTaskHandle ) TINIUX_FUNCTION;
uOSBool_t OSTaskPriorityDisinherit( OSTaskHandle_t const MutexHolderTaskHandle ) TINIUX_FUNCTION;
void OSTaskPriorityDisinheritAfterTimeout( OSTaskHandle_t const MutexHolderTaskHandle, uOSBase_t uxHighestPriorityWaitingTask ) TINIUX_FUNCTION;
#endif /* OS_MUTEX_ON */
#if ( OS_TIMER_ON == 1 )
void OSTaskBlockAndDelay( tOSList_t * const ptEventList, uOSTick_t uxTicksToWait, uOSBool_t bNeedSuspend ) TINIUX_FUNCTION;
#endif /* (OS_TIMER_ON==1) */
#if ( OS_LOWPOWER_ON == 1 )
void OSTaskFixTickCount( const uOSTick_t uxTicksToFix );
#endif //OS_LOWPOWER_ON
#if ( OS_TASK_SIGNAL_ON == 1 )
uOSBool_t OSTaskSignalWait( uOSTick_t const uxTicksToWait) TINIUX_FUNCTION;
uOSBool_t OSTaskSignalEmit( OSTaskHandle_t const TaskHandle ) TINIUX_FUNCTION;
uOSBool_t OSTaskSignalEmitFromISR( OSTaskHandle_t const TaskHandle ) TINIUX_FUNCTION;
uOSBool_t OSTaskSignalWaitMsg( sOSBase_t xSigValue, uOSTick_t const uxTicksToWait) TINIUX_FUNCTION;
uOSBool_t OSTaskSignalEmitMsg( OSTaskHandle_t const TaskHandle, sOSBase_t const xSigValue, uOSBool_t bOverWrite ) TINIUX_FUNCTION;
uOSBool_t OSTaskSignalEmitMsgFromISR( OSTaskHandle_t const TaskHandle, sOSBase_t const xSigValue, uOSBool_t bOverWrite ) TINIUX_FUNCTION;
uOSBool_t OSTaskSignalClear( OSTaskHandle_t const TaskHandle ) TINIUX_FUNCTION;
#endif
#ifdef __cplusplus
}
#endif
#endif //__OS_TASK_H_
| 50.567251 | 160 | 0.694461 |
108c4b18fa8c07a540bfebeedd5f9b8ff1858eb0 | 1,815 | h | C | include/s1ap/s1ap_msg_codes.h | sindack/Nucleus | f5ce6c446afd78c06b4a402d12ca32ce410dd358 | [
"Apache-2.0"
] | null | null | null | include/s1ap/s1ap_msg_codes.h | sindack/Nucleus | f5ce6c446afd78c06b4a402d12ca32ce410dd358 | [
"Apache-2.0"
] | 1 | 2020-05-21T00:21:52.000Z | 2020-05-21T00:21:52.000Z | include/s1ap/s1ap_msg_codes.h | thakurajayL/Nucleus | be709d9a7ac1d6181c0bdcf418913af8b12667d1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-present Open Networking Foundation
* Copyright (c) 2003-2018, Great Software Laboratory Pvt. Ltd.
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __S1AP_MSG_CODES_H_
#define __S1AP_MSG_CODES_H_
/****S1AP Procedude codes****/
#define S1AP_SETUP_REQUEST_CODE 17
#define S1AP_INITIAL_UE_MSG_CODE 12
#define S1AP_UE_CONTEXT_RELEASE_REQUEST_CODE 18
#define S1AP_UE_CONTEXT_RELEASE_CODE 23
#define S1AP_HANDOVER_REQUIRED_CODE 0
#define S1AP_HANDOVER_RESOURCE_ALLOCATION_CODE 1
#define S1AP_HANDOVER_NOTIFY_CODE 2
#define S1AP_ENB_STATUS_TRANSFER_CODE 24
#define S1AP_HANDOVER_CANCEL_CODE 4
#define S1AP_ERAB_SETUP_CODE 5
#define S1AP_ERAB_MODIFICATION_INDICATION_CODE 50
/*uplink NAS Transport*/
#define S1AP_UL_NAS_TX_MSG_CODE 13
#define S1AP_INITIAL_CTX_RESP_CODE 9
/*S1AP Protocol IE types*/
#define S1AP_IE_GLOBAL_ENB_ID 59
#define S1AP_IE_ENB_NAME 60
#define S1AP_IE_SUPPORTED_TAS 64
#define S1AP_IE_DEF_PAGING_DRX 137
#define S1AP_IE_MMENAME 61
#define S1AP_IE_SERVED_GUMMEIES 105
#define S1AP_IE_REL_MME_CAPACITY 87
#define S1AP_IE_MME_UE_ID 0
#define S1AP_IE_CAUSE 2
#define S1AP_IE_ENB_UE_ID 8
#define S1AP_IE_NAS_PDU 26
#define S1AP_IE_TAI 67
#define S1AP_IE_UTRAN_CGI 100
#define S1AP_IE_S_TMSI 96
#define S1AP_IE_RRC_EST_CAUSE 134
#define S1AP_ERAB_SETUP_CTX_SUR 51
#define S1AP_IE_HANDOVER_TYPE 1
#define S1AP_IE_TARGET_ID 4
#define S1AP_IE_SOURCE_TOTARGET_TRANSPARENTCONTAINER 104
#define S1AP_IE_E_RAB_ADMITTED 18
#define S1AP_IE_E_RAB_SETUP_LIST_BEARER_SU_RES 28
#define S1AP_IE_E_RAB_FAILED_TO_SETUP_LIST_BEARER_SU_RES 29
#define S1AP_IE_TARGET_TOSOURCE_TRANSPARENTCONTAINER 123
#define S1AP_IE_ENB_STATUS_TRANSFER_TRANSPARENTCONTAINER 90
#define S1AP_IE_E_RAB_TO_BE_MOD_LIST_BEARER_MOD_IND 199
#endif /*__S1AP_MSG_CODES*/
| 30.762712 | 63 | 0.855647 |
340c4232b6d46d06071ea13c13f8f34f8dab3448 | 74 | c | C | ex/incbf_sub.c | 0noketa/tobf | ee34d4ccf33d3824db6a90939145264422840837 | [
"MIT"
] | 1 | 2021-04-05T20:27:12.000Z | 2021-04-05T20:27:12.000Z | ex/incbf_sub.c | 0noketa/tobf | ee34d4ccf33d3824db6a90939145264422840837 | [
"MIT"
] | null | null | null | ex/incbf_sub.c | 0noketa/tobf | ee34d4ccf33d3824db6a90939145264422840837 | [
"MIT"
] | null | null | null | #include "c2bf.inc"
c_func(i, j, k) {
return i * 100 + j * 10 + k;
}
| 12.333333 | 32 | 0.5 |
a2b0e15e999a0dcf7e2448801a75495ab88cbf58 | 7,452 | c | C | src/test_opengl/main.c | ezaf/ezmake | 7ab33e3e3fc7c3f5d09fe7064184a65cb68de4fd | [
"Zlib"
] | null | null | null | src/test_opengl/main.c | ezaf/ezmake | 7ab33e3e3fc7c3f5d09fe7064184a65cb68de4fd | [
"Zlib"
] | 4 | 2018-08-15T11:18:40.000Z | 2018-12-23T00:48:11.000Z | src/test_opengl/main.c | ezaf/ezmake | 7ab33e3e3fc7c3f5d09fe7064184a65cb68de4fd | [
"Zlib"
] | null | null | null | //========================================================================
// Simple GLFW example
// Copyright (c) Camilla Löwy <elmindreda@glfw.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
//! [code]
// Near-identical copy of
// https://github.com/glfw/glfw/blob/master/examples/simple.c
// Only changed glad -> glew
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// Relevant segments manually copied from
// https://github.com/datenwolf/linmath.h/blob/master/linmath.h
//#include "linmath.h"
#include <stdlib.h>
#include <stdio.h>
#define LINMATH_H_DEFINE_VEC(n) \
typedef float vec##n[n]; \
static inline void vec##n##_add(vec##n r, vec##n const a, vec##n const b) \
{ \
int i; \
for(i=0; i<n; ++i) \
r[i] = a[i] + b[i]; \
} \
static inline void vec##n##_sub(vec##n r, vec##n const a, vec##n const b) \
{ \
int i; \
for(i=0; i<n; ++i) \
r[i] = a[i] - b[i]; \
} \
static inline void vec##n##_scale(vec##n r, vec##n const v, float const s) \
{ \
int i; \
for(i=0; i<n; ++i) \
r[i] = v[i] * s; \
} \
static inline float vec##n##_mul_inner(vec##n const a, vec##n const b) \
{ \
float p = 0.; \
int i; \
for(i=0; i<n; ++i) \
p += b[i]*a[i]; \
return p; \
} \
static inline float vec##n##_len(vec##n const v) \
{ \
return sqrtf(vec##n##_mul_inner(v,v)); \
} \
static inline void vec##n##_norm(vec##n r, vec##n const v) \
{ \
float k = 1.0 / vec##n##_len(v); \
vec##n##_scale(r, v, k); \
} \
static inline void vec##n##_min(vec##n r, vec##n a, vec##n b) \
{ \
int i; \
for(i=0; i<n; ++i) \
r[i] = a[i]<b[i] ? a[i] : b[i]; \
} \
static inline void vec##n##_max(vec##n r, vec##n a, vec##n b) \
{ \
int i; \
for(i=0; i<n; ++i) \
r[i] = a[i]>b[i] ? a[i] : b[i]; \
}
LINMATH_H_DEFINE_VEC(2)
LINMATH_H_DEFINE_VEC(3)
LINMATH_H_DEFINE_VEC(4)
typedef vec4 mat4x4[4];
static inline void mat4x4_identity(mat4x4 M)
{
int i, j;
for(i=0; i<4; ++i)
for(j=0; j<4; ++j)
M[i][j] = i==j ? 1.f : 0.f;
}
static inline void mat4x4_dup(mat4x4 M, mat4x4 N)
{
int i, j;
for(i=0; i<4; ++i)
for(j=0; j<4; ++j)
M[i][j] = N[i][j];
}
static inline void mat4x4_mul(mat4x4 M, mat4x4 a, mat4x4 b)
{
mat4x4 temp;
int k, r, c;
for(c=0; c<4; ++c) for(r=0; r<4; ++r) {
temp[c][r] = 0.f;
for(k=0; k<4; ++k)
temp[c][r] += a[k][r] * b[c][k];
}
mat4x4_dup(M, temp);
}
static inline void mat4x4_rotate_Z(mat4x4 Q, mat4x4 M, float angle)
{
float s = sinf(angle);
float c = cosf(angle);
mat4x4 R = {
{ c, s, 0.f, 0.f},
{ -s, c, 0.f, 0.f},
{ 0.f, 0.f, 1.f, 0.f},
{ 0.f, 0.f, 0.f, 1.f}
};
mat4x4_mul(Q, M, R);
}
static inline void mat4x4_ortho(mat4x4 M, float l, float r, float b, float t, float n, float f)
{
M[0][0] = 2.f/(r-l);
M[0][1] = M[0][2] = M[0][3] = 0.f;
M[1][1] = 2.f/(t-b);
M[1][0] = M[1][2] = M[1][3] = 0.f;
M[2][2] = -2.f/(f-n);
M[2][0] = M[2][1] = M[2][3] = 0.f;
M[3][0] = -(r+l)/(r-l);
M[3][1] = -(t+b)/(t-b);
M[3][2] = -(f+n)/(f-n);
M[3][3] = 1.f;
}
static const struct
{
float x, y;
float r, g, b;
} vertices[3] =
{
{ -0.6f, -0.4f, 1.f, 0.f, 0.f },
{ 0.6f, -0.4f, 0.f, 1.f, 0.f },
{ 0.f, 0.6f, 0.f, 0.f, 1.f }
};
static const char* vertex_shader_text =
"#version 110\n"
"uniform mat4 MVP;\n"
"attribute vec3 vCol;\n"
"attribute vec2 vPos;\n"
"varying vec3 color;\n"
"void main()\n"
"{\n"
" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"
" color = vCol;\n"
"}\n";
static const char* fragment_shader_text =
"#version 110\n"
"varying vec3 color;\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(color, 1.0);\n"
"}\n";
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
int main(void)
{
GLFWwindow* window;
GLuint vertex_buffer, vertex_shader, fragment_shader, program;
GLint mvp_location, vpos_location, vcol_location;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
glfwSwapInterval(1);
// NOTE: OpenGL error checks have been omitted for brevity
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
glCompileShader(vertex_shader);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
glCompileShader(fragment_shader);
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
mvp_location = glGetUniformLocation(program, "MVP");
vpos_location = glGetAttribLocation(program, "vPos");
vcol_location = glGetAttribLocation(program, "vCol");
glEnableVertexAttribArray(vpos_location);
glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*) 0);
glEnableVertexAttribArray(vcol_location);
glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE,
sizeof(vertices[0]), (void*) (sizeof(float) * 2));
while (!glfwWindowShouldClose(window))
{
float ratio;
int width, height;
mat4x4 m, p, mvp;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
mat4x4_identity(m);
mat4x4_rotate_Z(m, m, (float) glfwGetTime());
mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 1.f, -1.f);
mat4x4_mul(mvp, p, m);
glUseProgram(program);
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
//! [code]
| 26.147368 | 95 | 0.611648 |
c86bd128e24603d6cd642e5313b77b0705cf8cdd | 5,133 | h | C | Plugins/org.blueberry.core.runtime/src/berryWeakPointer.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.core.runtime/src/berryWeakPointer.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.core.runtime/src/berryWeakPointer.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __BERRY_WEAK_POINTER_H__
#define __BERRY_WEAK_POINTER_H__
#include <exception>
#include <iostream>
#include "berryMessage.h"
#include "berrySmartPointer.h"
namespace berry
{
/** \class WeakPointer
* \brief implements a WeakPointer class to deal with circular reference problems.
*
*
* The WeakPointer class implements smart pointer semantics without increasing the reference count.
* It registers itself at the Object it points to in order to get notified of its destruction and sets its internal pointer to 0.
* To be able to access an object through a weak pointer, you either use SmartPointer(const WeakPointer&)
* or the WeakPointer::Lock() method. The first approach throws a BadWeakPointerException if
* the object has been destroyed, the second returns an empty SmartPointer.
*/
template<class TObjectType>
class WeakPointer
{
public:
typedef TObjectType ObjectType;
/** Default Constructor */
WeakPointer() :
m_Pointer(nullptr)
{
}
/** Constructor */
template<class Other>
explicit WeakPointer(berry::SmartPointer<Other> sptr) :
m_Pointer(dynamic_cast<ObjectType*>(sptr.GetPointer()))
{
if (m_Pointer)
m_Pointer->AddDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
}
/** constructor */
template<class Other>
WeakPointer(const WeakPointer<Other>& p) :
m_Pointer(dynamic_cast<ObjectType*>(p.m_Pointer))
{
if (m_Pointer)
m_Pointer->AddDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
}
/** Copy constructor */
WeakPointer(const WeakPointer& p) :
m_Pointer(p.m_Pointer)
{
if (m_Pointer)
m_Pointer->AddDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
}
template<class Other>
WeakPointer &operator =(const SmartPointer<Other> &r)
{
if (m_Pointer)
m_Pointer->RemoveDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
m_Pointer = const_cast<ObjectType*>(r.GetPointer());
if (m_Pointer)
m_Pointer->AddDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
return *this;
}
WeakPointer& operator=(const WeakPointer& other)
{
if (m_Pointer)
m_Pointer->RemoveDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
this->m_Pointer = other.m_Pointer;
if (m_Pointer)
m_Pointer->AddDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
return *this;
}
template<class Other>
WeakPointer& operator=(const WeakPointer<Other>& other)
{
if (m_Pointer)
m_Pointer->RemoveDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
this->m_Pointer = const_cast<ObjectType*>(other.m_Pointer);
if (m_Pointer)
m_Pointer->AddDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
return *this;
}
/** Template comparison operators. */
template<typename R>
bool operator ==(const R* o) const
{
return (m_Pointer == nullptr ? o == nullptr : (o && m_Pointer->operator==(o)));
}
template<typename R>
bool operator ==(const WeakPointer<R>& r) const
{
const R* o = r.m_Pointer;
return (m_Pointer == nullptr ? o == nullptr : (o && m_Pointer->operator==(o)));
}
/** Comparison of pointers. Less than comparison. */
bool operator <(const WeakPointer &r) const
{
return (void*) m_Pointer < (void*) r.m_Pointer;
}
/** lock method is used to access the referring object */
SmartPointer<ObjectType> Lock() const
{
SmartPointer<ObjectType> sp(m_Pointer);
return sp;
}
void Reset()
{
if (m_Pointer)
m_Pointer->RemoveDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
m_Pointer = nullptr;
}
bool Expired() const
{
return m_Pointer == nullptr;
}
/** Destructor */
~ WeakPointer()
{
if (m_Pointer)
m_Pointer->RemoveDestroyListener(MessageDelegate<WeakPointer> (this,
&WeakPointer::ObjectDestroyed));
}
private:
template<class Y> friend class SmartPointer;
template<class Y> friend class WeakPointer;
ObjectType *m_Pointer;
void ObjectDestroyed()
{
m_Pointer = nullptr;
}
};
}
#endif // __BERRY_WEAK_POINTER_H__
| 26.323077 | 130 | 0.655562 |
a2f2e544e95bb469741d4b344e136272d5ca8a04 | 2,360 | h | C | Source/WebCore/html/HTMLMarqueeElement.h | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Source/WebCore/html/HTMLMarqueeElement.h | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Source/WebCore/html/HTMLMarqueeElement.h | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2007, 2010 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#pragma once
#include "ActiveDOMObject.h"
#include "HTMLElement.h"
namespace WebCore {
class RenderMarquee;
class HTMLMarqueeElement final : public HTMLElement, public ActiveDOMObject {
WTF_MAKE_ISO_ALLOCATED(HTMLMarqueeElement);
public:
static Ref<HTMLMarqueeElement> create(const QualifiedName&, Document&);
int minimumDelay() const;
WEBCORE_EXPORT void start();
WEBCORE_EXPORT void stop() final;
// Number of pixels to move on each scroll movement. Defaults to 6.
WEBCORE_EXPORT unsigned scrollAmount() const;
WEBCORE_EXPORT void setScrollAmount(unsigned);
// Interval between each scroll movement, in milliseconds. Defaults to 60.
WEBCORE_EXPORT unsigned scrollDelay() const;
WEBCORE_EXPORT void setScrollDelay(unsigned);
// Loop count. -1 means loop indefinitely.
WEBCORE_EXPORT int loop() const;
WEBCORE_EXPORT ExceptionOr<void> setLoop(int);
private:
HTMLMarqueeElement(const QualifiedName&, Document&);
bool isPresentationAttribute(const QualifiedName&) const final;
void collectStyleForPresentationAttribute(const QualifiedName&, const AtomString&, MutableStyleProperties&) final;
void suspend(ReasonForSuspension) final;
void resume() final;
const char* activeDOMObjectName() const final { return "HTMLMarqueeElement"; }
RenderMarquee* renderMarquee() const;
};
} // namespace WebCore
| 34.705882 | 118 | 0.741102 |
0c395fb059cfb2735e53c2728f0a20caa7136ad1 | 3,084 | h | C | qt-creator-opensource-src-4.6.1/src/plugins/mercurial/mercurialcontrol.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/plugins/mercurial/mercurialcontrol.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/plugins/mercurial/mercurialcontrol.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 Brian McGillion
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include <coreplugin/iversioncontrol.h>
QT_BEGIN_NAMESPACE
class QVariant;
QT_END_NAMESPACE
namespace Mercurial {
namespace Internal {
class MercurialClient;
// Implements just the basics of the Version Control Interface
// MercurialClient handles all the work.
class MercurialControl : public Core::IVersionControl
{
Q_OBJECT
public:
explicit MercurialControl(MercurialClient *mercurialClient);
QString displayName() const final;
Core::Id id() const final;
bool isVcsFileOrDirectory(const Utils::FileName &fileName) const final;
bool managesDirectory(const QString &filename, QString *topLevel = 0) const final;
bool managesFile(const QString &workingDirectory, const QString &fileName) const final;
bool isConfigured() const final;
bool supportsOperation(Operation operation) const final;
bool vcsOpen(const QString &fileName) final;
bool vcsAdd(const QString &filename) final;
bool vcsDelete(const QString &filename) final;
bool vcsMove(const QString &from, const QString &to) final;
bool vcsCreateRepository(const QString &directory) final;
bool vcsAnnotate(const QString &file, int line) final;
Core::ShellCommand *createInitialCheckoutCommand(const QString &url,
const Utils::FileName &baseDirectory,
const QString &localName,
const QStringList &extraArgs) final;
bool sccManaged(const QString &filename);
// To be connected to the HgTask's success signal to emit the repository/
// files changed signals according to the variant's type:
// String -> repository, StringList -> files
void changed(const QVariant&);
private:
MercurialClient *const mercurialClient;
};
} // namespace Internal
} // namespace Mercurial
| 38.074074 | 91 | 0.682879 |
bd4b521ad75a357beee250cc6ac4f74943a34b9c | 686 | c | C | usr.bin/pascal/libpc/ARGV.c | weiss/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 114 | 2015-01-18T22:55:52.000Z | 2022-02-17T10:45:02.000Z | usr.bin/pascal/libpc/ARGV.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | null | null | null | usr.bin/pascal/libpc/ARGV.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 29 | 2015-11-03T22:05:22.000Z | 2022-02-08T15:36:37.000Z | /*-
* Copyright (c) 1979, 1993
* The Regents of the University of California. All rights reserved.
*
* %sccs.include.redist.c%
*/
#ifndef lint
static char sccsid[] = "@(#)ARGV.c 8.1 (Berkeley) 06/06/93";
#endif /* not lint */
#include "h00vars.h"
ARGV(subscript, var, siz)
long subscript; /* subscript into argv */
register char *var; /* pointer to pascal char array */
long siz; /* sizeof(var) */
{
register char *cp;
register int size = siz;
if ((unsigned)subscript >= _argc) {
ERROR("Argument to argv of %D is out of range\n", subscript);
return;
}
cp = _argv[subscript];
do {
*var++ = *cp++;
} while (--size && *cp);
while (size--)
*var++ = ' ';
}
| 20.176471 | 69 | 0.612245 |
833144114fb9eefd8d2b9718907eb37a66edd725 | 10,791 | h | C | src/common/lexer/dcf_key_word.h | opengauss-mirror/DCF | bc41b9735088c4148fa41d1f776862c90d6c3d01 | [
"MulanPSL-1.0"
] | null | null | null | src/common/lexer/dcf_key_word.h | opengauss-mirror/DCF | bc41b9735088c4148fa41d1f776862c90d6c3d01 | [
"MulanPSL-1.0"
] | null | null | null | src/common/lexer/dcf_key_word.h | opengauss-mirror/DCF | bc41b9735088c4148fa41d1f776862c90d6c3d01 | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) 2021 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* dcf_key_word.h
*
*
* IDENTIFICATION
* src/common/lexer/dcf_key_word.h
*
* -------------------------------------------------------------------------
*/
#ifndef __DCF_KEY_WORD_H__
#define __DCF_KEY_WORD_H__
#ifdef __cplusplus
extern "C" {
#endif
// 20000 is used for GS_TYPE_BASE in cm_defs.h
#define SQL_KEY_WORD_BASE 10000
#define SQL_RESERVED_WORD_BASE 30000
typedef enum en_key_wid {
/* NOTE: 1. unknown key word, it is used as an initial value and the base for SQL keywords
2. the keyword must be arranged by alphabetical ascending order!!! */
KEY_WORD_0_UNKNOWN = SQL_KEY_WORD_BASE,
KEY_WORD_ABORT = KEY_WORD_0_UNKNOWN + 1,
KEY_WORD_ACCOUNT,
KEY_WORD_ACTIVATE,
KEY_WORD_ACTIVE,
KEY_WORD_ADD,
KEY_WORD_AFTER,
KEY_WORD_ALL,
KEY_WORD_ALTER,
KEY_WORD_ANALYZE,
KEY_WORD_AND,
KEY_WORD_ANY,
KEY_WORD_APPENDONLY,
KEY_WORD_ARCHIVELOG,
KEY_WORD_AS,
KEY_WORD_ASC,
KEY_WORD_ASYNC,
KEY_WORD_AUDIT,
KEY_WORD_AUTO_INCREMENT,
KEY_WORD_AUTOALLOCATE,
KEY_WORD_AUTOEXTEND,
KEY_WORD_AUTOMATIC,
KEY_WORD_AUTOPURGE,
KEY_WORD_AUTON_TRANS,
KEY_WORD_AUTOOFFLINE,
KEY_WORD_AVAILABILITY,
KEY_WORD_BACKUP,
KEY_WORD_BEFORE,
KEY_WORD_BEGIN,
KEY_WORD_BETWEEN,
KEY_WORD_BODY,
KEY_WORD_BOTH, /* for TRIM expression only */
KEY_WORD_BUFFER,
KEY_WORD_BUILD,
KEY_WORD_BULK,
KEY_WORD_BY,
KEY_WORD_CACHE,
KEY_WORD_CALL,
KEY_WORD_CANCEL,
KEY_WORD_CASCADE,
KEY_WORD_CASCADED,
KEY_WORD_CASE,
KEY_WORD_CAST,
KEY_WORD_CATALOG,
KEY_WORD_CHARACTER,
KEY_WORD_CHARSET,
KEY_WORD_CHECK,
KEY_WORD_CHECKPOINT,
KEY_WORD_CLOSE,
KEY_WORD_COALESCE,
KEY_WORD_COLLATE,
KEY_WORD_COLUMN,
KEY_WORD_COLUMNS,
KEY_WORD_COLUMN_VALUE,
KEY_WORD_COMMENT,
KEY_WORD_COMMIT,
KEY_WORD_COMPRESS,
KEY_WORD_CONFIG,
KEY_WORD_CONNECT,
KEY_WORD_CONSISTENCY,
KEY_WORD_CONSTRAINT,
KEY_WORD_CONTENT,
KEY_WORD_CONTROLFILE,
KEY_WORD_CONTINUE,
KEY_WORD_CONVERT,
KEY_WORD_COPY,
KEY_WORD_CREATE,
KEY_WORD_CRMODE,
KEY_WORD_CROSS,
KEY_WORD_CTRLFILE,
KEY_WORD_CUMULATIVE,
KEY_WORD_CURRENT,
KEY_WORD_CURRVAL,
KEY_WORD_CURSOR,
KEY_WORD_CYCLE,
KEY_WORD_DATA,
KEY_WORD_DATABASE,
KEY_WORD_DATAFILE,
KEY_WORD_DEBUG,
KEY_WORD_DECLARE,
KEY_WORD_DEFERRABLE, /* for constraint state */
KEY_WORD_DELETE,
KEY_WORD_DESC,
KEY_WORD_DICTIONARY,
KEY_WORD_DIRECTORY,
KEY_WORD_DISABLE,
KEY_WORD_DISCARD,
KEY_WORD_DISCONNECT,
KEY_WORD_DISTINCT,
KEY_WORD_DISTRIBUTE,
KEY_WORD_DO,
KEY_WORD_DROP,
KEY_WORD_DUMP,
KEY_WORD_DUPLICATE,
KEY_WORD_ELSE,
KEY_WORD_ELSIF,
KEY_WORD_ENABLE,
KEY_WORD_ENABLE_LOGIC_REPLICATION,
KEY_WORD_ENCRYPTION,
KEY_WORD_END,
KEY_WORD_ERROR,
KEY_WORD_ESCAPE,
KEY_WORD_EXCEPT,
KEY_WORD_EXCEPTION,
KEY_WORD_EXCLUDE,
KEY_WORD_EXEC,
KEY_WORD_EXECUTE,
KEY_WORD_EXISTS,
KEY_WORD_EXIT,
KEY_WORD_EXPLAIN,
KEY_WORD_EXTENT,
KEY_WORD_FAILOVER,
KEY_WORD_FETCH,
KEY_WORD_FILE,
KEY_WORD_FILETYPE,
KEY_WORD_FINAL,
KEY_WORD_FINISH,
KEY_WORD_FLASHBACK,
KEY_WORD_FLUSH,
KEY_WORD_FOR,
KEY_WORD_FORALL,
KEY_WORD_FORCE,
KEY_WORD_FOREIGN,
KEY_WORD_FORMAT,
KEY_WORD_FROM,
KEY_WORD_FULL,
KEY_WORD_FUNCTION,
KEY_WORD_GLOBAL,
KEY_WORD_GOTO,
KEY_WORD_GRANT,
KEY_WORD_GROUP,
KEY_WORD_GROUPID,
KEY_WORD_HASH,
KEY_WORD_HAVING,
KEY_WORD_IDENTIFIED,
KEY_WORD_IF,
KEY_WORD_IGNORE,
KEY_WORD_IN,
KEY_WORD_INCLUDE,
KEY_WORD_INCLUDING,
KEY_WORD_INCREMENT,
KEY_WORD_INCREMENTAL,
KEY_WORD_INDEX,
KEY_WORD_INDEX_ASC,
KEY_WORD_INDEX_DESC,
KEY_WORD_INIT,
KEY_WORD_INITIAL,
KEY_WORD_INITIALLY, /* for constraint state */
KEY_WORD_INITRANS,
KEY_WORD_INNER,
KEY_WORD_INSERT,
KEY_WORD_INSTANCE,
KEY_WORD_INSTANTIABLE,
KEY_WORD_INSTEAD,
KEY_WORD_INTERSECT,
KEY_WORD_INTO,
KEY_WORD_INVALIDATE,
KEY_WORD_IS,
KEY_WORD_IS_NOT,
KEY_WORD_JOIN,
KEY_WORD_JSON,
KEY_WORD_KEEP,
KEY_WORD_KEY,
KEY_WORD_KILL,
KEY_WORD_LANGUAGE,
KEY_WORD_LEADING, /* for TRIM expression only */
KEY_WORD_LEFT,
KEY_WORD_LESS,
KEY_WORD_LEVEL,
KEY_WORD_LIBRARY,
KEY_WORD_LIKE,
KEY_WORD_LIMIT,
KEY_WORD_LIST,
KEY_WORD_LNNVL,
KEY_WORD_LOAD,
KEY_WORD_LOB,
KEY_WORD_LOCAL,
KEY_WORD_LOCK,
KEY_WORD_LOCK_WAIT,
KEY_WORD_LOG,
KEY_WORD_LOGFILE,
KEY_WORD_LOGGING,
KEY_WORD_LOGICAL,
KEY_WORD_LOOP,
KEY_WORD_MANAGED,
KEY_WORD_MAXIMIZE,
KEY_WORD_MAXSIZE,
KEY_WORD_MAXTRANS,
KEY_WORD_MAXVALUE,
KEY_WORD_MEMBER,
KEY_WORD_MEMORY,
KEY_WORD_MERGE,
KEY_WORD_MINUS,
KEY_WORD_MINVALUE,
KEY_WORD_MODE,
KEY_WORD_MODIFY,
KEY_WORD_MONITOR,
KEY_WORD_MOUNT,
KEY_WORD_MOVE,
KEY_WORD_NEXT,
KEY_WORD_NEXTVAL,
KEY_WORD_NOARCHIVELOG,
KEY_WORD_NO_CACHE,
KEY_WORD_NO_COMPRESS,
KEY_WORD_NO_CYCLE,
KEY_WORD_NODE,
KEY_WORD_NO_LOGGING,
KEY_WORD_NO_MAXVALUE,
KEY_WORD_NO_MINVALUE,
KEY_WORD_NO_ORDER,
KEY_WORD_NO_RELY, /* for constraint state */
KEY_WORD_NOT,
KEY_WORD_NO_VALIDATE, /* for constraint state */
KEY_WORD_NOWAIT,
KEY_WORD_NULL,
KEY_WORD_NULLS,
KEY_WORD_OF,
KEY_WORD_OFF,
KEY_WORD_OFFLINE,
KEY_WORD_OFFSET,
KEY_WORD_ON,
KEY_WORD_ONLINE,
KEY_WORD_ONLY,
KEY_WORD_OPEN,
KEY_WORD_OR,
KEY_WORD_ORDER,
KEY_WORD_ORGANIZATION,
KEY_WORD_OUTER,
KEY_WORD_OVERRIDING,
KEY_WORD_PACKAGE,
KEY_WORD_PARALLELISM,
KEY_WORD_PARAM,
KEY_WORD_PARTITION,
KEY_WORD_PASSWORD,
KEY_WORD_PATH,
KEY_WORD_PCTFREE,
KEY_WORD_PERFORMANCE,
KEY_WORD_PHYSICAL,
KEY_WORD_PIVOT,
KEY_WORD_PLAN,
KEY_WORD_PRAGMA,
KEY_WORD_PREPARE,
KEY_WORD_PREPARED,
KEY_WORD_PRESERVE,
KEY_WORD_PRIMARY,
KEY_WORD_PRIOR,
KEY_WORD_PRIVILEGES,
KEY_WORD_PROCEDURE,
KEY_WORD_PROFILE,
KEY_WORD_PROTECTION,
KEY_WORD_PUBLIC,
KEY_WORD_PURGE,
KEY_WORD_QUERY,
KEY_WORD_RAISE,
KEY_WORD_RANGE,
KEY_WORD_READ,
KEY_WORD_READ_ONLY,
KEY_WORD_READ_WRITE,
KEY_WORD_REBUILD,
KEY_WORD_RECOVER,
KEY_WORD_RECYCLEBIN,
KEY_WORD_REDO,
KEY_WORD_REFERENCES,
KEY_WORD_REFRESH,
KEY_WORD_REGEXP,
KEY_WORD_REGEXP_LIKE,
KEY_WORD_REGISTER,
KEY_WORD_RELEASE,
KEY_WORD_RELOAD,
KEY_WORD_RELY,
KEY_WORD_RENAME,
KEY_WORD_REPLACE,
KEY_WORD_RESET,
KEY_WORD_RESIZE,
KEY_WORD_RESTORE,
KEY_WORD_RESTRICT,
KEY_WORD_RETURN,
KEY_WORD_RETURNING,
KEY_WORD_REUSE,
KEY_WORD_REVOKE,
KEY_WORD_RIGHT,
KEY_WORD_ROLE,
KEY_WORD_ROLLBACK,
KEY_WORD_ROUTE,
KEY_WORD_ROWS,
KEY_WORD_SAVEPOINT,
KEY_WORD_SCN,
KEY_WORD_SECONDARY,
KEY_WORD_SECTION,
KEY_WORD_SELECT,
KEY_WORD_SEPARATOR,
KEY_WORD_SEQUENCE,
KEY_WORD_SERIALIZABLE,
KEY_WORD_SERVER,
KEY_WORD_SESSION,
KEY_WORD_SET,
KEY_WORD_SHARE,
KEY_WORD_SHOW,
KEY_WORD_SHRINK,
KEY_WORD_SHUTDOWN,
#ifdef DB_DEBUG_VERSION
KEY_WORD_SIGNAL,
#endif /* DB_DEBUG_VERSION */
KEY_WORD_SIZE,
KEY_WORD_SKIP,
KEY_WORD_SKIP_ADD_DROP_TABLE,
KEY_WORD_SKIP_COMMENTS,
KEY_WORD_SKIP_TRIGGERS,
KEY_WORD_SKIP_QUOTE_NAMES,
KEY_WORD_SPACE,
KEY_WORD_SPLIT,
KEY_WORD_SPLIT_FACTOR,
KEY_WORD_SQL_MAP,
KEY_WORD_STANDARD,
KEY_WORD_STANDBY,
KEY_WORD_START,
KEY_WORD_STARTUP,
KEY_WORD_STATIC,
KEY_WORD_STOP,
KEY_WORD_STORAGE,
KEY_WORD_SWAP,
KEY_WORD_SWITCH,
KEY_WORD_SWITCHOVER,
#ifdef DB_DEBUG_VERSION
KEY_WORD_SYNCPOINT,
#endif /* DB_DEBUG_VERSION */
KEY_WORD_SYNONYM,
KEY_WORD_SYSAUX,
KEY_WORD_SYSTEM,
KEY_WORD_TABLE,
KEY_WORD_TABLES,
KEY_WORD_TABLESPACE,
KEY_WORD_TAG,
KEY_WORD_TEMP,
KEY_WORD_TEMPFILE,
KEY_WORD_TEMPORARY,
KEY_WORD_THAN,
KEY_WORD_THEN,
KEY_WORD_THREAD,
KEY_WORD_TIMEOUT,
KEY_WORD_TIMEZONE,
KEY_WORD_TO,
KEY_WORD_TRAILING, /* for TRIM expression only */
KEY_WORD_TRANSACTION,
KEY_WORD_TRIGGER,
KEY_WORD_TRUNCATE,
KEY_WORD_TYPE,
KEY_WORD_UNDO,
KEY_WORD_UNIFORM,
KEY_WORD_UNION,
KEY_WORD_UNIQUE,
KEY_WORD_UNLIMITED,
KEY_WORD_UNLOCK,
KEY_WORD_UNPIVOT,
KEY_WORD_UNTIL,
KEY_WORD_UNUSABLE,
KEY_WORD_UPDATE,
KEY_WORD_USER,
KEY_WORD_USERS,
KEY_WORD_USING,
KEY_WORD_VALIDATE, /* for constraint state */
KEY_WORD_VALUES,
KEY_WORD_VIEW,
KEY_WORD_WAIT,
KEY_WORD_WHEN,
KEY_WORD_WHERE,
KEY_WORD_WHILE,
KEY_WORD_WITH,
KEY_WORD_DUMB_END, // dumb key word, just for static assert
} key_wid_t;
typedef enum en_hint_key_wid {
HINT_KEY_WORD_INVALID = 0x00000000,
/* table hints below */
// access method
HINT_KEY_WORD_FULL = 0x00000001,
HINT_KEY_WORD_INDEX = 0x00000002,
HINT_KEY_WORD_NO_INDEX = 0x00000004,
HINT_KEY_WORD_INDEX_ASC = 0x00000008,
HINT_KEY_WORD_INDEX_DESC = 0x00000010,
HINT_KEY_WORD_INDEX_FFS = 0x00000020,
HINT_KEY_WORD_NO_INDEX_FFS = 0x00000040,
HINT_KEY_WORD_PARALLEL = 0x00000080,
/* query hints below */
// rbo
HINT_KEY_WORD_RULE = 0x00000100,
// join order
HINT_KEY_WORD_LEADING = 0x00000200,
HINT_KEY_WORD_ORDERED = 0x00000400,
// join method
HINT_KEY_WORD_USE_NL = 0x00000800,
HINT_KEY_WORD_USE_MERGE = 0x00001000,
HINT_KEY_WORD_USE_HASH = 0x00002000,
/* insert hints below */
HINT_KEY_WORD_HASH_BUCKET_SIZE = 0x00004000,
#ifdef Z_SHARDING
/* Z_SHARDING hints below */
// from subquery pullup
HINT_KEY_WORD_MERGE = 0x00008000,
HINT_KEY_WORD_NO_MERGE = 0x00010000,
#endif
/* replace hints below */
HINT_KEY_WORD_THROW_DUPLICATE = 0x00020000,
#ifdef Z_SHARDING
HINT_KEY_WORD_SQL_WHITELIST = 0x00040000,
HINT_KEY_WORD_SHD_READ_MASTER = 0x00080000,
#endif
} hint_key_wid_t;
#ifdef __cplusplus
}
#endif
#endif
| 23.256466 | 94 | 0.712816 |
d9035878c0746c2835944b00a1866da9ce4d538c | 251 | h | C | Legacy/QFog2-MachO/QFogSource/Mac_Other/C_KEYS.h | artiste-qb-net/QFog-Pyodide | 9ce6ad7ef6a7f7a71bbcd4fe6a6a35a5f02e8744 | [
"BSD-3-Clause"
] | 87 | 2015-12-17T22:19:21.000Z | 2022-03-08T10:27:54.000Z | Legacy/QFog2-MachO/QFogSource/Mac_Other/C_KEYS.h | artiste-qb-net/QFog-Pyodide | 9ce6ad7ef6a7f7a71bbcd4fe6a6a35a5f02e8744 | [
"BSD-3-Clause"
] | 18 | 2016-02-18T15:08:36.000Z | 2021-03-10T00:52:36.000Z | Legacy/QFog2-MachO/QFogSource/Mac_Other/C_KEYS.h | artiste-qb-net/QFog-Pyodide | 9ce6ad7ef6a7f7a71bbcd4fe6a6a35a5f02e8744 | [
"BSD-3-Clause"
] | 34 | 2015-11-29T09:08:46.000Z | 2022-02-16T22:54:24.000Z | #pragma once
class C_KEYS
{
public:
static BOOLEAN KeyIsDown( SHORT theKeyCode);
static EKeyStatus my_PrintingCharField(
TEHandle inMacTEH,
UInt16 inKeyCode,
UInt16 &ioCharCode,
EventModifiers inModifiers);
}; | 251 | 251 | 0.685259 |
038dd90d5f870846edaab7b5c46ecff34d47eea8 | 997 | c | C | DEVC/EX40/main.c | giljr/c | b8058423f9feda06f05e67af617a1e2f5089f9e8 | [
"MIT"
] | null | null | null | DEVC/EX40/main.c | giljr/c | b8058423f9feda06f05e67af617a1e2f5089f9e8 | [
"MIT"
] | null | null | null | DEVC/EX40/main.c | giljr/c | b8058423f9feda06f05e67af617a1e2f5089f9e8 | [
"MIT"
] | 1 | 2021-06-29T08:26:40.000Z | 2021-06-29T08:26:40.000Z | /*
Project 40 - Reading & Displaying Strings in C
Description
This Program asks the user to enter until 10 names;
Then it presents it in the console.
************************************
Output
Enter the number of names (<10): 5
Enter 5 names:
john
maccarthy
malcomx
Bill
Keil
Entered names are:
john
maccarthy
malcomx
Bill
Keil
************************************
Edited by J3
Date: Jul, 13/2020
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[10][20];
int i,n;
printf("Enter the number of names (<10): ");
scanf("%d",&n);
/* reading string from user */
/* Watch out! scanf("%s[^\n]",name[i]) */
printf("Enter %d names:\n",n);
for(i=0; i<n; i++)
scanf("%s[^\n]",name[i]);
/* Displaying strings */
printf("\nEntered names are:\n");
for(i=0;i<n;i++)
puts(name[i]);
return 0;
}
| 17.189655 | 54 | 0.48345 |
ea99667ac8f9d9e4d498a1110313915611175b39 | 4,796 | h | C | Source/Drivers/OniFile/PlayerStream.h | clalancette/OpenNI2 | 50ebd3330364bdcb0890e0e3910979183f402f82 | [
"Apache-2.0"
] | 1 | 2021-01-11T06:28:25.000Z | 2021-01-11T06:28:25.000Z | Source/Drivers/OniFile/PlayerStream.h | clalancette/OpenNI2 | 50ebd3330364bdcb0890e0e3910979183f402f82 | [
"Apache-2.0"
] | null | null | null | Source/Drivers/OniFile/PlayerStream.h | clalancette/OpenNI2 | 50ebd3330364bdcb0890e0e3910979183f402f82 | [
"Apache-2.0"
] | 1 | 2021-07-16T08:42:52.000Z | 2021-07-16T08:42:52.000Z | /*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* 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. *
* *
*****************************************************************************/
/// @file
/// Contains the declaration of Stream class that implements a stream from
/// a virtual OpenNI device.
#ifndef PLAYERSTREAM_H
#define PLAYERSTREAM_H
#include "Driver/OniDriverAPI.h"
#include "PlayerProperties.h"
#include "PlayerSource.h"
#include "XnOSCpp.h"
namespace oni_file {
class Decoder;
class PlayerDevice;
/// Implements a stream from a virtual OpenNI device.
class PlayerStream final : public oni::driver::StreamBase
{
public:
// General stream event.
typedef struct
{
PlayerStream* pStream;
} StreamEventArgs;
typedef xnl::Event<StreamEventArgs> StreamEvent;
typedef void (ONI_CALLBACK_TYPE* StreamCallback)(const StreamEventArgs& streamEventArgs, void* pCookie);
// Ready for data event.
typedef StreamEventArgs ReadyForDataEventArgs;
typedef StreamEvent ReadyForDataEvent;
typedef StreamCallback ReadyForDataCallback;
// Destroy event.
typedef StreamEventArgs DestroyEventArgs;
typedef StreamEvent DestroyEvent;
typedef StreamCallback DestroyCallback;
/// Constructor.
PlayerStream(PlayerDevice* pDevice, PlayerSource* pSource);
/// Destructor.
virtual ~PlayerStream();
/// Initialize the stream object.
OniStatus Initialize();
virtual int getRequiredFrameSize() override;
/// @copydoc OniStreamBase::start()
virtual OniStatus start() override;
/// has start() been called on this stream already?
bool isStreamStarted() { return m_isStarted; }
/// @copydoc OniStreamBase::stop()
virtual void stop() override;
// Return the player source the stream was created on.
PlayerSource* GetSource();
/// @copydoc OniStreamBase::getProperty(int,void*,int*)
virtual OniStatus getProperty(int propertyId, void* pData, int* pDataSize) override;
/// @copydoc OniStreamBase::setProperty(int,void*,int*)
virtual OniStatus setProperty(int propertyId, const void* pData, int dataSize) override;
// Register for 'ready for data' event.
OniStatus RegisterReadyForDataEvent(ReadyForDataCallback callback, void* pCookie, OniCallbackHandle& handle);
// Unregister from 'ready for data' event.
void UnregisterReadyForDataEvent(OniCallbackHandle handle);
// Register for 'destroy' event.
OniStatus RegisterDestroyEvent(DestroyCallback callback, void* pCookie, OniCallbackHandle& handle);
// Unregister from 'destroy' event.
void UnregisterDestroyEvent(OniCallbackHandle handle);
void notifyAllProperties();
private:
void destroy();
void MainLoop();
static XN_THREAD_PROC ThreadProc(XN_THREAD_PARAM pThreadParam);
// Callback to be called when new data is available.
static void ONI_CALLBACK_TYPE OnNewDataCallback(const PlayerSource::NewDataEventArgs& newDataEventArgs, void* pCookie);
// Data members
private:
// Source the stream was created on.
PlayerSource* m_pSource;
// Stream properties.
PlayerProperties m_properties;
// Handle to new data callback.
OniCallbackHandle m_newDataHandle;
// Ready for data event.
ReadyForDataEvent m_readyForDataEvent;
// Destroy event.
DestroyEvent m_destroyEvent;
// Critical section.
xnl::CriticalSection m_cs;
// Are we streaming right now?
bool m_isStarted;
int m_requiredFrameSize;
PlayerDevice* m_pDevice;
};
} // namespace oni_files_player
#endif // PLAYERSTREAM_H
| 33.305556 | 120 | 0.619266 |
cfe703ed90754b7ddd8159920d3a4af90675982b | 8,898 | h | C | util/autovector.h | CPB9/rocksdb | adfcc4ccb7a565d513222b1b4b926431f6a5fc41 | [
"BSD-3-Clause"
] | 1 | 2021-08-19T12:42:17.000Z | 2021-08-19T12:42:17.000Z | util/autovector.h | CPB9/rocksdb | adfcc4ccb7a565d513222b1b4b926431f6a5fc41 | [
"BSD-3-Clause"
] | null | null | null | util/autovector.h | CPB9/rocksdb | adfcc4ccb7a565d513222b1b4b926431f6a5fc41 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#pragma once
#include <algorithm>
#include <cassert>
#include <initializer_list>
#include <iterator>
#include <stdexcept>
#include <vector>
namespace rocksdb {
#ifdef ROCKSDB_LITE
template <class T, size_t kSize = 8>
class autovector : public std::vector<T> {
using std::vector<T>::vector;
};
#else
// A vector that leverages pre-allocated stack-based array to achieve better
// performance for array with small amount of items.
//
// The interface resembles that of vector, but with less features since we aim
// to solve the problem that we have in hand, rather than implementing a
// full-fledged generic container.
//
// Currently we don't support:
// * reserve()/shrink_to_fit()
// If used correctly, in most cases, people should not touch the
// underlying vector at all.
// * random insert()/erase(), please only use push_back()/pop_back().
// * No move/swap operations. Each autovector instance has a
// stack-allocated array and if we want support move/swap operations, we
// need to copy the arrays other than just swapping the pointers. In this
// case we'll just explicitly forbid these operations since they may
// lead users to make false assumption by thinking they are inexpensive
// operations.
//
// Naming style of public methods almost follows that of the STL's.
template <class T, size_t kSize = 8>
class autovector {
public:
// General STL-style container member types.
typedef T value_type;
typedef typename std::vector<T>::difference_type difference_type;
typedef typename std::vector<T>::size_type size_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
// This class is the base for regular/const iterator
template <class TAutoVector, class TValueType>
class iterator_impl {
public:
// -- iterator traits
typedef iterator_impl<TAutoVector, TValueType> self_type;
typedef TValueType value_type;
typedef TValueType& reference;
typedef TValueType* pointer;
typedef typename TAutoVector::difference_type difference_type;
typedef std::random_access_iterator_tag iterator_category;
iterator_impl(TAutoVector* vect, size_t index)
: vect_(vect), index_(index) {};
iterator_impl(const iterator_impl&) = default;
~iterator_impl() {}
iterator_impl& operator=(const iterator_impl&) = default;
// -- Advancement
// ++iterator
self_type& operator++() {
++index_;
return *this;
}
// iterator++
self_type operator++(int) {
auto old = *this;
++index_;
return old;
}
// --iterator
self_type& operator--() {
--index_;
return *this;
}
// iterator--
self_type operator--(int) {
auto old = *this;
--index_;
return old;
}
self_type operator-(difference_type len) {
return self_type(vect_, index_ - len);
}
difference_type operator-(const self_type& other) {
assert(vect_ == other.vect_);
return index_ - other.index_;
}
self_type operator+(difference_type len) {
return self_type(vect_, index_ + len);
}
self_type& operator+=(difference_type len) {
index_ += len;
return *this;
}
self_type& operator-=(difference_type len) {
index_ -= len;
return *this;
}
// -- Reference
reference operator*() {
assert(vect_->size() >= index_);
return (*vect_)[index_];
}
pointer operator->() {
assert(vect_->size() >= index_);
return &(*vect_)[index_];
}
// -- Logical Operators
bool operator==(const self_type& other) const {
assert(vect_ == other.vect_);
return index_ == other.index_;
}
bool operator!=(const self_type& other) const { return !(*this == other); }
bool operator>(const self_type& other) const {
assert(vect_ == other.vect_);
return index_ > other.index_;
}
bool operator<(const self_type& other) const {
assert(vect_ == other.vect_);
return index_ < other.index_;
}
bool operator>=(const self_type& other) const {
assert(vect_ == other.vect_);
return index_ >= other.index_;
}
bool operator<=(const self_type& other) const {
assert(vect_ == other.vect_);
return index_ <= other.index_;
}
private:
TAutoVector* vect_ = nullptr;
size_t index_ = 0;
};
typedef iterator_impl<autovector, value_type> iterator;
typedef iterator_impl<const autovector, const value_type> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
autovector() = default;
autovector(std::initializer_list<T> init_list) {
for (const T& item : init_list) {
push_back(item);
}
}
~autovector() = default;
// -- Immutable operations
// Indicate if all data resides in in-stack data structure.
bool only_in_stack() const {
// If no element was inserted at all, the vector's capacity will be `0`.
return vect_.capacity() == 0;
}
size_type size() const { return num_stack_items_ + vect_.size(); }
// resize does not guarantee anything about the contents of the newly
// available elements
void resize(size_type n) {
if (n > kSize) {
vect_.resize(n - kSize);
num_stack_items_ = kSize;
} else {
vect_.clear();
num_stack_items_ = n;
}
}
bool empty() const { return size() == 0; }
const_reference operator[](size_type n) const {
assert(n < size());
return n < kSize ? values_[n] : vect_[n - kSize];
}
reference operator[](size_type n) {
assert(n < size());
return n < kSize ? values_[n] : vect_[n - kSize];
}
const_reference at(size_type n) const {
assert(n < size());
return (*this)[n];
}
reference at(size_type n) {
assert(n < size());
return (*this)[n];
}
reference front() {
assert(!empty());
return *begin();
}
const_reference front() const {
assert(!empty());
return *begin();
}
reference back() {
assert(!empty());
return *(end() - 1);
}
const_reference back() const {
assert(!empty());
return *(end() - 1);
}
// -- Mutable Operations
void push_back(T&& item) {
if (num_stack_items_ < kSize) {
values_[num_stack_items_++] = std::move(item);
} else {
vect_.push_back(item);
}
}
void push_back(const T& item) {
if (num_stack_items_ < kSize) {
values_[num_stack_items_++] = item;
} else {
vect_.push_back(item);
}
}
template <class... Args>
void emplace_back(Args&&... args) {
push_back(value_type(args...));
}
void pop_back() {
assert(!empty());
if (!vect_.empty()) {
vect_.pop_back();
} else {
--num_stack_items_;
}
}
void clear() {
num_stack_items_ = 0;
vect_.clear();
}
// -- Copy and Assignment
autovector& assign(const autovector& other);
autovector(const autovector& other) { assign(other); }
autovector& operator=(const autovector& other) { return assign(other); }
// move operation are disallowed since it is very hard to make sure both
// autovectors are allocated from the same function stack.
autovector& operator=(autovector&& other) = delete;
autovector(autovector&& other) = delete;
// -- Iterator Operations
iterator begin() { return iterator(this, 0); }
const_iterator begin() const { return const_iterator(this, 0); }
iterator end() { return iterator(this, this->size()); }
const_iterator end() const { return const_iterator(this, this->size()); }
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
private:
size_type num_stack_items_ = 0; // current number of items
value_type values_[kSize]; // the first `kSize` items
// used only if there are more than `kSize` items.
std::vector<T> vect_;
};
template <class T, size_t kSize>
autovector<T, kSize>& autovector<T, kSize>::assign(const autovector& other) {
// copy the internal vector
vect_.assign(other.vect_.begin(), other.vect_.end());
// copy array
num_stack_items_ = other.num_stack_items_;
std::copy(other.values_, other.values_ + num_stack_items_, values_);
return *this;
}
#endif // ROCKSDB_LITE
} // namespace rocksdb
| 26.801205 | 79 | 0.658013 |
2ca5ba9bc496843443a1424a9f2b53fb6cb58101 | 4,169 | c | C | head/contrib/gcc/config/host-hpux.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | 105 | 2015-03-02T16:58:34.000Z | 2022-03-28T07:17:49.000Z | head/contrib/gcc/config/host-hpux.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | 145 | 2015-03-18T10:08:17.000Z | 2022-03-31T01:27:08.000Z | head/contrib/gcc/config/host-hpux.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | 26 | 2015-10-10T09:37:44.000Z | 2022-02-23T02:02:05.000Z | /* HP-UX host-specific hook definitions.
Copyright (C) 2004, 2005 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GCC is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to the
Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include <sys/mman.h>
#include <unistd.h>
#include "hosthooks.h"
#include "hosthooks-def.h"
#ifndef MAP_FAILED
#define MAP_FAILED (void *)-1L
#endif
static void *hpux_gt_pch_get_address (size_t, int);
static int hpux_gt_pch_use_address (void *, size_t, int, size_t);
#undef HOST_HOOKS_GT_PCH_GET_ADDRESS
#define HOST_HOOKS_GT_PCH_GET_ADDRESS hpux_gt_pch_get_address
#undef HOST_HOOKS_GT_PCH_USE_ADDRESS
#define HOST_HOOKS_GT_PCH_USE_ADDRESS hpux_gt_pch_use_address
/* For various ports, try to guess a fixed spot in the vm space
that's probably free. */
#if (defined(__hppa__) || defined(__ia64__)) && defined(__LP64__)
# define TRY_EMPTY_VM_SPACE 0x8000000000000000
#elif defined(__hppa__) || defined(__ia64__)
# define TRY_EMPTY_VM_SPACE 0x60000000
#else
# define TRY_EMPTY_VM_SPACE 0
#endif
/* Determine a location where we might be able to reliably allocate
SIZE bytes. FD is the PCH file, though we should return with the
file unmapped. */
static void *
hpux_gt_pch_get_address (size_t size, int fd)
{
void *addr;
addr = mmap ((void *)TRY_EMPTY_VM_SPACE, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE, fd, 0);
/* If we failed the map, that means there's *no* free space. */
if (addr == (void *) MAP_FAILED)
return NULL;
/* Unmap the area before returning. */
munmap (addr, size);
return addr;
}
/* Map SIZE bytes of FD+OFFSET at BASE. Return 1 if we succeeded at
mapping the data at BASE, -1 if we couldn't.
It's not possibly to reliably mmap a file using MAP_PRIVATE to
a specific START address on either hpux or linux. First we see
if mmap with MAP_PRIVATE works. If it does, we are off to the
races. If it doesn't, we try an anonymous private mmap since the
kernel is more likely to honor the BASE address in anonymous maps.
We then copy the data to the anonymous private map. This assumes
of course that we don't need to change the data in the PCH file
after it is created.
This approach obviously causes a performance penalty but there is
little else we can do given the current PCH implementation. */
static int
hpux_gt_pch_use_address (void *base, size_t size, int fd, size_t offset)
{
void *addr;
/* We're called with size == 0 if we're not planning to load a PCH
file at all. This allows the hook to free any static space that
we might have allocated at link time. */
if (size == 0)
return -1;
/* Try to map the file with MAP_PRIVATE. */
addr = mmap (base, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, offset);
if (addr == base)
return 1;
if (addr != (void *) MAP_FAILED)
munmap (addr, size);
/* Try to make an anonymous private mmap at the desired location. */
addr = mmap (base, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (addr != base)
{
if (addr != (void *) MAP_FAILED)
munmap (addr, size);
return -1;
}
if (lseek (fd, offset, SEEK_SET) == (off_t)-1)
return -1;
while (size)
{
ssize_t nbytes;
nbytes = read (fd, base, MIN (size, SSIZE_MAX));
if (nbytes <= 0)
return -1;
base = (char *) base + nbytes;
size -= nbytes;
}
return 1;
}
const struct host_hooks host_hooks = HOST_HOOKS_INITIALIZER;
| 30.430657 | 76 | 0.701607 |
8293fabb3eebaf8931521de59a72dbfbc89ebbbc | 50,700 | c | C | azure_iot_sdk/serializer/src/commanddecoder.c | h7ga40/azure_iot_hub_rose | 7b7e94860737f777e1af514fc84e41e91fe94fab | [
"MIT"
] | null | null | null | azure_iot_sdk/serializer/src/commanddecoder.c | h7ga40/azure_iot_hub_rose | 7b7e94860737f777e1af514fc84e41e91fe94fab | [
"MIT"
] | null | null | null | azure_iot_sdk/serializer/src/commanddecoder.c | h7ga40/azure_iot_hub_rose | 7b7e94860737f777e1af514fc84e41e91fe94fab | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdlib.h>
#include "azure_c_shared_utility/optimize_size.h"
#include "azure_c_shared_utility/gballoc.h"
#include <stddef.h>
#include "commanddecoder.h"
#include "multitree.h"
#include "azure_c_shared_utility/crt_abstractions.h"
#include "azure_c_shared_utility/xlogging.h"
#include "schema.h"
#include "codefirst.h"
#include "jsondecoder.h"
MU_DEFINE_ENUM_STRINGS_WITHOUT_INVALID(COMMANDDECODER_RESULT, COMMANDDECODER_RESULT_VALUES);
typedef struct COMMAND_DECODER_HANDLE_DATA_TAG
{
METHOD_CALLBACK_FUNC methodCallback;
void* methodCallbackContext;
SCHEMA_MODEL_TYPE_HANDLE ModelHandle;
ACTION_CALLBACK_FUNC ActionCallback;
void* ActionCallbackContext;
} COMMAND_DECODER_HANDLE_DATA;
static int DecodeValueFromNode(SCHEMA_HANDLE schemaHandle, AGENT_DATA_TYPE* agentDataType, MULTITREE_HANDLE node, const char* edmTypeName)
{
/* because "pottentially uninitialized variable on MS compiler" */
int result = 0;
const char* argStringValue;
AGENT_DATA_TYPE_TYPE primitiveType;
/* Codes_SRS_COMMAND_DECODER_99_029:[ If the argument type is complex then a complex type value shall be built from the child nodes.] */
if ((primitiveType = CodeFirst_GetPrimitiveType(edmTypeName)) == EDM_NO_TYPE)
{
SCHEMA_STRUCT_TYPE_HANDLE structTypeHandle;
size_t propertyCount;
/* Codes_SRS_COMMAND_DECODER_99_033:[ In order to determine which are the members of a complex types, Schema APIs for structure types shall be used.] */
if (((structTypeHandle = Schema_GetStructTypeByName(schemaHandle, edmTypeName)) == NULL) ||
(Schema_GetStructTypePropertyCount(structTypeHandle, &propertyCount) != SCHEMA_OK))
{
/* Codes_SRS_COMMAND_DECODER_99_010:[ If any Schema API fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
result = MU_FAILURE;
LogError("Getting Struct information failed.");
}
else
{
if (propertyCount == 0)
{
/* Codes_SRS_COMMAND_DECODER_99_034:[ If Schema APIs indicate that a complex type has 0 members then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
result = MU_FAILURE;
LogError("Struct type with 0 members is not allowed");
}
else
{
AGENT_DATA_TYPE* memberValues = (AGENT_DATA_TYPE*)calloc(1, (sizeof(AGENT_DATA_TYPE)* propertyCount));
if (memberValues == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
result = MU_FAILURE;
LogError("Failed allocating member values for command argument");
}
else
{
const char** memberNames = (const char**)malloc(sizeof(const char*)* propertyCount);
if (memberNames == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
result = MU_FAILURE;
LogError("Failed allocating member names for command argument.");
}
else
{
size_t j;
size_t k;
for (j = 0; j < propertyCount; j++)
{
SCHEMA_PROPERTY_HANDLE propertyHandle;
MULTITREE_HANDLE memberNode;
const char* propertyName;
const char* propertyType;
if ((propertyHandle = Schema_GetStructTypePropertyByIndex(structTypeHandle, j)) == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_010:[ If any Schema API fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
result = MU_FAILURE;
LogError("Getting struct member failed.");
break;
}
else if (((propertyName = Schema_GetPropertyName(propertyHandle)) == NULL) ||
((propertyType = Schema_GetPropertyType(propertyHandle)) == NULL))
{
/* Codes_SRS_COMMAND_DECODER_99_010:[ If any Schema API fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
result = MU_FAILURE;
LogError("Getting the struct member information failed.");
break;
}
else
{
memberNames[j] = propertyName;
/* Codes_SRS_COMMAND_DECODER_01_014: [CommandDecoder shall use the MultiTree APIs to extract a specific element from the command JSON.] */
if (MultiTree_GetChildByName(node, memberNames[j], &memberNode) != MULTITREE_OK)
{
/* Codes_SRS_COMMAND_DECODER_99_028:[ If decoding the argument fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
result = MU_FAILURE;
LogError("Getting child %s failed", propertyName);
break;
}
/* Codes_SRS_COMMAND_DECODER_99_032:[ Nesting shall be supported for complex type.] */
else if ((result = DecodeValueFromNode(schemaHandle, &memberValues[j], memberNode, propertyType)) != 0)
{
break;
}
}
}
if (j == propertyCount)
{
/* Codes_SRS_COMMAND_DECODER_99_031:[ The complex type value that aggregates the children shall be built by using the Create_AGENT_DATA_TYPE_from_Members.] */
if (Create_AGENT_DATA_TYPE_from_Members(agentDataType, edmTypeName, propertyCount, (const char* const*)memberNames, memberValues) != AGENT_DATA_TYPES_OK)
{
/* Codes_SRS_COMMAND_DECODER_99_028:[ If decoding the argument fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
result = MU_FAILURE;
LogError("Creating the agent data type from members failed.");
}
else
{
result = 0;
}
}
for (k = 0; k < j; k++)
{
Destroy_AGENT_DATA_TYPE(&memberValues[k]);
}
free((void*)memberNames);
}
free(memberValues);
}
}
}
}
else
{
/* Codes_SRS_COMMAND_DECODER_01_014: [CommandDecoder shall use the MultiTree APIs to extract a specific element from the command JSON.] */
if (MultiTree_GetValue(node, (const void **)&argStringValue) != MULTITREE_OK)
{
/* Codes_SRS_COMMAND_DECODER_99_012:[ If any argument is missing in the command text then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
result = MU_FAILURE;
LogError("Getting the string from the multitree failed.");
}
/* Codes_SRS_COMMAND_DECODER_99_027:[ The value for an argument of primitive type shall be decoded by using the CreateAgentDataType_From_String API.] */
else if (CreateAgentDataType_From_String(argStringValue, primitiveType, agentDataType) != AGENT_DATA_TYPES_OK)
{
/* Codes_SRS_COMMAND_DECODER_99_028:[ If decoding the argument fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
result = MU_FAILURE;
LogError("Failed parsing node %s.", argStringValue);
}
}
return result;
}
static EXECUTE_COMMAND_RESULT DecodeAndExecuteModelAction(COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance, SCHEMA_HANDLE schemaHandle, SCHEMA_MODEL_TYPE_HANDLE modelHandle, const char* relativeActionPath, const char* actionName, MULTITREE_HANDLE commandNode)
{
EXECUTE_COMMAND_RESULT result;
char tempStr[128];
size_t strLength = strlen(actionName);
if (strLength <= 1)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
LogError("Invalid action name");
result = EXECUTE_COMMAND_ERROR;
}
else if (strLength >= 128)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
LogError("Invalid action name length");
result = EXECUTE_COMMAND_ERROR;
}
else
{
/* Codes_SRS_COMMAND_DECODER_99_006:[ The action name shall be decoded from the element "Name" of the command JSON.] */
SCHEMA_ACTION_HANDLE modelActionHandle;
size_t argCount;
MULTITREE_HANDLE parametersTreeNode;
if (memcpy(tempStr, actionName, strLength-1) == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
LogError("Invalid action name.");
result = EXECUTE_COMMAND_ERROR;
}
/* Codes_SRS_COMMAND_DECODER_01_014: [CommandDecoder shall use the MultiTree APIs to extract a specific element from the command JSON.] */
else if (MultiTree_GetChildByName(commandNode, "Parameters", ¶metersTreeNode) != MULTITREE_OK)
{
/* Codes_SRS_COMMAND_DECODER_01_015: [If any MultiTree API call fails then the processing shall stop and the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
LogError("Error getting Parameters node.");
result = EXECUTE_COMMAND_ERROR;
}
else
{
tempStr[strLength-1] = 0;
/* Codes_SRS_COMMAND_DECODER_99_009:[ CommandDecoder shall call Schema_GetModelActionByName to obtain the information about a specific action.] */
if (((modelActionHandle = Schema_GetModelActionByName(modelHandle, tempStr)) == NULL) ||
(Schema_GetModelActionArgumentCount(modelActionHandle, &argCount) != SCHEMA_OK))
{
/* Codes_SRS_COMMAND_DECODER_99_010:[ If any Schema API fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
LogError("Failed reading action %s from the schema", tempStr);
result = EXECUTE_COMMAND_ERROR;
}
else
{
AGENT_DATA_TYPE* arguments = NULL;
if (argCount > 0)
{
arguments = (AGENT_DATA_TYPE*)calloc(1, (sizeof(AGENT_DATA_TYPE)* argCount));
}
if ((argCount > 0) &&
(arguments == NULL))
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
LogError("Failed allocating arguments array");
result = EXECUTE_COMMAND_ERROR;
}
else
{
size_t i;
size_t j;
result = EXECUTE_COMMAND_ERROR;
/* Codes_SRS_COMMAND_DECODER_99_011:[ CommandDecoder shall attempt to extract from the command text the value for each action argument.] */
for (i = 0; i < argCount; i++)
{
SCHEMA_ACTION_ARGUMENT_HANDLE actionArgumentHandle;
MULTITREE_HANDLE argumentNode;
const char* argName;
const char* argType;
if (((actionArgumentHandle = Schema_GetModelActionArgumentByIndex(modelActionHandle, i)) == NULL) ||
((argName = Schema_GetActionArgumentName(actionArgumentHandle)) == NULL) ||
((argType = Schema_GetActionArgumentType(actionArgumentHandle)) == NULL))
{
LogError("Failed getting the argument information from the schema");
result = EXECUTE_COMMAND_ERROR;
break;
}
/* Codes_SRS_COMMAND_DECODER_01_014: [CommandDecoder shall use the MultiTree APIs to extract a specific element from the command JSON.] */
/* Codes_SRS_COMMAND_DECODER_01_008: [Each argument shall be looked up as a field, member of the "Parameters" node.] */
else if (MultiTree_GetChildByName(parametersTreeNode, argName, &argumentNode) != MULTITREE_OK)
{
/* Codes_SRS_COMMAND_DECODER_99_012:[ If any argument is missing in the command text then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
LogError("Missing argument %s", argName);
result = EXECUTE_COMMAND_ERROR;
break;
}
else if (DecodeValueFromNode(schemaHandle, &arguments[i], argumentNode, argType) != 0)
{
result = EXECUTE_COMMAND_ERROR;
break;
}
}
if (i == argCount)
{
/* Codes_SRS_COMMAND_DECODER_99_005:[ If an Invoke Action is decoded successfully then the callback actionCallback shall be called, passing to it the callback action context, decoded name and arguments.] */
result = commandDecoderInstance->ActionCallback(commandDecoderInstance->ActionCallbackContext, relativeActionPath, tempStr, argCount, arguments);
}
for (j = 0; j < i; j++)
{
Destroy_AGENT_DATA_TYPE(&arguments[j]);
}
if (arguments != NULL)
{
free(arguments);
}
}
}
}
}
return result;
}
static METHODRETURN_HANDLE DecodeAndExecuteModelMethod(COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance, SCHEMA_HANDLE schemaHandle, SCHEMA_MODEL_TYPE_HANDLE modelHandle, const char* relativeMethodPath, const char* methodName, MULTITREE_HANDLE methodTree)
{
METHODRETURN_HANDLE result;
size_t strLength = strlen(methodName);
if (strLength == 0)
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("Invalid method name");
result = NULL;
}
else
{
SCHEMA_METHOD_HANDLE modelMethodHandle;
size_t argCount;
#ifdef _MSC_VER
#pragma warning(suppress: 6324) /* We intentionally use here strncpy */
#endif
/*Codes_SRS_COMMAND_DECODER_02_020: [ CommandDecoder_ExecuteMethod shall verify that the model has a method called methodName. ]*/
if (((modelMethodHandle = Schema_GetModelMethodByName(modelHandle, methodName)) == NULL) ||
(Schema_GetModelMethodArgumentCount(modelMethodHandle, &argCount) != SCHEMA_OK))
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("Failed reading method %s from the schema", methodName);
result = NULL;
}
else
{
/*Codes_SRS_COMMAND_DECODER_02_021: [ For every argument of methodName, CommandDecoder_ExecuteMethod shall build an AGENT_DATA_TYPE from the node with the same name from the MULTITREE_HANDLE. ]*/
if (argCount == 0)
{
/*no need for any parameters*/
result = commandDecoderInstance->methodCallback(commandDecoderInstance->methodCallbackContext, relativeMethodPath, methodName, 0, NULL);
}
else
{
AGENT_DATA_TYPE* arguments;
arguments = (AGENT_DATA_TYPE*)calloc(1, (sizeof(AGENT_DATA_TYPE)* argCount));
if (arguments == NULL)
{
LogError("Failed allocating arguments array");
result = NULL;
}
else
{
size_t i;
size_t j;
result = NULL;
for (i = 0; i < argCount; i++)
{
SCHEMA_METHOD_ARGUMENT_HANDLE methodArgumentHandle;
MULTITREE_HANDLE argumentNode;
const char* argName;
const char* argType;
if (((methodArgumentHandle = Schema_GetModelMethodArgumentByIndex(modelMethodHandle, i)) == NULL) ||
((argName = Schema_GetMethodArgumentName(methodArgumentHandle)) == NULL) ||
((argType = Schema_GetMethodArgumentType(methodArgumentHandle)) == NULL))
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("Failed getting the argument information from the schema");
result = NULL;
break;
}
else if (MultiTree_GetChildByName(methodTree, argName, &argumentNode) != MULTITREE_OK)
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("Missing argument %s", argName);
result = NULL;
break;
}
else if (DecodeValueFromNode(schemaHandle, &arguments[i], argumentNode, argType) != 0)
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("failure in DecodeValueFromNode");
result = NULL;
break;
}
}
if (i == argCount)
{
/*Codes_SRS_COMMAND_DECODER_02_022: [ CommandDecoder_ExecuteMethod shall call methodCallback passing the context, the methodName, number of arguments and the AGENT_DATA_TYPE. ]*/
/*Codes_SRS_COMMAND_DECODER_02_024: [ Otherwise, CommandDecoder_ExecuteMethod shall return what methodCallback returns. ]*/
result = commandDecoderInstance->methodCallback(commandDecoderInstance->methodCallbackContext, relativeMethodPath, methodName, argCount, arguments);
}
for (j = 0; j < i; j++)
{
Destroy_AGENT_DATA_TYPE(&arguments[j]);
}
free(arguments);
}
}
}
}
return result;
}
static EXECUTE_COMMAND_RESULT ScanActionPathAndExecuteAction(COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance, SCHEMA_HANDLE schemaHandle, const char* actionPath, MULTITREE_HANDLE commandNode)
{
EXECUTE_COMMAND_RESULT result;
char* relativeActionPath;
const char* actionName = actionPath;
SCHEMA_MODEL_TYPE_HANDLE modelHandle = commandDecoderInstance->ModelHandle;
/* Codes_SRS_COMMAND_DECODER_99_035:[ CommandDecoder_ExecuteCommand shall support paths to actions that are in child models (i.e. ChildModel/SomeAction.] */
do
{
/* find the slash */
const char* slashPos = strchr(actionName, '/');
if (slashPos == NULL)
{
size_t relativeActionPathLength;
/* Codes_SRS_COMMAND_DECODER_99_037:[ The relative path passed to the actionCallback shall be in the format "childModel1/childModel2/.../childModelN".] */
if (actionName == actionPath)
{
relativeActionPathLength = 0;
}
else
{
relativeActionPathLength = actionName - actionPath - 1;
}
relativeActionPath = (char*)malloc(relativeActionPathLength + 1);
if (relativeActionPath == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
LogError("Failed allocating relative action path");
result = EXECUTE_COMMAND_ERROR;
}
else
{
strncpy(relativeActionPath, actionPath, relativeActionPathLength);
relativeActionPath[relativeActionPathLength] = 0;
/* no slash found, this must be an action */
result = DecodeAndExecuteModelAction(commandDecoderInstance, schemaHandle, modelHandle, relativeActionPath, actionName, commandNode);
free(relativeActionPath);
actionName = NULL;
}
break;
}
else
{
/* found a slash, get the child model name */
size_t modelLength = slashPos - actionName;
char* childModelName = (char*)malloc(modelLength + 1);
if (childModelName == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
LogError("Failed allocating child model name");
result = EXECUTE_COMMAND_ERROR;
break;
}
else
{
strncpy(childModelName, actionName, modelLength);
childModelName[modelLength] = 0;
/* find the model */
modelHandle = Schema_GetModelModelByName(modelHandle, childModelName);
if (modelHandle == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_036:[ If a child model cannot be found by using Schema APIs then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
LogError("Getting the model %s failed", childModelName);
free(childModelName);
result = EXECUTE_COMMAND_ERROR;
break;
}
else
{
free(childModelName);
actionName = slashPos + 1;
result = EXECUTE_COMMAND_ERROR; /*this only exists to quench a compiler warning about returning an uninitialized variable, which is not possible by design*/
}
}
}
} while (actionName != NULL);
return result;
}
static METHODRETURN_HANDLE ScanMethodPathAndExecuteMethod(COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance, SCHEMA_HANDLE schemaHandle, const char* fullMethodName, MULTITREE_HANDLE methodTree)
{
METHODRETURN_HANDLE result;
char* relativeMethodPath;
const char* methodName = fullMethodName;
SCHEMA_MODEL_TYPE_HANDLE modelHandle = commandDecoderInstance->ModelHandle;
/*Codes_SRS_COMMAND_DECODER_02_018: [ CommandDecoder_ExecuteMethod shall validate that consecutive segments of the fullMethodName exist in the model. ]*/
/*Codes_SRS_COMMAND_DECODER_02_019: [ CommandDecoder_ExecuteMethod shall locate the final model to which the methodName applies. ]*/
do
{
/* find the slash */
const char* slashPos = strchr(methodName, '/');
if (slashPos == NULL)
{
size_t relativeMethodPathLength;
if (methodName == fullMethodName)
{
relativeMethodPathLength = 0;
}
else
{
relativeMethodPathLength = methodName - fullMethodName - 1;
}
relativeMethodPath = (char*)malloc(relativeMethodPathLength + 1);
if (relativeMethodPath == NULL)
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("Failed allocating relative method path");
result = NULL;
}
else
{
strncpy(relativeMethodPath, fullMethodName, relativeMethodPathLength);
relativeMethodPath[relativeMethodPathLength] = 0;
/* no slash found, this must be an method */
result = DecodeAndExecuteModelMethod(commandDecoderInstance, schemaHandle, modelHandle, relativeMethodPath, methodName, methodTree);
free(relativeMethodPath);
methodName = NULL;
}
break;
}
else
{
/* found a slash, get the child model name */
size_t modelLength = slashPos - methodName;
char* childModelName = (char*)malloc(modelLength + 1);
if (childModelName == NULL)
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("Failed allocating child model name");
result = NULL;
break;
}
else
{
strncpy(childModelName, methodName, modelLength);
childModelName[modelLength] = 0;
/* find the model */
modelHandle = Schema_GetModelModelByName(modelHandle, childModelName);
if (modelHandle == NULL)
{
/*Codes_SRS_COMMAND_DECODER_02_023: [ If any of the previous operations fail, then CommandDecoder_ExecuteMethod shall return NULL. ]*/
LogError("Getting the model %s failed", childModelName);
free(childModelName);
result = NULL;
break;
}
else
{
free(childModelName);
methodName = slashPos + 1;
result = NULL; /*this only exists to quench a compiler warning about returning an uninitialized variable, which is not possible by design*/
}
}
}
} while (methodName != NULL);
return result;
}
static EXECUTE_COMMAND_RESULT DecodeCommand(COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance, MULTITREE_HANDLE commandNode)
{
EXECUTE_COMMAND_RESULT result;
SCHEMA_HANDLE schemaHandle;
/* Codes_SRS_COMMAND_DECODER_99_022:[ CommandDecoder shall use the Schema APIs to obtain the information about the entity set name and namespace] */
if ((schemaHandle = Schema_GetSchemaForModelType(commandDecoderInstance->ModelHandle)) == NULL)
{
/* Codes_SRS_COMMAND_DECODER_99_010:[ If any Schema API fails then the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
LogError("Getting schema information failed");
result = EXECUTE_COMMAND_ERROR;
}
else
{
const char* actionName;
MULTITREE_HANDLE nameTreeNode;
/* Codes_SRS_COMMAND_DECODER_01_014: [CommandDecoder shall use the MultiTree APIs to extract a specific element from the command JSON.] */
/* Codes_SRS_COMMAND_DECODER_99_006:[ The action name shall be decoded from the element "name" of the command JSON.] */
if ((MultiTree_GetChildByName(commandNode, "Name", &nameTreeNode) != MULTITREE_OK) ||
(MultiTree_GetValue(nameTreeNode, (const void **)&actionName) != MULTITREE_OK))
{
/* Codes_SRS_COMMAND_DECODER_01_015: [If any MultiTree API call fails then the processing shall stop and the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
LogError("Getting action name failed.");
result = EXECUTE_COMMAND_ERROR;
}
else if (strlen(actionName) < 2)
{
/* Codes_SRS_COMMAND_DECODER_99_021:[ If the parsing of the command fails for any other reason the command shall not be dispatched.] */
LogError("Invalid action name.");
result = EXECUTE_COMMAND_ERROR;
}
else
{
actionName++;
result = ScanActionPathAndExecuteAction(commandDecoderInstance, schemaHandle, actionName, commandNode);
}
}
return result;
}
static METHODRETURN_HANDLE DecodeMethod(COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance, const char* fullMethodName, MULTITREE_HANDLE methodTree)
{
METHODRETURN_HANDLE result;
SCHEMA_HANDLE schemaHandle;
/*Codes_SRS_COMMAND_DECODER_02_017: [ CommandDecoder_ExecuteMethod shall get the SCHEMA_HANDLE associated with the modelHandle passed at CommandDecoder_Create. ]*/
if ((schemaHandle = Schema_GetSchemaForModelType(commandDecoderInstance->ModelHandle)) == NULL)
{
LogError("Getting schema information failed");
result = NULL;
}
else
{
result = ScanMethodPathAndExecuteMethod(commandDecoderInstance, schemaHandle, fullMethodName, methodTree);
}
return result;
}
/*Codes_SRS_COMMAND_DECODER_01_009: [Whenever CommandDecoder_ExecuteCommand is the command shall be decoded and further dispatched to the actionCallback passed in CommandDecoder_Create.]*/
EXECUTE_COMMAND_RESULT CommandDecoder_ExecuteCommand(COMMAND_DECODER_HANDLE handle, const char* command)
{
EXECUTE_COMMAND_RESULT result;
COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance = (COMMAND_DECODER_HANDLE_DATA*)handle;
/*Codes_SRS_COMMAND_DECODER_01_010: [If either the buffer or the receiveCallbackContext argument is NULL, the processing shall stop and the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
if (
(command == NULL) ||
(commandDecoderInstance == NULL)
)
{
LogError("Invalid argument, COMMAND_DECODER_HANDLE handle=%p, const char* command=%p", handle, command);
result = EXECUTE_COMMAND_ERROR;
}
else
{
size_t size = strlen(command);
char* commandJSON;
/* Codes_SRS_COMMAND_DECODER_01_011: [If the size of the command is 0 then the processing shall stop and the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
if (size == 0)
{
LogError("Failed because command size is zero");
result = EXECUTE_COMMAND_ERROR;
}
/*Codes_SRS_COMMAND_DECODER_01_013: [If parsing the JSON to a multi tree fails, the processing shall stop and the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.]*/
else if ((commandJSON = (char*)malloc(size + 1)) == NULL)
{
LogError("Failed to allocate temporary storage for the commands JSON");
result = EXECUTE_COMMAND_ERROR;
}
else
{
MULTITREE_HANDLE commandsTree;
(void)memcpy(commandJSON, command, size);
commandJSON[size] = '\0';
/* Codes_SRS_COMMAND_DECODER_01_012: [CommandDecoder shall decode the command JSON contained in buffer to a multi-tree by using JSONDecoder_JSON_To_MultiTree.] */
if (JSONDecoder_JSON_To_MultiTree(commandJSON, &commandsTree) != JSON_DECODER_OK)
{
/* Codes_SRS_COMMAND_DECODER_01_013: [If parsing the JSON to a multi tree fails, the processing shall stop and the command shall not be dispatched and it shall return EXECUTE_COMMAND_ERROR.] */
LogError("Decoding JSON to a multi tree failed");
result = EXECUTE_COMMAND_ERROR;
}
else
{
result = DecodeCommand(commandDecoderInstance, commandsTree);
/* Codes_SRS_COMMAND_DECODER_01_016: [CommandDecoder shall ensure that the multi-tree resulting from JSONDecoder_JSON_To_MultiTree is freed after the commands are executed.] */
MultiTree_Destroy(commandsTree);
}
free(commandJSON);
}
}
return result;
}
METHODRETURN_HANDLE CommandDecoder_ExecuteMethod(COMMAND_DECODER_HANDLE handle, const char* fullMethodName, const char* methodPayload)
{
METHODRETURN_HANDLE result;
/*Codes_SRS_COMMAND_DECODER_02_014: [ If handle is NULL then CommandDecoder_ExecuteMethod shall fail and return NULL. ]*/
/*Codes_SRS_COMMAND_DECODER_02_015: [ If fulMethodName is NULL then CommandDecoder_ExecuteMethod shall fail and return NULL. ]*/
if (
(handle == NULL) ||
(fullMethodName == NULL) /*methodPayload can be NULL*/
)
{
LogError("Invalid argument, COMMAND_DECODER_HANDLE handle=%p, const char* fullMethodName=%p", handle, fullMethodName);
result = NULL;
}
else
{
COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance = (COMMAND_DECODER_HANDLE_DATA*)handle;
/*Codes_SRS_COMMAND_DECODER_02_025: [ If methodCallback is NULL then CommandDecoder_ExecuteMethod shall fail and return NULL. ]*/
if (commandDecoderInstance->methodCallback == NULL)
{
LogError("unable to execute a method when the methodCallback passed in CommandDecoder_Create is NULL");
result = NULL;
}
else
{
/*Codes_SRS_COMMAND_DECODER_02_016: [ If methodPayload is not NULL then CommandDecoder_ExecuteMethod shall build a MULTITREE_HANDLE out of methodPayload. ]*/
if (methodPayload == NULL)
{
result = DecodeMethod(commandDecoderInstance, fullMethodName, NULL);
}
else
{
char* methodJSON;
if (mallocAndStrcpy_s(&methodJSON, methodPayload) != 0)
{
LogError("Failed to allocate temporary storage for the method JSON");
result = NULL;
}
else
{
//printf("%s %s\n", fullMethodName, methodJSON);
if (strcmp(methodJSON, "null") == 0) {
strcpy(methodJSON, "{}");
}
MULTITREE_HANDLE methodTree;
if (JSONDecoder_JSON_To_MultiTree(methodJSON, &methodTree) != JSON_DECODER_OK)
{
LogError("Decoding JSON to a multi tree failed");
result = NULL;
}
else
{
result = DecodeMethod(commandDecoderInstance, fullMethodName, methodTree);
MultiTree_Destroy(methodTree);
}
free(methodJSON);
}
}
}
}
return result;
}
COMMAND_DECODER_HANDLE CommandDecoder_Create(SCHEMA_MODEL_TYPE_HANDLE modelHandle, ACTION_CALLBACK_FUNC actionCallback, void* actionCallbackContext, METHOD_CALLBACK_FUNC methodCallback, void* methodCallbackContext)
{
COMMAND_DECODER_HANDLE_DATA* result;
/* Codes_SRS_COMMAND_DECODER_99_019:[ For all exposed APIs argument validity checks shall precede other checks.] */
/* Codes_SRS_COMMAND_DECODER_01_003: [ If modelHandle is NULL, CommandDecoder_Create shall return NULL. ]*/
if (modelHandle == NULL)
{
LogError("Invalid arguments: SCHEMA_MODEL_TYPE_HANDLE modelHandle=%p, ACTION_CALLBACK_FUNC actionCallback=%p, void* actionCallbackContext=%p, METHOD_CALLBACK_FUNC methodCallback=%p, void* methodCallbackContext=%p",
modelHandle, actionCallback, actionCallbackContext, methodCallback, methodCallbackContext);
result = NULL;
}
else
{
/* Codes_SRS_COMMAND_DECODER_01_001: [CommandDecoder_Create shall create a new instance of a CommandDecoder.] */
result = malloc(sizeof(COMMAND_DECODER_HANDLE_DATA));
if (result == NULL)
{
/* Codes_SRS_COMMAND_DECODER_01_004: [If any error is encountered during CommandDecoder_Create CommandDecoder_Create shall return NULL.] */
/*return as is*/
}
else
{
result->ModelHandle = modelHandle;
result->ActionCallback = actionCallback;
result->ActionCallbackContext = actionCallbackContext;
result->methodCallback = methodCallback;
result->methodCallbackContext = methodCallbackContext;
}
}
return result;
}
void CommandDecoder_Destroy(COMMAND_DECODER_HANDLE commandDecoderHandle)
{
/* Codes_SRS_COMMAND_DECODER_01_007: [If CommandDecoder_Destroy is called with a NULL handle, CommandDecoder_Destroy shall do nothing.] */
if (commandDecoderHandle != NULL)
{
COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance = (COMMAND_DECODER_HANDLE_DATA*)commandDecoderHandle;
/* Codes_SRS_COMMAND_DECODER_01_005: [CommandDecoder_Destroy shall free all resources associated with the commandDecoderHandle instance.] */
free(commandDecoderInstance);
}
}
MU_DEFINE_ENUM_STRINGS_WITHOUT_INVALID(AGENT_DATA_TYPE_TYPE, AGENT_DATA_TYPE_TYPE_VALUES);
/*validates that the multitree (coming from a JSON) is actually a serialization of the model (complete or incomplete)*/
/*if the serialization contains more than the model, then it fails.*/
/*if the serialization does not contain mandatory items from the model, it fails*/
static bool validateModel_vs_Multitree(void* startAddress, SCHEMA_MODEL_TYPE_HANDLE modelHandle, MULTITREE_HANDLE desiredPropertiesTree, size_t offset)
{
bool result;
size_t nChildren;
size_t nProcessedChildren = 0;
(void)MultiTree_GetChildCount(desiredPropertiesTree, &nChildren);
for (size_t i = 0;i < nChildren;i++)
{
MULTITREE_HANDLE child;
if (MultiTree_GetChild(desiredPropertiesTree, i, &child) != MULTITREE_OK)
{
LogError("failure in MultiTree_GetChild");
i = nChildren;
}
else
{
STRING_HANDLE childName = STRING_new();
if (childName == NULL)
{
LogError("failure to STRING_new");
i = nChildren;
}
else
{
if (MultiTree_GetName(child, childName) != MULTITREE_OK)
{
LogError("failure to MultiTree_GetName");
i = nChildren;
}
else
{
const char *childName_str = STRING_c_str(childName);
SCHEMA_MODEL_ELEMENT elementType = Schema_GetModelElementByName(modelHandle, childName_str);
switch (elementType.elementType)
{
default:
{
LogError("INTERNAL ERROR: unexpected function return");
i = nChildren;
break;
}
case (SCHEMA_PROPERTY):
{
LogError("cannot ingest name (WITH_DATA instead of WITH_DESIRED_PROPERTY): %s", childName_str);
i = nChildren;
break;
}
case (SCHEMA_REPORTED_PROPERTY):
{
LogError("cannot ingest name (WITH_REPORTED_PROPERTY instead of WITH_DESIRED_PROPERTY): %s", childName_str);
i = nChildren;
break;
}
case (SCHEMA_DESIRED_PROPERTY):
{
/*Codes_SRS_COMMAND_DECODER_02_007: [ If the child name corresponds to a desired property then an AGENT_DATA_TYPE shall be constructed from the MULTITREE node. ]*/
SCHEMA_DESIRED_PROPERTY_HANDLE desiredPropertyHandle = elementType.elementHandle.desiredPropertyHandle;
const char* desiredPropertyType = Schema_GetModelDesiredPropertyType(desiredPropertyHandle);
AGENT_DATA_TYPE output;
if (DecodeValueFromNode(Schema_GetSchemaForModelType(modelHandle), &output, child, desiredPropertyType) != 0)
{
LogError("failure in DecodeValueFromNode");
i = nChildren;
}
else
{
/*Codes_SRS_COMMAND_DECODER_02_008: [ The desired property shall be constructed in memory by calling pfDesiredPropertyFromAGENT_DATA_TYPE. ]*/
pfDesiredPropertyFromAGENT_DATA_TYPE leFunction = Schema_GetModelDesiredProperty_pfDesiredPropertyFromAGENT_DATA_TYPE(desiredPropertyHandle);
if (leFunction(&output, (char*)startAddress + offset + Schema_GetModelDesiredProperty_offset(desiredPropertyHandle)) != 0)
{
LogError("failure in a function that converts from AGENT_DATA_TYPE to C data");
}
else
{
/*Codes_SRS_COMMAND_DECODER_02_013: [ If the desired property has a non-NULL pfOnDesiredProperty then it shall be called. ]*/
pfOnDesiredProperty onDesiredProperty = Schema_GetModelDesiredProperty_pfOnDesiredProperty(desiredPropertyHandle);
if (onDesiredProperty != NULL)
{
onDesiredProperty((char*)startAddress + offset);
}
nProcessedChildren++;
}
Destroy_AGENT_DATA_TYPE(&output);
}
break;
}
case(SCHEMA_MODEL_IN_MODEL):
{
SCHEMA_MODEL_TYPE_HANDLE modelModel = elementType.elementHandle.modelHandle;
/*Codes_SRS_COMMAND_DECODER_02_009: [ If the child name corresponds to a model in model then the function shall call itself recursively. ]*/
if (!validateModel_vs_Multitree(startAddress, modelModel, child, offset + Schema_GetModelModelByName_Offset(modelHandle, childName_str)))
{
LogError("failure in validateModel_vs_Multitree");
i = nChildren;
}
else
{
/*if the model in model so happened to be a WITH_DESIRED_PROPERTY... (only those has non_NULL pfOnDesiredProperty) */
/*Codes_SRS_COMMAND_DECODER_02_012: [ If the child model in model has a non-NULL pfOnDesiredProperty then pfOnDesiredProperty shall be called. ]*/
pfOnDesiredProperty onDesiredProperty = Schema_GetModelModelByName_OnDesiredProperty(modelHandle, childName_str);
if (onDesiredProperty != NULL)
{
onDesiredProperty((char*)startAddress + offset);
}
nProcessedChildren++;
}
break;
}
} /*switch*/
}
STRING_delete(childName);
}
}
}
if(nProcessedChildren == nChildren)
{
/*Codes_SRS_COMMAND_DECODER_02_010: [ If the complete MULTITREE has been parsed then CommandDecoder_IngestDesiredProperties shall succeed and return EXECUTE_COMMAND_SUCCESS. ]*/
result = true;
}
else
{
/*Codes_SRS_COMMAND_DECODER_02_011: [ Otherwise CommandDecoder_IngestDesiredProperties shall fail and return EXECUTE_COMMAND_FAILED. ]*/
LogError("not all constituents of the JSON have been ingested");
result = false;
}
return result;
}
static EXECUTE_COMMAND_RESULT DecodeDesiredProperties(void* startAddress, COMMAND_DECODER_HANDLE_DATA* handle, MULTITREE_HANDLE desiredPropertiesTree)
{
/*Codes_SRS_COMMAND_DECODER_02_006: [ CommandDecoder_IngestDesiredProperties shall parse the MULTITREEE recursively. ]*/
return validateModel_vs_Multitree(startAddress, handle->ModelHandle, desiredPropertiesTree, 0 )?EXECUTE_COMMAND_SUCCESS:EXECUTE_COMMAND_FAILED;
}
/* Raw JSON has properties we don't need; potentially nodes other than "desired" for full TWIN as well as a $version we don't pass to callees */
static bool RemoveUnneededTwinProperties(MULTITREE_HANDLE initialParsedTree, bool parseDesiredNode, MULTITREE_HANDLE *desiredPropertiesTree)
{
MULTITREE_HANDLE updateTree;
bool result;
if (parseDesiredNode)
{
/*Codes_SRS_COMMAND_DECODER_02_014: [ If parseDesiredNode is TRUE, parse only the `desired` part of JSON tree ]*/
if (MultiTree_GetChildByName(initialParsedTree, "desired", &updateTree) != MULTITREE_OK)
{
LogError("Unable to find 'desired' in tree");
return false;
}
}
else
{
// Tree already starts on node we want so just use it.
updateTree = initialParsedTree;
}
/*Codes_COMMAND_DECODER_02_015: [ Remove '$version' string from node, if it is present. It not being present is not an error ]*/
MULTITREE_RESULT deleteChildResult = MultiTree_DeleteChild(updateTree, "$version");
if ((deleteChildResult == MULTITREE_OK) || (deleteChildResult == MULTITREE_CHILD_NOT_FOUND))
{
*desiredPropertiesTree = updateTree;
result = true;
}
else
{
*desiredPropertiesTree = NULL;
result = false;
}
return result;
}
EXECUTE_COMMAND_RESULT CommandDecoder_IngestDesiredProperties(void* startAddress, COMMAND_DECODER_HANDLE handle, const char* jsonPayload, bool parseDesiredNode)
{
EXECUTE_COMMAND_RESULT result;
/*Codes_SRS_COMMAND_DECODER_02_001: [ If startAddress is NULL then CommandDecoder_IngestDesiredProperties shall fail and return EXECUTE_COMMAND_ERROR. ]*/
/*Codes_SRS_COMMAND_DECODER_02_002: [ If handle is NULL then CommandDecoder_IngestDesiredProperties shall fail and return EXECUTE_COMMAND_ERROR. ]*/
/*Codes_SRS_COMMAND_DECODER_02_003: [ If jsonPayload is NULL then CommandDecoder_IngestDesiredProperties shall fail and return EXECUTE_COMMAND_ERROR. ]*/
if(
(startAddress == NULL) ||
(handle == NULL) ||
(jsonPayload == NULL)
)
{
LogError("invalid argument COMMAND_DECODER_HANDLE handle=%p, const char* jsonPayload=%p", handle, jsonPayload);
result = EXECUTE_COMMAND_ERROR;
}
else
{
/*Codes_SRS_COMMAND_DECODER_02_004: [ CommandDecoder_IngestDesiredProperties shall clone desiredProperties. ]*/
char* copy;
if (mallocAndStrcpy_s(©, jsonPayload) != 0)
{
LogError("failure in mallocAndStrcpy_s");
result = EXECUTE_COMMAND_FAILED;
}
else
{
/*Codes_SRS_COMMAND_DECODER_02_005: [ CommandDecoder_IngestDesiredProperties shall create a MULTITREE_HANDLE ouf of the clone of desiredProperties. ]*/
MULTITREE_HANDLE initialParsedTree;
MULTITREE_HANDLE desiredPropertiesTree;
if (JSONDecoder_JSON_To_MultiTree(copy, &initialParsedTree) != JSON_DECODER_OK)
{
LogError("Decoding JSON to a multi tree failed");
result = EXECUTE_COMMAND_ERROR;
}
else
{
if (RemoveUnneededTwinProperties(initialParsedTree, parseDesiredNode, &desiredPropertiesTree) == false)
{
LogError("Removing unneeded twin properties failed");
result = EXECUTE_COMMAND_ERROR;
}
else
{
COMMAND_DECODER_HANDLE_DATA* commandDecoderInstance = (COMMAND_DECODER_HANDLE_DATA*)handle;
/*Codes_SRS_COMMAND_DECODER_02_006: [ CommandDecoder_IngestDesiredProperties shall parse the MULTITREEE recursively. ]*/
result = DecodeDesiredProperties(startAddress, commandDecoderInstance, desiredPropertiesTree);
// Do NOT free desiredPropertiesTree. It is only a pointer into initialParsedTree.
MultiTree_Destroy(initialParsedTree);
}
}
free(copy);
}
}
return result;
}
| 48.516746 | 262 | 0.593649 |
65df8095bf2a264948f64303a5d8e82cbda8794c | 2,276 | h | C | arrus/core/devices/us4r/external/ius4oem/IUs4OEMInitializerImpl.h | us4useu/arrus | 10487b09f556e327ddb1bec28fbaccf3b8b08064 | [
"BSL-1.0",
"MIT"
] | 11 | 2021-02-04T19:56:08.000Z | 2022-02-18T09:41:51.000Z | arrus/core/devices/us4r/external/ius4oem/IUs4OEMInitializerImpl.h | us4useu/arrus | 10487b09f556e327ddb1bec28fbaccf3b8b08064 | [
"BSL-1.0",
"MIT"
] | 60 | 2020-11-06T04:59:06.000Z | 2022-03-12T17:39:06.000Z | arrus/core/devices/us4r/external/ius4oem/IUs4OEMInitializerImpl.h | us4useu/arrus | 10487b09f556e327ddb1bec28fbaccf3b8b08064 | [
"BSL-1.0",
"MIT"
] | 4 | 2021-07-22T16:13:06.000Z | 2021-12-13T08:53:31.000Z | #ifndef ARRUS_CORE_DEVICES_US4R_EXTERNAL_IUS4OEM_IUS4OEMINITIALIZERIMPL_H
#define ARRUS_CORE_DEVICES_US4R_EXTERNAL_IUS4OEM_IUS4OEMINITIALIZERIMPL_H
#include <algorithm>
#include <execution>
#include <mutex>
#include <iostream>
#include "IUs4OEMInitializer.h"
namespace arrus::devices {
class IUs4OEMInitializerImpl : public IUs4OEMInitializer {
public:
void initModules(std::vector<IUs4OEMHandle> &ius4oems) override {
// Reorder us4oems according to ids (us4oem with the lowest id is the
// first one, with the highest id - the last one).
// TODO(pjarosik) make the below sorting exception safe
// (currently will std::terminate on an exception).
std::sort(std::begin(ius4oems), std::end(ius4oems),
[](const IUs4OEMHandle &x, const IUs4OEMHandle &y) {
return x->GetID() < y->GetID();
});
initializeUs4oems(ius4oems, 1);
// Perform successive initialization levels.
for(int level = 2; level <= 4; level++) {
ius4oems[0]->Synchronize();
initializeUs4oems(ius4oems, level);
}
// Us4OEMs are initialized here.
}
private:
void initializeUs4oems(std::vector<IUs4OEMHandle> &ius4oems, int level) {
std::vector<std::exception> exceptions;
std::mutex exceptions_mutex;
std::for_each(
std::execution::par_unseq, std::begin(ius4oems), std::end(ius4oems),
[&](IUs4OEMHandle &u) {
try {
u->Initialize(level);
}
catch(const std::exception &e) {
std::lock_guard guard(exceptions_mutex);
exceptions.push_back(e);
}
catch(...) {
std::lock_guard guard(exceptions_mutex);
exceptions.push_back(std::runtime_error("Unknown exception during Us4OEM initialization."));
}
}
);
if(!exceptions.empty()) {
// TODO create a complete list of error messages
// now throw any of the exception
throw exceptions.front();
}
}
};
}
#endif //ARRUS_CORE_DEVICES_US4R_EXTERNAL_IUS4OEM_IUS4OEMINITIALIZERIMPL_H
| 34.484848 | 112 | 0.597979 |
a9028f3d597208abb2a99147bbe67ace2923aae0 | 946 | h | C | mlir/include/mlir/Dialect/PDL/IR/PDLTypes.h | Machiry/checkedc-clang | ab9360d8be0a737cb5e09051f3a0051adc4b3e47 | [
"BSD-Source-Code"
] | 250 | 2019-05-07T12:56:44.000Z | 2022-03-10T15:52:06.000Z | mlir/include/mlir/Dialect/PDL/IR/PDLTypes.h | procedural/checkedc_binaries_ubuntu_16_04_from_12_Oct_2021 | ad4e8b01121fbfb40d81ee798480add7dc93f0bf | [
"BSD-Source-Code"
] | 410 | 2019-06-06T20:52:32.000Z | 2022-01-18T14:21:48.000Z | mlir/include/mlir/Dialect/PDL/IR/PDLTypes.h | procedural/checkedc_binaries_ubuntu_16_04_from_12_Oct_2021 | ad4e8b01121fbfb40d81ee798480add7dc93f0bf | [
"BSD-Source-Code"
] | 50 | 2019-05-10T21:12:24.000Z | 2022-01-21T06:39:47.000Z | //===- PDLTypes.h - Pattern Descriptor Language Types -----------*- 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
//
//===----------------------------------------------------------------------===//
//
// This file defines the types for the Pattern Descriptor Language dialect.
//
//===----------------------------------------------------------------------===//
#ifndef MLIR_DIALECT_PDL_IR_PDLTYPES_H_
#define MLIR_DIALECT_PDL_IR_PDLTYPES_H_
#include "mlir/IR/Types.h"
//===----------------------------------------------------------------------===//
// PDL Dialect Types
//===----------------------------------------------------------------------===//
#define GET_TYPEDEF_CLASSES
#include "mlir/Dialect/PDL/IR/PDLOpsTypes.h.inc"
#endif // MLIR_DIALECT_PDL_IR_PDLTYPES_H_
| 36.384615 | 80 | 0.488372 |
455f10dd282e67d558fbd17e084cfaf6d9a276a3 | 1,427 | h | C | kernel/arch/sparc/leon3/timer.h | BaldLee/pok | 1e250f2730f7c1410b1a7a0bef12d6ba228b22a0 | [
"BSD-2-Clause"
] | 73 | 2015-02-02T13:35:08.000Z | 2022-03-29T19:28:10.000Z | kernel/arch/sparc/leon3/timer.h | leonhxx/pok | a2666ee6a4765f02db9e5fde43d665ec870fe7b8 | [
"BSD-2-Clause"
] | 25 | 2017-07-13T05:21:37.000Z | 2022-03-20T19:24:45.000Z | kernel/arch/sparc/leon3/timer.h | leonhxx/pok | a2666ee6a4765f02db9e5fde43d665ec870fe7b8 | [
"BSD-2-Clause"
] | 61 | 2015-03-03T13:41:32.000Z | 2022-03-29T19:28:29.000Z | /*
* POK header
*
* The following file is a part of the POK project. Any modification should
* be made according to the POK licence. You CANNOT use this file or a part
* of a file for your own project.
*
* For more information on the POK licence, please see our LICENCE FILE
*
* Please follow the coding guidelines described in doc/CODING_GUIDELINES
*
* Copyright (c) 2007-2021 POK team
*/
/**
* @file
* @author Fabien Chouteau
*/
#ifndef __POK_SPARC_LEON3_TIMER_H__
#define __POK_SPARC_LEON3_TIMER_H__
#define TIMER_CTRL_EN (1 << 0) /**< Enable */
#define TIMER_CTRL_RS (1 << 1) /**< Restart */
#define TIMER_CTRL_LD (1 << 2) /**< Load */
#define TIMER_CTRL_IE (1 << 3) /**< Interrupt enable */
#define TIMER_CTRL_IP (1 << 4) /**< Interrupt Pending */
#define TIMER_CTRL_CH (1 << 5) /**< Chain */
#define TIMER_CTRL_DH (1 << 6) /**< Debug Halt */
#define TIMER_SCALER_OFFSET 0x00 /**< Scaler value register offset */
#define TIMER_SCAL_RELOAD_OFFSET 0x04 /**< Scaler reload register offset */
#define TIMER_CNT_VAL_OFFSET 0x10 /**< Counter value register offset */
#define TIMER_RELOAD_OFFSET 0x14 /**< Counter reload register offset */
#define TIMER_CTRL_OFFSET 0x18 /**< Control register offset */
#define TIMER_IRQ 0x8U
#define TIMER1 0x80000300 /**< first Leon3 TIMER IO adress */
#endif /* __POK_SPARC_LEON3_TIMER_H__ */
| 33.186047 | 75 | 0.673441 |
04db318e6218d93100bd07c12bebc38e2bc1f138 | 7,203 | c | C | linux/net/core/request_sock.c | bradchesney79/illacceptanything | 4594ae4634fdb5e39263a6423dc255ed46c25208 | [
"MIT"
] | 2 | 2018-03-09T23:59:27.000Z | 2018-04-01T07:58:39.000Z | linux/net/core/request_sock.c | bradchesney79/illacceptanything | 4594ae4634fdb5e39263a6423dc255ed46c25208 | [
"MIT"
] | null | null | null | linux/net/core/request_sock.c | bradchesney79/illacceptanything | 4594ae4634fdb5e39263a6423dc255ed46c25208 | [
"MIT"
] | 3 | 2017-06-24T20:23:09.000Z | 2018-03-25T04:30:11.000Z | /*
* NET Generic infrastructure for Network protocols.
*
* Authors: Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* From code originally in include/net/tcp.h
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/tcp.h>
#include <linux/vmalloc.h>
#include <net/request_sock.h>
/*
* Maximum number of SYN_RECV sockets in queue per LISTEN socket.
* One SYN_RECV socket costs about 80bytes on a 32bit machine.
* It would be better to replace it with a global counter for all sockets
* but then some measure against one socket starving all other sockets
* would be needed.
*
* The minimum value of it is 128. Experiments with real servers show that
* it is absolutely not enough even at 100conn/sec. 256 cures most
* of problems.
* This value is adjusted to 128 for low memory machines,
* and it will increase in proportion to the memory of machine.
* Note : Dont forget somaxconn that may limit backlog too.
*/
int sysctl_max_syn_backlog = 256;
EXPORT_SYMBOL(sysctl_max_syn_backlog);
int reqsk_queue_alloc(struct request_sock_queue *queue,
unsigned int nr_table_entries)
{
size_t lopt_size = sizeof(struct listen_sock);
struct listen_sock *lopt = NULL;
nr_table_entries = min_t(u32, nr_table_entries, sysctl_max_syn_backlog);
nr_table_entries = max_t(u32, nr_table_entries, 8);
nr_table_entries = roundup_pow_of_two(nr_table_entries + 1);
lopt_size += nr_table_entries * sizeof(struct request_sock *);
if (lopt_size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
lopt = kzalloc(lopt_size, GFP_KERNEL |
__GFP_NOWARN |
__GFP_NORETRY);
if (!lopt)
lopt = vzalloc(lopt_size);
if (!lopt)
return -ENOMEM;
get_random_bytes(&lopt->hash_rnd, sizeof(lopt->hash_rnd));
rwlock_init(&queue->syn_wait_lock);
queue->rskq_accept_head = NULL;
lopt->nr_table_entries = nr_table_entries;
lopt->max_qlen_log = ilog2(nr_table_entries);
write_lock_bh(&queue->syn_wait_lock);
queue->listen_opt = lopt;
write_unlock_bh(&queue->syn_wait_lock);
return 0;
}
void __reqsk_queue_destroy(struct request_sock_queue *queue)
{
/* This is an error recovery path only, no locking needed */
kvfree(queue->listen_opt);
}
static inline struct listen_sock *reqsk_queue_yank_listen_sk(
struct request_sock_queue *queue)
{
struct listen_sock *lopt;
write_lock_bh(&queue->syn_wait_lock);
lopt = queue->listen_opt;
queue->listen_opt = NULL;
write_unlock_bh(&queue->syn_wait_lock);
return lopt;
}
void reqsk_queue_destroy(struct request_sock_queue *queue)
{
/* make all the listen_opt local to us */
struct listen_sock *lopt = reqsk_queue_yank_listen_sk(queue);
if (lopt->qlen != 0) {
unsigned int i;
for (i = 0; i < lopt->nr_table_entries; i++) {
struct request_sock *req;
while ((req = lopt->syn_table[i]) != NULL) {
lopt->syn_table[i] = req->dl_next;
lopt->qlen--;
reqsk_free(req);
}
}
}
WARN_ON(lopt->qlen != 0);
kvfree(lopt);
}
/*
* This function is called to set a Fast Open socket's "fastopen_rsk" field
* to NULL when a TFO socket no longer needs to access the request_sock.
* This happens only after 3WHS has been either completed or aborted (e.g.,
* RST is received).
*
* Before TFO, a child socket is created only after 3WHS is completed,
* hence it never needs to access the request_sock. things get a lot more
* complex with TFO. A child socket, accepted or not, has to access its
* request_sock for 3WHS processing, e.g., to retransmit SYN-ACK pkts,
* until 3WHS is either completed or aborted. Afterwards the req will stay
* until either the child socket is accepted, or in the rare case when the
* listener is closed before the child is accepted.
*
* In short, a request socket is only freed after BOTH 3WHS has completed
* (or aborted) and the child socket has been accepted (or listener closed).
* When a child socket is accepted, its corresponding req->sk is set to
* NULL since it's no longer needed. More importantly, "req->sk == NULL"
* will be used by the code below to determine if a child socket has been
* accepted or not, and the check is protected by the fastopenq->lock
* described below.
*
* Note that fastopen_rsk is only accessed from the child socket's context
* with its socket lock held. But a request_sock (req) can be accessed by
* both its child socket through fastopen_rsk, and a listener socket through
* icsk_accept_queue.rskq_accept_head. To protect the access a simple spin
* lock per listener "icsk->icsk_accept_queue.fastopenq->lock" is created.
* only in the rare case when both the listener and the child locks are held,
* e.g., in inet_csk_listen_stop() do we not need to acquire the lock.
* The lock also protects other fields such as fastopenq->qlen, which is
* decremented by this function when fastopen_rsk is no longer needed.
*
* Note that another solution was to simply use the existing socket lock
* from the listener. But first socket lock is difficult to use. It is not
* a simple spin lock - one must consider sock_owned_by_user() and arrange
* to use sk_add_backlog() stuff. But what really makes it infeasible is the
* locking hierarchy violation. E.g., inet_csk_listen_stop() may try to
* acquire a child's lock while holding listener's socket lock. A corner
* case might also exist in tcp_v4_hnd_req() that will trigger this locking
* order.
*
* When a TFO req is created, it needs to sock_hold its listener to prevent
* the latter data structure from going away.
*
* This function also sets "treq->listener" to NULL and unreference listener
* socket. treq->listener is used by the listener so it is protected by the
* fastopenq->lock in this function.
*/
void reqsk_fastopen_remove(struct sock *sk, struct request_sock *req,
bool reset)
{
struct sock *lsk = tcp_rsk(req)->listener;
struct fastopen_queue *fastopenq =
inet_csk(lsk)->icsk_accept_queue.fastopenq;
tcp_sk(sk)->fastopen_rsk = NULL;
spin_lock_bh(&fastopenq->lock);
fastopenq->qlen--;
tcp_rsk(req)->listener = NULL;
if (req->sk) /* the child socket hasn't been accepted yet */
goto out;
if (!reset || lsk->sk_state != TCP_LISTEN) {
/* If the listener has been closed don't bother with the
* special RST handling below.
*/
spin_unlock_bh(&fastopenq->lock);
sock_put(lsk);
reqsk_free(req);
return;
}
/* Wait for 60secs before removing a req that has triggered RST.
* This is a simple defense against TFO spoofing attack - by
* counting the req against fastopen.max_qlen, and disabling
* TFO when the qlen exceeds max_qlen.
*
* For more details see CoNext'11 "TCP Fast Open" paper.
*/
req->expires = jiffies + 60*HZ;
if (fastopenq->rskq_rst_head == NULL)
fastopenq->rskq_rst_head = req;
else
fastopenq->rskq_rst_tail->dl_next = req;
req->dl_next = NULL;
fastopenq->rskq_rst_tail = req;
fastopenq->qlen++;
out:
spin_unlock_bh(&fastopenq->lock);
sock_put(lsk);
}
| 34.966019 | 77 | 0.736776 |
3159732be7a2d027dda4e84ef4f02b536f8b17e5 | 19,580 | c | C | PHY62XX_SDK_2.0.1/components/ethermind/mesh/export/appl/model/client/appl_generic_property_client.c | sentervip/phy62xBleSDk2.0.1 | edbb43c98d3f27a584a0026a5aac8197d7a219d0 | [
"Apache-2.0"
] | 1 | 2020-12-14T19:47:20.000Z | 2020-12-14T19:47:20.000Z | PHY62XX_SDK_2.0.1/components/ethermind/mesh/export/appl/model/client/appl_generic_property_client.c | sentervip/phy62xBleSDk2.0.1 | edbb43c98d3f27a584a0026a5aac8197d7a219d0 | [
"Apache-2.0"
] | null | null | null | PHY62XX_SDK_2.0.1/components/ethermind/mesh/export/appl/model/client/appl_generic_property_client.c | sentervip/phy62xBleSDk2.0.1 | edbb43c98d3f27a584a0026a5aac8197d7a219d0 | [
"Apache-2.0"
] | null | null | null | /**
* \file appl_generic_property_client.c
*
* \brief This file defines the Mesh Generic Property Model Application Interface
* - includes Data Structures and Methods for Client.
*/
/*
* Copyright (C) 2018. Mindtree Ltd.
* All rights reserved.
*/
/* --------------------------------------------- Header File Inclusion */
#include "appl_generic_property_client.h"
/* --------------------------------------------- Global Definitions */
/* --------------------------------------------- Static Global Variables */
static const char main_generic_property_client_options[] = "\n\
======== Generic_Property Client Menu ========\n\
0. Exit. \n\
1. Refresh. \n\
\n\
10. Send Generic Admin Properties Get. \n\
11. Send Generic Admin Property Get. \n\
12. Send Generic Admin Property Set. \n\
13. Send Generic Admin Property Set Unacknowledged. \n\
14. Send Generic Client Properties Get. \n\
15. Send Generic Manufacturer Properties Get. \n\
16. Send Generic Manufacturer Property Get. \n\
17. Send Generic Manufacturer Property Set. \n\
18. Send Generic Manufacturer Property Set Unacknowledged. \n\
19. Send Generic User Properties Get. \n\
20. Send Generic User Property Get. \n\
21. Send Generic User Property Set. \n\
22. Send Generic User Property Set Unacknowledged. \n\
\n\
23. Get Model Handle. \n\
24. Set Publish Address. \n\
\n\
Your Option ? \0";
/* --------------------------------------------- External Global Variables */
static MS_ACCESS_MODEL_HANDLE appl_generic_property_client_model_handle;
/* --------------------------------------------- Function */
/* generic_property client application entry point */
void main_generic_property_client_operations(void)
{
int choice;
MS_ACCESS_ELEMENT_HANDLE element_handle;
static UCHAR model_initialized = 0x00;
/**
* Register with Access Layer.
*/
if (0x00 == model_initialized)
{
API_RESULT retval;
/* Use Default Element Handle. Index 0 */
element_handle = MS_ACCESS_DEFAULT_ELEMENT_HANDLE;
retval = MS_generic_property_client_init
(
element_handle,
&appl_generic_property_client_model_handle,
appl_generic_property_client_cb
);
if (API_SUCCESS == retval)
{
CONSOLE_OUT(
"Generic Property Client Initialized. Model Handle: 0x%04X\n",
appl_generic_property_client_model_handle);
}
else
{
CONSOLE_OUT(
"[ERR] Generic Property Client Initialization Failed. Result: 0x%04X\n",
retval);
}
model_initialized = 0x01;
}
MS_LOOP_FOREVER()
{
CONSOLE_OUT
("%s", main_generic_property_client_options);
CONSOLE_IN
("%d", &choice);
if (choice < 0)
{
CONSOLE_OUT
("*** Invalid Choice. Try Again.\n");
continue;
}
switch (choice)
{
case 0:
return;
case 1:
break;
case 10: /* Send Generic Admin Properties Get */
appl_send_generic_admin_properties_get();
break;
case 11: /* Send Generic Admin Property Get */
appl_send_generic_admin_property_get();
break;
case 12: /* Send Generic Admin Property Set */
appl_send_generic_admin_property_set();
break;
case 13: /* Send Generic Admin Property Set Unacknowledged */
appl_send_generic_admin_property_set_unacknowledged();
break;
case 14: /* Send Generic Client Properties Get */
appl_send_generic_client_properties_get();
break;
case 15: /* Send Generic Manufacturer Properties Get */
appl_send_generic_manufacturer_properties_get();
break;
case 16: /* Send Generic Manufacturer Property Get */
appl_send_generic_manufacturer_property_get();
break;
case 17: /* Send Generic Manufacturer Property Set */
appl_send_generic_manufacturer_property_set();
break;
case 18: /* Send Generic Manufacturer Property Set Unacknowledged */
appl_send_generic_manufacturer_property_set_unacknowledged();
break;
case 19: /* Send Generic User Properties Get */
appl_send_generic_user_properties_get();
break;
case 20: /* Send Generic User Property Get */
appl_send_generic_user_property_get();
break;
case 21: /* Send Generic User Property Set */
appl_send_generic_user_property_set();
break;
case 22: /* Send Generic User Property Set Unacknowledged */
appl_send_generic_user_property_set_unacknowledged();
break;
case 23: /* Get Model Handle */
appl_generic_property_client_get_model_handle();
break;
case 24: /* Set Publish Address */
appl_generic_property_client_set_publish_address();
break;
}
}
}
/* Send Generic Admin Properties Get */
void appl_send_generic_admin_properties_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Admin Properties Get\n");
retval = MS_generic_admin_properties_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Admin Property Get */
void appl_send_generic_admin_property_get(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_ADMIN_PROPERTY_GET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Admin Property Get\n");
CONSOLE_OUT
("Enter Admin Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.admin_property_id = (UINT16)choice;
retval = MS_generic_admin_property_get(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Admin Property Set */
void appl_send_generic_admin_property_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_ADMIN_PROPERTY_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Admin Property Set\n");
CONSOLE_OUT
("Enter Admin Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.admin_property_id = (UINT16)choice;
CONSOLE_OUT
("Enter Admin User Access (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.admin_user_access = (UCHAR)choice;
CONSOLE_OUT
("Enter Admin Property Value Length (in decimal)\n");
CONSOLE_IN
("%d", &choice);
CONSOLE_OUT
("Enter Admin Property Value (%d-octets in HEX)\n", (UINT16)choice);
{
UINT16 index, input_len;
input_len = (UINT16)choice;
param.admin_property_value = EM_alloc_mem(input_len);
if(NULL == param.admin_property_value)
{
CONSOLE_OUT
("Memory allocation failed for Admin Property Value. Returning\n");
return;
}
param.admin_property_value_len = (UINT16) input_len;
for(index = 0; index < input_len; index++)
{
CONSOLE_IN
("%x", &choice);
param.admin_property_value[index] = (UCHAR)choice;
}
}
retval = MS_generic_admin_property_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
if(NULL != param.admin_property_value)
{
EM_free_mem(param.admin_property_value);
}
}
/* Send Generic Admin Property Set Unacknowledged */
void appl_send_generic_admin_property_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_ADMIN_PROPERTY_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Admin Property Set Unacknowledged\n");
CONSOLE_OUT
("Enter Admin Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.admin_property_id = (UINT16)choice;
CONSOLE_OUT
("Enter Admin User Access (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.admin_user_access = (UCHAR)choice;
CONSOLE_OUT
("Enter Admin Property Value Length (in decimal)\n");
CONSOLE_IN
("%d", &choice);
CONSOLE_OUT
("Enter Admin Property Value (%d-octets in HEX)\n", (UINT16)choice);
{
UINT16 index, input_len;
input_len = (UINT16)choice;
param.admin_property_value = EM_alloc_mem(input_len);
if(NULL == param.admin_property_value)
{
CONSOLE_OUT
("Memory allocation failed for Admin Property Value. Returning\n");
return;
}
param.admin_property_value_len = (UINT16) input_len;
for(index = 0; index < input_len; index++)
{
CONSOLE_IN
("%x", &choice);
param.admin_property_value[index] = (UCHAR)choice;
}
}
retval = MS_generic_admin_property_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
if(NULL != param.admin_property_value)
{
EM_free_mem(param.admin_property_value);
}
}
/* Send Generic Client Properties Get */
void appl_send_generic_client_properties_get(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_CLIENT_PROPERTIES_GET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Client Properties Get\n");
CONSOLE_OUT
("Enter Client Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.client_property_id = (UINT16)choice;
retval = MS_generic_client_properties_get(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Manufacturer Properties Get */
void appl_send_generic_manufacturer_properties_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic Manufacturer Properties Get\n");
retval = MS_generic_manufacturer_properties_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Manufacturer Property Get */
void appl_send_generic_manufacturer_property_get(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_MANUFACTURER_PROPERTY_GET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Manufacturer Property Get\n");
CONSOLE_OUT
("Enter Manufacturer Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.manufacturer_property_id = (UINT16)choice;
retval = MS_generic_manufacturer_property_get(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Manufacturer Property Set */
void appl_send_generic_manufacturer_property_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_MANUFACTURER_PROPERTY_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Manufacturer Property Set\n");
CONSOLE_OUT
("Enter Manufacturer Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.manufacturer_property_id = (UINT16)choice;
CONSOLE_OUT
("Enter Manufacturer User Access (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.manufacturer_user_access = (UCHAR)choice;
retval = MS_generic_manufacturer_property_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic Manufacturer Property Set Unacknowledged */
void appl_send_generic_manufacturer_property_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_MANUFACTURER_PROPERTY_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic Manufacturer Property Set Unacknowledged\n");
CONSOLE_OUT
("Enter Manufacturer Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.manufacturer_property_id = (UINT16)choice;
CONSOLE_OUT
("Enter Manufacturer User Access (8-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.manufacturer_user_access = (UCHAR)choice;
retval = MS_generic_manufacturer_property_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic User Properties Get */
void appl_send_generic_user_properties_get(void)
{
API_RESULT retval;
CONSOLE_OUT
(">> Send Generic User Properties Get\n");
retval = MS_generic_user_properties_get();
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic User Property Get */
void appl_send_generic_user_property_get(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_USER_PROPERTY_GET_STRUCT param;
CONSOLE_OUT
(">> Send Generic User Property Get\n");
CONSOLE_OUT
("Enter User Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.user_property_id = (UINT16)choice;
retval = MS_generic_user_property_get(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
}
/* Send Generic User Property Set */
void appl_send_generic_user_property_set(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_USER_PROPERTY_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic User Property Set\n");
CONSOLE_OUT
("Enter User Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.user_property_id = (UINT16)choice;
CONSOLE_OUT
("Enter User Property Value Length (in decimal)\n");
CONSOLE_IN
("%d", &choice);
CONSOLE_OUT
("Enter User Property Value (%d-octets in HEX)\n", (UINT16)choice);
{
UINT16 index, input_len;
input_len = (UINT16)choice;
param.user_property_value = EM_alloc_mem(input_len);
if(NULL == param.user_property_value)
{
CONSOLE_OUT
("Memory allocation failed for User Property Value. Returning\n");
return;
}
param.user_property_value_len = (UINT16) input_len;
for(index = 0; index < input_len; index++)
{
CONSOLE_IN
("%x", &choice);
param.user_property_value[index] = (UCHAR)choice;
}
}
retval = MS_generic_user_property_set(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
if(NULL != param.user_property_value)
{
EM_free_mem(param.user_property_value);
}
}
/* Send Generic User Property Set Unacknowledged */
void appl_send_generic_user_property_set_unacknowledged(void)
{
API_RESULT retval;
int choice;
MS_GENERIC_USER_PROPERTY_SET_STRUCT param;
CONSOLE_OUT
(">> Send Generic User Property Set Unacknowledged\n");
CONSOLE_OUT
("Enter User Property ID (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
param.user_property_id = (UINT16)choice;
CONSOLE_OUT
("Enter User Property Value Length (in decimal)\n");
CONSOLE_IN
("%d", &choice);
CONSOLE_OUT
("Enter User Property Value (%d-octets in HEX)\n", (UINT16)choice);
{
UINT16 index, input_len;
input_len = (UINT16)choice;
param.user_property_value = EM_alloc_mem(input_len);
if(NULL == param.user_property_value)
{
CONSOLE_OUT
("Memory allocation failed for User Property Value. Returning\n");
return;
}
param.user_property_value_len = (UINT16) input_len;
for(index = 0; index < input_len; index++)
{
CONSOLE_IN
("%x", &choice);
param.user_property_value[index] = (UCHAR)choice;
}
}
retval = MS_generic_user_property_set_unacknowledged(¶m);
CONSOLE_OUT
("retval = 0x%04X\n", retval);
if(NULL != param.user_property_value)
{
EM_free_mem(param.user_property_value);
}
}
/* Get Model Handle */
void appl_generic_property_client_get_model_handle(void)
{
API_RESULT retval;
MS_ACCESS_MODEL_HANDLE model_handle;
retval = MS_generic_property_client_get_model_handle(&model_handle);
if (API_SUCCESS == retval)
{
CONSOLE_OUT
(">> Model Handle 0x%04X\n", model_handle);
}
else
{
CONSOLE_OUT
(">> Get Model Handle Failed. Status 0x%04X\n", retval);
}
return;
}
/* Set Publish Address */
void appl_generic_property_client_set_publish_address(void)
{
int choice;
API_RESULT retval;
MS_ACCESS_MODEL_HANDLE model_handle;
MS_ACCESS_PUBLISH_INFO publish_info;
/* Set Publish Information */
EM_mem_set(&publish_info, 0, sizeof(publish_info));
publish_info.addr.use_label = MS_FALSE;
CONSOLE_OUT
("Enter Model Handle (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
model_handle = (UINT16)choice;
CONSOLE_OUT
("Enter Generic_Property client Server Address (16-bit in HEX)\n");
CONSOLE_IN
("%x", &choice);
publish_info.addr.addr = (UINT16)choice;
CONSOLE_OUT
("Enter AppKey Index\n");
CONSOLE_IN
("%x", &choice);
publish_info.appkey_index = choice;
publish_info.remote = MS_FALSE;
retval = MS_access_cm_set_model_publication
(
model_handle,
&publish_info
);
if (API_SUCCESS == retval)
{
CONSOLE_OUT
(">> Publish Address is set Successfully.\n");
}
else
{
CONSOLE_OUT
(">> Failed to set publish address. Status 0x%04X\n", retval);
}
return;
}
/**
* \brief Client Application Asynchronous Notification Callback.
*
* \par Description
* Generic_Property client calls the registered callback to indicate events occurred to the application.
*
* \param [in] handle Model Handle.
* \param [in] opcode Opcode.
* \param [in] data_param Data associated with the event if any or NULL.
* \param [in] data_len Size of the event data. 0 if event data is NULL.
*/
API_RESULT appl_generic_property_client_cb
(
/* IN */ MS_ACCESS_MODEL_HANDLE * handle,
/* IN */ UINT32 opcode,
/* IN */ UCHAR * data_param,
/* IN */ UINT16 data_len
)
{
API_RESULT retval;
retval = API_SUCCESS;
CONSOLE_OUT (
"[GENERIC_PROPERTY_CLIENT] Callback. Opcode 0x%04X\n", opcode);
appl_dump_bytes(data_param, data_len);
switch(opcode)
{
case MS_ACCESS_GENERIC_ADMIN_PROPERTIES_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_ADMIN_PROPERTIES_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_ADMIN_PROPERTY_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_ADMIN_PROPERTY_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_CLIENT_PROPERTIES_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_CLIENT_PROPERTIES_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_MANUFACTURER_PROPERTIES_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_MANUFACTURER_PROPERTIES_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_MANUFACTURER_PROPERTY_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_MANUFACTURER_PROPERTY_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_USER_PROPERTIES_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_USER_PROPERTIES_STATUS_OPCODE\n");
}
break;
case MS_ACCESS_GENERIC_USER_PROPERTY_STATUS_OPCODE:
{
CONSOLE_OUT(
"MS_ACCESS_GENERIC_USER_PROPERTY_STATUS_OPCODE\n");
}
break;
}
return retval;
}
| 25.102564 | 104 | 0.62477 |
3173d584d43d35698949d340c157e426c440803f | 783 | c | C | libs/xlibc/unistd/mount.c | MUYIio/Mini-OS | cac8134f636e30a28d8c1da6a6c7c71366cc2618 | [
"MIT"
] | 5 | 2021-11-17T05:22:18.000Z | 2021-12-25T04:30:25.000Z | libs/xlibc/unistd/mount.c | MUYIio/Mini-OS | cac8134f636e30a28d8c1da6a6c7c71366cc2618 | [
"MIT"
] | null | null | null | libs/xlibc/unistd/mount.c | MUYIio/Mini-OS | cac8134f636e30a28d8c1da6a6c7c71366cc2618 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <types.h>
#include <stddef.h>
#include <string.h>
#include <math.h>
#include <sys/syscall.h>
int mount(
const char *source,
const char *target,
const char *fstype,
unsigned long flags
) {
if (source == NULL || target == NULL || fstype == NULL)
return -1;
return syscall4(int, SYS_MOUNT, source, target, fstype, flags);
}
int unmount(const char *source, unsigned long flags)
{
if (source == NULL)
return -1;
return syscall2(int, SYS_UNMOUNT, source, flags);
}
int mkfs(
const char *source,
const char *fstype,
unsigned long flags
) {
if (source == NULL || fstype == NULL)
return -1;
return syscall3(int, SYS_MKFS, source, fstype, flags);
}
| 21.75 | 68 | 0.597701 |
2ee600b1b992ce38522979a668dcc7b721a62c8f | 3,034 | h | C | OutPutHeaders/WXCSdkMultiTalkProxy.h | cocos543/WeChatTimeLineRobot | 1e93480e502e36ca9a21a506f481aa1fcb70ac4b | [
"MIT"
] | 106 | 2016-04-09T01:16:14.000Z | 2021-06-04T00:20:24.000Z | OutPutHeaders/WXCSdkMultiTalkProxy.h | cocos543/WeChatTimeLineRobot | 1e93480e502e36ca9a21a506f481aa1fcb70ac4b | [
"MIT"
] | 2 | 2017-06-13T09:41:29.000Z | 2018-03-26T03:32:07.000Z | OutPutHeaders/WXCSdkMultiTalkProxy.h | cocos543/WeChatTimeLineRobot | 1e93480e502e36ca9a21a506f481aa1fcb70ac4b | [
"MIT"
] | 58 | 2016-04-28T09:52:08.000Z | 2021-12-25T06:42:14.000Z | /**
* This header is generated by class-dump-z 0.2a.
* class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3.
*
* Source: (null)
*/
#import <XXUnknownSuperclass.h> // Unknown library
#import "IWXTalkExt.h"
@class NSString;
@interface WXCSdkMultiTalkProxy : XXUnknownSuperclass <IWXTalkExt> {
NSString* _tmpUniqueID;
NSString* _mUserName;
long _mUin;
}
@property(assign, nonatomic) long mUin;
@property(copy, nonatomic) NSString* mUserName;
@property(copy, nonatomic) NSString* tmpUniqueID;
-(void).cxx_destruct;
-(void)onMultiTalkRedirectOk;
-(id)convertGroupInfoItemListToGroupBriefInfoList:(id)groupBriefInfoList;
-(void)onMultiTalkAudioDeviceUnPlugin;
-(void)onMultiTalkAudioDevicePlugin;
-(void)onReceiveVideoMemberChangeMessage:(id)message extArray:(id)array;
-(void)onReceiveReawakeOrPokerMessage:(id)message extData:(id)data;
-(void)onRespPokerOrResumeFriend:(id)aFriend isSuccess:(BOOL)success;
-(void)onRespActiveGroupInfoItemList:(id)list isSuccess:(BOOL)success;
-(void)onCancelCreateMultiTalk:(id)talk;
-(void)onReceiveMissMultiTalk:(id)talk;
-(void)onInviteMultiTalk:(id)talk;
-(void)onVideoData:(unsigned long)data Bgra:(char*)bgra Width:(unsigned long)width Height:(unsigned long)height frontCamera:(BOOL)camera;
-(void)OnVideoStateChange:(BOOL)change VideoOn:(BOOL)on;
-(void)OnMuteStateChange:(BOOL)change;
-(void)OnSpeakerStateChange:(BOOL)change;
-(void)OnError:(id)error errorType:(int)type errorNo:(int)no;
-(void)OnRoomMemberChange:(id)change;
-(void)OnSysCallNotifyInterrupt:(int)interrupt;
-(void)OnInviteWXTalkModeResult:(BOOL)result groupId:(id)anId;
-(void)OnBeginStartDevice;
-(void)OnDeviceStartOK;
-(void)OnSelfAndOtherEntered;
-(void)OnReceiveOtherMemberTalkData;
-(void)OnDataConnectOK;
-(void)OnEnterTalkModeOK:(id)ok;
-(void)OnCreateTalkModeOKWithGroupId:(id)groupId;
-(id)getWXCMultiTalkMemberListWithVoiceGroupMemList:(id)voiceGroupMemList;
-(id)getWXCMultiTalkGroupWithRoomData:(id)roomData;
-(BOOL)requestActiveGroupBriefInfoList:(id)list;
-(long)getCurMultiTalkUin;
-(id)getCurMultiTalkUserName;
-(id)genMultiTalkClientGroupId;
-(BOOL)isMultiTalkWorking;
-(BOOL)holdMultiTalk:(BOOL)talk holdType:(int)type;
-(id)getTalkIngMember:(id)member;
-(BOOL)sendResumeFriendOrSendPokerToFriend:(id)aFriend friendUserName:(id)name extData:(id)data;
-(BOOL)modifyCutomMultiTalkGroupId:(id)anId grpName:(id)name;
-(BOOL)rejectMultiTalk:(id)talk;
-(BOOL)exitCurMultiTalk:(id)talk;
-(BOOL)addMultiTalkMemberToCurTalk:(id)curTalk wxGroupId:(id)anId addMemberList:(id)list;
-(BOOL)enterCurMultiTalk:(id)talk routId:(int)anId isAnswerCall:(BOOL)call;
-(BOOL)startCreateMultiTalk:(id)talk wxGroupId:(id)anId memberList:(id)list;
-(void)setCurMuteTalkInfo:(id)info uin:(long)uin;
-(int)VideoEncAndSend:(char*)send Length:(unsigned long)length Format:(void*)format resolutionMode:(int)mode cameraMode:(int)mode5;
-(BOOL)closeVideoRecvAndSend;
-(BOOL)setVideo:(BOOL)video;
-(BOOL)setMute:(BOOL)mute;
-(BOOL)getSpeakerStatus;
-(BOOL)setSpeaker:(BOOL)speaker;
-(void)dealloc;
-(id)init;
@end
| 40.453333 | 137 | 0.796638 |
c8cdec03d838fad924220ece189fcd8c5e51bcb6 | 644 | h | C | JsOCCall/JsCallOc/JsCallOc/LXJSMessageModel.h | leixiang1986/exercise_ios_projects | aafde468ba018115f3de233705e5e4683bced1b0 | [
"MIT"
] | null | null | null | JsOCCall/JsCallOc/JsCallOc/LXJSMessageModel.h | leixiang1986/exercise_ios_projects | aafde468ba018115f3de233705e5e4683bced1b0 | [
"MIT"
] | null | null | null | JsOCCall/JsCallOc/JsCallOc/LXJSMessageModel.h | leixiang1986/exercise_ios_projects | aafde468ba018115f3de233705e5e4683bced1b0 | [
"MIT"
] | null | null | null | //
// LXJSMessageModel.h
// JsCallOc
//
// Created by LeiXiang on 2021/9/11.
// Copyright © 2021 leixiang. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface LXJSMessageModel : NSObject
@property (nonatomic, copy) NSString *method;
@property (nonatomic, copy) NSDictionary *parameters;
@property (nonatomic, copy) NSString *callback;
///拼接参数后的方法
@property (nonatomic, copy, readonly) NSString *fullMethod;
+ (instancetype)messageModelWithBody:(NSDictionary *)body;
//回调方法
- (void)callbackWithResponse:(id)res webView:(WKWebView *)webView;
@end
NS_ASSUME_NONNULL_END
| 23 | 66 | 0.759317 |
ec8412db48c921ad650e4eea4494d8668498bcdb | 370 | h | C | src/Pred/BinPredicateFunction.h | mnowotnik/fovris | 82f692743fa6c96fef05041e686d716b03c22f07 | [
"BSD-3-Clause"
] | 4 | 2017-01-04T17:22:55.000Z | 2018-12-08T02:10:18.000Z | src/Pred/BinPredicateFunction.h | Mike-Now/fovris | 82f692743fa6c96fef05041e686d716b03c22f07 | [
"BSD-3-Clause"
] | null | null | null | src/Pred/BinPredicateFunction.h | Mike-Now/fovris | 82f692743fa6c96fef05041e686d716b03c22f07 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T05:26:13.000Z | 2022-03-24T05:26:13.000Z | #ifndef BINPREDICATEFUNCTION_H_2HWB3J8C
#define BINPREDICATEFUNCTION_H_2HWB3J8C
#include "PredicateFunction.h"
#include <memory>
#include <cstdint>
namespace fovris {
enum class BuiltinPredicate : uint8_t { Lt, Le, Gt, Ge, Eq, Neq };
PredicateFunction binDispatch(BuiltinPredicate pred);
} // fovris
#endif /* end of include guard: BINPREDICATEFUNCTION_H_2HWB3J8C */
| 26.428571 | 66 | 0.791892 |
0c07359188f842ac881008730b35009ce73d8327 | 24,413 | c | C | src/disp.c | ethinethin/MapGame | 62813c48eb2b19a7379a2740bede14516980ba2c | [
"BSD-3-Clause"
] | null | null | null | src/disp.c | ethinethin/MapGame | 62813c48eb2b19a7379a2740bede14516980ba2c | [
"BSD-3-Clause"
] | null | null | null | src/disp.c | ethinethin/MapGame | 62813c48eb2b19a7379a2740bede14516980ba2c | [
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <SDL2/SDL.h>
#include "disp.h"
#include "font.h"
#include "harv.h"
#include "loot.h"
#include "main.h"
#include "maps.h"
#include "play.h"
/* Structure for window position */
struct win_pos {
int x;
int y;
};
/* Function prototypes */
static void draw_player(struct game *cur_game, struct player *cur_player, struct win_pos win);
static void update_winpos(struct player *cur_player, struct win_pos win);
static void draw_player_indicator(struct game *cur_game, struct win_pos win, int size);
static void draw_inv(struct game *cur_game, struct player *cur_player);
static void draw_map(struct game *cur_game);
static struct win_pos find_win_pos(struct worldmap *map, struct player *cur_player);
static void load_sprites(struct game *cur_game);
static void unload_sprites(struct game *cur_game);
static void map_init(struct game *cur_game);
static void map_destroy(struct game *cur_game);
void
display_init(struct game *cur_game)
{
SDL_DisplayMode dm;
/* Create the main window */
if (cur_game->screen.displaymode == 0) {
SDL_GetDesktopDisplayMode(0, &dm);
cur_game->screen.w = dm.w;
cur_game->screen.h = dm.h;
cur_game->screen.window = SDL_CreateWindow(cur_game->screen.name, 0, 0, cur_game->screen.w, cur_game->screen.h, SDL_WINDOW_FULLSCREEN_DESKTOP);
} else if (cur_game->screen.displaymode == 1) {
cur_game->screen.window = SDL_CreateWindow(cur_game->screen.name, 0, 0, cur_game->screen.w, cur_game->screen.h, SDL_WINDOW_FULLSCREEN);
} else {
cur_game->screen.window = SDL_CreateWindow(cur_game->screen.name, 0, 0, cur_game->screen.w, cur_game->screen.h, SDL_WINDOW_SHOWN);
}
/* Set scale based on window width and height */
cur_game->screen.scale_x = cur_game->screen.w / 1280.0;
cur_game->screen.scale_y = cur_game->screen.h / 720.0;
/* Create renderer */
if (cur_game->screen.vsync == SDL_TRUE) {
cur_game->screen.renderer = SDL_CreateRenderer(cur_game->screen.window, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_TARGETTEXTURE|SDL_RENDERER_PRESENTVSYNC);
} else {
cur_game->screen.renderer = SDL_CreateRenderer(cur_game->screen.window, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_TARGETTEXTURE);
}
SDL_SetRenderDrawBlendMode(cur_game->screen.renderer, SDL_BLENDMODE_BLEND);
/* Poll for event */
SDL_Event event;
while (SDL_PollEvent(&event) == 1);
/* Load sprites and font */
load_sprites(cur_game);
load_font(cur_game);
/* Initialize worldmap */
map_init(cur_game);
/* Setup scanlines */
setup_scanlines(cur_game);
/* Create output texture */
cur_game->screen.output = SDL_CreateTexture(cur_game->screen.renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 1280, 720);
/* Clear screen */
SDL_SetRenderDrawColor(cur_game->screen.renderer, 0, 0, 0, 255);
SDL_RenderClear(cur_game->screen.renderer);
SDL_RenderPresent(cur_game->screen.renderer);
}
void
display_quit(struct game *cur_game)
{
/* Unload sprites, font, scanlines, and output */
unload_sprites(cur_game);
unload_font(cur_game);
SDL_DestroyTexture(cur_game->scanlines);
SDL_DestroyTexture(cur_game->screen.output);
/* Kill the world map texture */
map_destroy(cur_game);
/* Destroy renderer and window */
SDL_DestroyRenderer(cur_game->screen.renderer);
cur_game->screen.renderer = NULL;
SDL_DestroyWindow(cur_game->screen.window);
cur_game->screen.window = NULL;
}
void
draw_point(struct game *cur_game, int x, int y, char *col)
{
SDL_SetRenderDrawColor(cur_game->screen.renderer, *(col+0), *(col+1), *(col+2), 255);
SDL_RenderDrawPoint(cur_game->screen.renderer, x, y);
}
void
draw_line(struct game *cur_game, int x1, int y1, int x2, int y2, char *col)
{
SDL_SetRenderDrawColor(cur_game->screen.renderer, *(col+0), *(col+1), *(col+2), 255);
SDL_RenderDrawLine(cur_game->screen.renderer, x1, y1, x2, y2);
}
void
render_clear(struct game *cur_game)
{
/* Set the rendering target to the output texture and clear it */
SDL_SetRenderTarget(cur_game->screen.renderer, cur_game->screen.output);
SDL_SetRenderDrawColor(cur_game->screen.renderer, 0, 0, 0, 255);
SDL_RenderClear(cur_game->screen.renderer);
}
void
render_present(struct game *cur_game)
{
SDL_Rect src = { 0, 0, 1280, 720 };
SDL_Rect dest = { 0, 0, cur_game->screen.w, cur_game->screen.h };
/* Reset render target to the renderer */
SDL_SetRenderTarget(cur_game->screen.renderer, NULL);
/* Clear the renderer */
SDL_RenderClear(cur_game->screen.renderer);
/* Copy the output texture to the renderer */
SDL_RenderCopy(cur_game->screen.renderer, cur_game->screen.output, &src, &dest);
/* draw scanlines */
if (cur_game->screen.scanlines_on == SDL_TRUE) {
SDL_RenderCopy(cur_game->screen.renderer, cur_game->scanlines, NULL, &dest);
}
/* Present */
SDL_RenderPresent(cur_game->screen.renderer);
}
void
draw_rect(struct game *cur_game, unsigned int x, unsigned int y, unsigned int w, unsigned int h, SDL_bool fill, char *fill_col, SDL_bool border, char *bord_col)
{
SDL_Rect coords = { x, y, w, h };
SDL_SetRenderDrawColor(cur_game->screen.renderer, fill_col[0], fill_col[1], fill_col[2], 255);
/* Draw filled rectangle? */
if (fill) {
SDL_RenderFillRect(cur_game->screen.renderer, &coords);
} else {
SDL_RenderDrawRect(cur_game->screen.renderer, &coords);
}
/* Draw border? */
if (border && bord_col != NULL) {
SDL_SetRenderDrawColor(cur_game->screen.renderer, bord_col[0], bord_col[1], bord_col[2], 0xFF);
SDL_RenderDrawRect(cur_game->screen.renderer, &coords);
}
}
void
draw_tile(struct game *cur_game, int x, int y, int w, int h, int sprite_index, unsigned char alpha)
{
SDL_Rect rect = {x, y, w, h};
if (alpha != 255) SDL_SetTextureAlphaMod(cur_game->sprite_textures[sprite_index], alpha);
SDL_RenderCopy(cur_game->screen.renderer, cur_game->sprite_textures[sprite_index], NULL, &rect);
if (alpha != 255) SDL_SetTextureAlphaMod(cur_game->sprite_textures[sprite_index], 255);
}
void
draw_all(struct game *cur_game, struct worldmap *map, struct player *cur_player)
{
char white[3] = { 255, 255, 255 };
draw_game(cur_game, map, cur_player);
draw_rect(cur_game, GAME_X, GAME_Y, GAME_W, GAME_H, SDL_FALSE, white, SDL_FALSE, NULL);
render_present(cur_game);
}
void
draw_game(struct game *cur_game, struct worldmap *map, struct player *cur_player)
{
char loot_type;
int rows, cols;
short int sprite_index;
struct win_pos win;
short int alpha;
SDL_bool harvestable;
/* Update window position */
win = find_win_pos(map, cur_player);
/* Update player winpos */
update_winpos(cur_player, win);
/* Update screen view */
check_if_inside(map, cur_player);
/* Draw game tiles on screen */
render_clear(cur_game);
for (rows = win.y; rows < win.y+WIN_ROWS; rows++) {
for (cols = win.x; cols < win.x+WIN_COLS; cols++) {
/* Check if there's ground */
if (*(*(map->ground+rows)+cols) != 0) {
sprite_index = get_loot_sprite(*(*(map->ground+rows)+cols));
alpha = 255;
} else {
sprite_index = get_sprite(*(*(map->tile+rows)+cols),
*(*(map->biome+rows)+cols));
/* Change sprite index based on frame */
sprite_index += *(*(map->frame+rows)+cols);
harvestable = is_harvestable(map, cols, rows);
if (harvestable == SDL_TRUE) {
alpha = 255;
} else {
alpha = 96;
}
}
/* Draw ground tile */
draw_tile(cur_game, (cols - win.x) * SPRITE_W * WIN_SCALE + GAME_X, (rows - win.y) * SPRITE_H * WIN_SCALE + GAME_Y, SPRITE_W * WIN_SCALE, SPRITE_H * WIN_SCALE, sprite_index, alpha);
/* Draw loot */
if (*(*(map->loot+rows)+cols) != 0) {
sprite_index = get_loot_sprite(*(*(map->loot+rows)+cols));
loot_type = get_loot_type(*(*(map->loot+rows)+cols));
if (*(*(map->quantity+rows)+cols) > 1 || loot_type == ITEM || loot_type == GROUND || loot_type == ROOF) {
draw_tile(cur_game, (cols - win.x) * SPRITE_W * WIN_SCALE + GAME_X + SPRITE_W * WIN_SCALE / 4, (rows - win.y) * SPRITE_H * WIN_SCALE + GAME_Y + SPRITE_W * WIN_SCALE / 4, SPRITE_W * WIN_SCALE / 2, SPRITE_H * WIN_SCALE / 2, sprite_index, 255);
} else if (loot_type == WALL || loot_type == C_DOOR || loot_type == O_DOOR || loot_type == HOLDER) {
draw_tile(cur_game, (cols - win.x) * SPRITE_W * WIN_SCALE + GAME_X, (rows - win.y) * SPRITE_H * WIN_SCALE + GAME_Y, SPRITE_W * WIN_SCALE, SPRITE_H * WIN_SCALE, sprite_index, 255);
}
}
/* Check if there's a roof and draw it */
if (*(*(map->roof+rows)+cols) != 0) {
if (*(*(cur_player->screen_view+(rows - win.y))+(cols - win.x)) == 0) {
alpha = 255;
} else {
alpha = 32;
}
sprite_index = get_loot_sprite(*(*(map->roof+rows)+cols));
draw_tile(cur_game, (cols - win.x) * SPRITE_W * WIN_SCALE + GAME_X, (rows - win.y) * SPRITE_H * WIN_SCALE + GAME_Y, SPRITE_W * WIN_SCALE, SPRITE_H * WIN_SCALE, sprite_index, alpha);
}
}
}
draw_player(cur_game, cur_player, win);
draw_inv(cur_game, cur_player);
/* Process frames for animation */
process_frames(map, win.y, win.x);
}
static void
draw_player(struct game *cur_game, struct player *cur_player, struct win_pos win)
{
draw_tile(cur_game,
(cur_player->x * SPRITE_W * WIN_SCALE - win.x * SPRITE_W * WIN_SCALE + GAME_X),
(cur_player->y * SPRITE_H * WIN_SCALE - win.y * SPRITE_H * WIN_SCALE + GAME_Y),
SPRITE_W * WIN_SCALE, SPRITE_H * WIN_SCALE, 334, 255);
}
static void
update_winpos(struct player *cur_player, struct win_pos win)
{
cur_player->winpos_x = (cur_player->x - win.x);
cur_player->winpos_y = (cur_player->y - win.y);
}
static void
draw_inv(struct game *cur_game, struct player *cur_player)
{
int i, j, k;
short int sprite_index;
char stackable;
char darkred[3] = { 128, 0, 0 };
char white[3] = { 255, 255, 255 };
char black[3] = { 0, 0, 0 };
char quantity[4];
/* Draw quick bar */
draw_rect(cur_game, QB_X, QB_Y, QB_W + 1, QB_H, SDL_TRUE, black, SDL_TRUE, white);
for (i = 0; i < 8; i++) {
draw_line(cur_game,
(QB_X + i * SPRITE_W * WIN_SCALE),
QB_Y,
(QB_X + i * SPRITE_W * WIN_SCALE),
(QB_Y + SPRITE_H * WIN_SCALE * 1.25),
white);
if (cur_player->loot[i] != 0) {
sprite_index = get_loot_sprite(cur_player->loot[i]);
draw_tile(cur_game,
QB_X + i * SPRITE_W * WIN_SCALE + 1,
QB_Y + 2,
SPRITE_W * WIN_SCALE, SPRITE_H * WIN_SCALE,
sprite_index,
255);
stackable = is_loot_stackable(cur_player->loot[i]);
if (stackable == STACKABLE) {
sprintf(quantity, "%3d", cur_player->quantity[i]);
draw_small_sentence(cur_game,
QB_X + i * SPRITE_W * WIN_SCALE + 30,
QB_Y + SPRITE_H * WIN_SCALE + 2,
quantity);
}
}
}
/* Draw cursor */
if (cur_game->cursor <= 7) {
for (i = 1; i < 5; i++) {
draw_rect(cur_game, QB_X + SPRITE_W * WIN_SCALE * cur_game->cursor - i, QB_Y - i, SPRITE_W * WIN_SCALE + 1 + i*2, SPRITE_H * WIN_SCALE * 1.25 + i*2, SDL_FALSE, darkred, SDL_FALSE, NULL);
}
}
/* Draw inventory? */
if (cur_game->inventory == SDL_FALSE) return;
/* Draw inventory rectangle */
draw_rect(cur_game, INV_X, INV_Y, INV_W, INV_H, SDL_TRUE, black, SDL_TRUE, white);
/* Draw "Items" text box */
draw_rect(cur_game, INV_X, (INV_Y - 20), INV_W, (18 + 3), SDL_TRUE, black, SDL_TRUE, white);
draw_small_sentence(cur_game, (INV_X + 2), (INV_Y - 16), "INVENTORY");
/* Draw "X" for closing inventory */
draw_line(cur_game, (INV_X + INV_W - 15), (INV_Y - 15), (INV_X + INV_W - 5), (INV_Y - 5), white);
draw_line(cur_game, (INV_X + INV_W - 6), (INV_Y - 15), (INV_X + INV_W - 16), (INV_Y - 5), white);
/* Draw grid */
for (i = 0; i < 8; i++) {
draw_line(cur_game,
INV_X,
(INV_Y + SPRITE_H * WIN_SCALE * 1.25 * i),
(INV_X + INV_W),
(INV_Y + SPRITE_H * WIN_SCALE * 1.25 * i),
white);
}
for (i = 1; i < 4; i++) {
draw_line(cur_game,
INV_X + i * SPRITE_W * WIN_SCALE, INV_Y,
INV_X + i * SPRITE_W * WIN_SCALE, INV_Y + INV_H, white);
}
/* Draw items */
for (i = 0; i < 4; i++) {
for (j = 0; j < 8; j++) {
if (cur_player->loot[j+i*8+8] != 0) {
sprite_index = get_loot_sprite(cur_player->loot[j+i*8+8]);
draw_tile(cur_game,
INV_X + SPRITE_W * WIN_SCALE * i + 1,
INV_Y + SPRITE_H * WIN_SCALE * 1.25 * j + 2,
SPRITE_W * WIN_SCALE, SPRITE_H * WIN_SCALE,
sprite_index,
255);
stackable = is_loot_stackable(cur_player->loot[j+i*8+8]);
if (stackable == STACKABLE) {
sprintf(quantity, "%3d", cur_player->quantity[j+i*8+8]);
draw_small_sentence(cur_game,
INV_X + i * SPRITE_W * WIN_SCALE + 30,
INV_Y + SPRITE_H * WIN_SCALE * 1.25 * j + 2 + SPRITE_H * WIN_SCALE,
quantity);
}
}
}
}
/* Draw cursor */
if (cur_game->cursor > 7) {
/* Determine horizontal position */
if (cur_game->cursor >= 8 && cur_game->cursor < 16) {
j = INV_X;
} else if (cur_game->cursor >= 16 && cur_game->cursor < 24) {
j = INV_X + SPRITE_W * WIN_SCALE;
} else if (cur_game->cursor >= 24 && cur_game->cursor < 32) {
j = INV_X + SPRITE_W * WIN_SCALE * 2;
} else if (cur_game->cursor >= 32 && cur_game->cursor < 40) {
j = INV_X + SPRITE_W * WIN_SCALE * 3;
} else {
return;
}
/* Determine vertical position */
i = INV_Y + SPRITE_H * WIN_SCALE * 1.25 * (cur_game->cursor % 8);
/* Draw cursor */
for (k = 1; k < 5; k++) {
draw_rect(cur_game, j - k, i - k, SPRITE_W * WIN_SCALE + k*2 + 1, SPRITE_H * WIN_SCALE * 1.25 + k*2 + 1, SDL_FALSE, darkred, SDL_FALSE, NULL);
}
}
}
static void
draw_map(struct game *cur_game)
{
char white[3] = { 255, 255, 255 };
char black[3] = { 0, 0, 0 };
SDL_Rect rect = { MAP_X, MAP_Y,
MAP_W, MAP_H };
/* Draw map */
draw_rect(cur_game,
MAP_X, MAP_Y,
MAP_W, MAP_H,
SDL_TRUE, black, SDL_TRUE, white);
SDL_RenderCopy(cur_game->screen.renderer, cur_game->map_texture, NULL, &rect);
/* Draw map border */
draw_rect(cur_game, MAP_X, MAP_Y, MAP_W, MAP_H, SDL_FALSE, white, SDL_FALSE, NULL);
}
static void
draw_player_indicator(struct game *cur_game, struct win_pos win, int size)
{
char red[3] = { 255, 0, 0 };
int w_size;
int h_size;
/* Draw player indicator */
w_size = size * 1;
h_size = size * WIN_ROWS / WIN_COLS;
draw_rect(cur_game,
(MAP_X + win.x + WIN_COLS/2 - w_size/2),
(MAP_Y + win.y + WIN_ROWS/2 - h_size/2),
w_size, h_size, SDL_FALSE, red, SDL_FALSE, NULL);
draw_rect(cur_game,
(MAP_X + win.x + WIN_COLS/2 - w_size/2 - 1),
(MAP_Y + win.y + WIN_ROWS/2 - h_size/2 - 1),
(w_size + 2),
(h_size + 2),
SDL_FALSE, red, SDL_FALSE, NULL);
}
static struct win_pos
find_win_pos(struct worldmap *map, struct player *cur_player)
{
struct win_pos win;
/* Find where the window position starts; x/y values = world x/y */
win.x = cur_player->x - WIN_COLS/2;
win.y = cur_player->y - WIN_ROWS/2;
/* correct x value */
if (win.x < 0) {
win.x = 0;
} else if (win.x > map->col_size - WIN_COLS) {
win.x = map->col_size - WIN_COLS;
}
/* correct y value */
if (win.y < 0) {
win.y = 0;
} else if (win.y > map->row_size - WIN_ROWS) {
win.y = map->row_size - WIN_ROWS;
}
return win;
}
void
worldmap(struct game *cur_game, struct worldmap *map, struct player *cur_player)
{
char black[3] = { 0, 0, 0 };
char white[3] = { 255, 255, 255 };
struct win_pos win;
/* Find window position */
win = find_win_pos(map, cur_player);
/* Wait for user input */
SDL_Event event;
int size = 1;
int size_change = 2;
while (SDL_TRUE) {
/* Redraw screen */
draw_game(cur_game, map, cur_player);
/* Draw map */
draw_map(cur_game);
draw_rect(cur_game, GAME_X, GAME_Y, GAME_W, GAME_H, SDL_FALSE, white, SDL_FALSE, NULL);
/* Write "Map" at the top of the screen with an X */
draw_rect(cur_game, MAP_X, (MAP_Y - 20), MAP_W, (18 + 2 + 1), SDL_TRUE, black, SDL_TRUE, white);
draw_sentence(cur_game, (MAP_X + 1), (MAP_Y - 19), "WORLD MAP");
draw_line(cur_game, (MAP_X + MAP_W - 15), (MAP_Y - 15), (MAP_X + MAP_W - 5), (MAP_Y - 5), white);
draw_line(cur_game, (MAP_X + MAP_W - 6), (MAP_Y - 15), (MAP_X + MAP_W - 16), (MAP_Y - 5), white);
/* Draw player indicator, render, and change size */
draw_player_indicator(cur_game, win, size);
render_present(cur_game);
SDL_Delay(10);
size += size_change;
if (size >= WIN_COLS) {
size_change = -2;
} else if (size <= 1) {
size_change = 2;
}
/* Poll for input */
if (SDL_PollEvent(&event) == 0) continue;
if (event.type == SDL_KEYDOWN || event.type == SDL_MOUSEBUTTONDOWN) {
return;
}
}
}
void
setup_scanlines(struct game *cur_game)
{
int i;
/* Destroy scanlines if they already exist */
if (cur_game->scanlines != NULL) SDL_DestroyTexture(cur_game->scanlines);
/* Create scanlines as a texture */
cur_game->scanlines = SDL_CreateTexture(cur_game->screen.renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET, cur_game->screen.w, cur_game->screen.h);
SDL_SetRenderTarget(cur_game->screen.renderer, cur_game->scanlines);
SDL_SetTextureBlendMode(cur_game->scanlines, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(cur_game->screen.renderer, 0, 0, 0, 128);
for (i = 0; i < cur_game->screen.h; i += 3) {
SDL_RenderDrawLine(cur_game->screen.renderer, 0, i, cur_game->screen.w, i);
}
SDL_SetRenderTarget(cur_game->screen.renderer, NULL);
}
void
toggle_scanlines(struct game *cur_game)
{
cur_game->screen.scanlines_on = !cur_game->screen.scanlines_on;
}
#define TMP_NUMSPRITES 584
static void
load_sprites(struct game *cur_game)
{
/* Load placeholder sprites */
SDL_Surface *surface = SDL_LoadBMP("art/sprites.bmp");
SDL_Surface **tiles, *tile;
tiles = (SDL_Surface**) malloc(sizeof(SDL_Surface*)*TMP_NUMSPRITES);
cur_game->sprite_textures = (SDL_Texture**) malloc(sizeof(SDL_Texture*)*TMP_NUMSPRITES);
int i, j;
SDL_Rect rect = {0, 0, SPRITE_W, SPRITE_H};
for (i = 0; i < 16; i++) {
for (j = 0; j < 32; j++) {
tiles[(i*32)+j] = SDL_CreateRGBSurface(0, SPRITE_W, SPRITE_H, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tiles[(i*32)+j], 1, 0x000000);
SDL_FillRect(tiles[(i*32)+j], 0, 0x000000);
rect.x = j * SPRITE_W;
rect.y = i * SPRITE_H;
SDL_BlitSurface(surface, &rect, tiles[(i*32)+j], NULL);
cur_game->sprite_textures[(i*32)+j] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tiles[(i*32)+j]);
}
}
SDL_FreeSurface(surface);
/* Load custom sprites I designed */
surface = SDL_LoadBMP("art/grass.bmp");
rect.y = 0;
for (i = 0; i < 16; i++) {
tiles[512+i] = SDL_CreateRGBSurface(0, SPRITE_W, SPRITE_H, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tiles[512+i], 1, 0x000000);
SDL_FillRect(tiles[512+i], 0, 0x000000);
rect.x = i * SPRITE_W;
SDL_BlitSurface(surface, &rect, tiles[512+i], NULL);
cur_game->sprite_textures[512+i] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tiles[512+i]);
}
SDL_FreeSurface(surface);
/* Load custom sprites I designed */
surface = SDL_LoadBMP("art/desert.bmp");
rect.y = 0;
for (i = 0; i < 32; i++) {
tiles[528+i] = SDL_CreateRGBSurface(0, SPRITE_W, SPRITE_H, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tiles[528+i], 1, 0x000000);
SDL_FillRect(tiles[528+i], 0, 0x000000);
rect.x = i * SPRITE_W;
SDL_BlitSurface(surface, &rect, tiles[528+i], NULL);
cur_game->sprite_textures[528+i] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tiles[528+i]);
}
SDL_FreeSurface(surface);
/* Load custom sprites I designed */
surface = SDL_LoadBMP("art/grass_items.bmp");
rect.y = 0;
for (i = 0; i < 15; i++) {
tiles[560+i] = SDL_CreateRGBSurface(0, SPRITE_W, SPRITE_H, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tiles[560+i], 1, 0xFF00FF);
SDL_FillRect(tiles[560+i], 0, 0xFF00FF);
rect.x = i * SPRITE_W;
SDL_BlitSurface(surface, &rect, tiles[560+i], NULL);
cur_game->sprite_textures[560+i] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tiles[560+i]);
}
SDL_FreeSurface(surface);
/* Load custom sprites I designed */
surface = SDL_LoadBMP("art/items.bmp");
rect.y = 0;
for (i = 0; i < 9; i++) {
tiles[575+i] = SDL_CreateRGBSurface(0, SPRITE_W, SPRITE_H, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tiles[575+i], 1, 0xFF00FF);
SDL_FillRect(tiles[575+i], 0, 0xFF00FF);
rect.x = i * SPRITE_W;
SDL_BlitSurface(surface, &rect, tiles[575+i], NULL);
cur_game->sprite_textures[575+i] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tiles[575+i]);
}
/* Free surface tiles from memory */
SDL_FreeSurface(surface);
for (i = 0; i < TMP_NUMSPRITES; i++) {
SDL_FreeSurface(tiles[i]);
}
free(tiles);
/* Load crafting buttons */
cur_game->craft = (SDL_Texture**) malloc(sizeof(SDL_Texture*)*7);
surface = SDL_LoadBMP("art/craft.bmp");
rect.x = 0; rect.y = 0; rect.w = 451; rect.h = 287;
tile = SDL_CreateRGBSurface(0, 451, 287, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tile, 1, 0xFF00FF);
SDL_FillRect(tile, 0, 0xFF00FF);
SDL_BlitSurface(surface, &rect, tile, NULL);
cur_game->craft[0] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tile);
SDL_FreeSurface(surface);
SDL_FreeSurface(tile);
/* No crafting buttons */
surface = SDL_LoadBMP("art/no_craft.bmp");
tile = SDL_CreateRGBSurface(0, 451, 287, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tile, 1, 0xFF00FF);
SDL_FillRect(tile, 0, 0xFF00FF);
SDL_BlitSurface(surface, &rect, tile, NULL);
cur_game->craft[1] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tile);
SDL_FreeSurface(surface);
SDL_FreeSurface(tile);
/* Load scroll buttons */
surface = SDL_LoadBMP("art/scroll_craft.bmp");
rect.x = 0; rect.y = 0; rect.w = 69; rect.h = 69;
tile = SDL_CreateRGBSurface(0, 69, 69, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tile, 1, 0xFF00FF);
SDL_FillRect(tile, 0, 0xFF00FF);
SDL_BlitSurface(surface, &rect, tile, NULL);
cur_game->craft[2] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tile);
SDL_FreeSurface(tile);
rect.x = 69;
tile = SDL_CreateRGBSurface(0, 69, 69, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tile, 1, 0xFF00FF);
SDL_FillRect(tile, 0, 0xFF00FF);
SDL_BlitSurface(surface, &rect, tile, NULL);
cur_game->craft[3] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tile);
SDL_FreeSurface(tile);
rect.x = 138;
tile = SDL_CreateRGBSurface(0, 69, 69, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tile, 1, 0xFF00FF);
SDL_FillRect(tile, 0, 0xFF00FF);
SDL_BlitSurface(surface, &rect, tile, NULL);
cur_game->craft[4] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tile);
SDL_FreeSurface(tile);
rect.x = 207;
tile = SDL_CreateRGBSurface(0, 69, 69, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tile, 1, 0xFF00FF);
SDL_FillRect(tile, 0, 0xFF00FF);
SDL_BlitSurface(surface, &rect, tile, NULL);
cur_game->craft[5] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tile);
SDL_FreeSurface(tile);
SDL_FreeSurface(surface);
/* Load unknown recipe icon */
surface = SDL_LoadBMP("art/craft_unknown.bmp");
rect.x = 0; rect.y = 0; rect.w = 32; rect.h = 32;
tile = SDL_CreateRGBSurface(0, 32, 32, 24, 0x00, 0x00, 0x00, 0x00);
SDL_SetColorKey(tile, 1, 0xFF00FF);
SDL_FillRect(tile, 0, 0xFF00FF);
SDL_BlitSurface(surface, &rect, tile, NULL);
cur_game->craft[6] = SDL_CreateTextureFromSurface(cur_game->screen.renderer, tile);
SDL_FreeSurface(tile);
SDL_FreeSurface(surface);
}
static void
unload_sprites(struct game *cur_game)
{
int i;
/* Free all sprites */
for (i = 0; i < TMP_NUMSPRITES; i++) {
SDL_DestroyTexture(cur_game->sprite_textures[i]);
}
free(cur_game->sprite_textures);
/* Free craft textures */
for (i = 0; i < 7; i++) {
SDL_DestroyTexture(cur_game->craft[i]);
}
free(cur_game->craft);
}
int LAST = 0;
void
loading_bar(struct game *cur_game, char *title, int percentage)
{
char black[3] = { 0, 0, 0 };
char white[3] = { 255, 255, 255 };
char blue[3] = { 0, 0, 255 };
/* Should I even draw the loading bar? */
if (percentage == LAST) return;
/* Yes */
LAST = percentage;
if (percentage % 3 != 0) return;
/* Clear screen */
render_clear(cur_game);
/* Write title to screen */
draw_sentence(cur_game, 0, 0, title);
/* Draw percentage bar */
draw_rect(cur_game, 20, 30, 1000, 40, SDL_TRUE, black, SDL_TRUE, white);
draw_rect(cur_game, 21, 31, percentage*10-2, 38, SDL_TRUE, blue, SDL_FALSE, NULL);
render_present(cur_game);
}
static void
map_init(struct game *cur_game)
{
cur_game->map_texture = SDL_CreateTexture(cur_game->screen.renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET, MAP_COLS, MAP_ROWS);
}
static void
map_destroy(struct game *cur_game)
{
SDL_DestroyTexture(cur_game->map_texture);
}
| 34.925608 | 247 | 0.680211 |
261afb6165c7158c304768da02588d04993acd10 | 112 | c | C | infun.c | avinal/C_ode | f056da37c8c56a4a62a06351c2ea3773d16d1b11 | [
"MIT"
] | 1 | 2020-08-23T20:21:35.000Z | 2020-08-23T20:21:35.000Z | infun.c | avinal/C_ode | f056da37c8c56a4a62a06351c2ea3773d16d1b11 | [
"MIT"
] | null | null | null | infun.c | avinal/C_ode | f056da37c8c56a4a62a06351c2ea3773d16d1b11 | [
"MIT"
] | 2 | 2019-03-18T10:22:13.000Z | 2021-01-03T10:12:28.000Z | #include<stdio.h>
int let();
int main()
{
let(let());
}
int let()
{
printf("C is a Cimple Language.");
} | 11.2 | 38 | 0.553571 |
6494338eadb61f11ab931af17934b8186d33b991 | 2,839 | h | C | panda/src/physx/physxRevoluteJoint.h | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/physx/physxRevoluteJoint.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | panda/src/physx/physxRevoluteJoint.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: physxRevoluteJoint.h
// Created by: enn0x (02Oct09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#ifndef PHYSXREVOLUTEJOINT_H
#define PHYSXREVOLUTEJOINT_H
#include "pandabase.h"
#include "physxJoint.h"
#include "physx_includes.h"
class PhysxRevoluteJointDesc;
class PhysxSpringDesc;
class PhysxMotorDesc;
class PhysxJointLimitDesc;
////////////////////////////////////////////////////////////////////
// Class : PhysxRevoluteJoint
// Description : A joint which behaves in a similar way to a hinge
// or axel. A hinge joint removes all but a single
// rotational degree of freedom from two objects. The
// axis along which the two bodies may rotate is
// specified with a point and a direction vector.
////////////////////////////////////////////////////////////////////
class EXPCL_PANDAPHYSX PhysxRevoluteJoint : public PhysxJoint {
PUBLISHED:
INLINE PhysxRevoluteJoint();
INLINE ~PhysxRevoluteJoint();
void save_to_desc(PhysxRevoluteJointDesc &jointDesc) const;
void load_from_desc(const PhysxRevoluteJointDesc &jointDesc);
void set_spring(const PhysxSpringDesc &spring);
void set_motor(const PhysxMotorDesc &motor);
void set_limits(const PhysxJointLimitDesc &low, const PhysxJointLimitDesc &high);
void set_flag(PhysxRevoluteJointFlag flag, bool value);
void set_projection_mode(PhysxProjectionMode mode);
float get_angle() const;
float get_velocity() const;
bool get_flag(PhysxRevoluteJointFlag flag) const;
PhysxProjectionMode get_projection_mode() const;
PhysxMotorDesc get_motor() const;
PhysxSpringDesc get_spring() const;
////////////////////////////////////////////////////////////////////
public:
INLINE NxJoint *ptr() const { return (NxJoint *)_ptr; };
void link(NxJoint *jointPtr);
void unlink();
private:
NxRevoluteJoint *_ptr;
////////////////////////////////////////////////////////////////////
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
PhysxJoint::init_type();
register_type(_type_handle, "PhysxRevoluteJoint",
PhysxJoint::get_class_type());
}
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {
init_type();
return get_class_type();
}
private:
static TypeHandle _type_handle;
};
#include "physxRevoluteJoint.I"
#endif // PHYSXREVOLUTEJOINT_H
| 30.526882 | 83 | 0.628038 |
233f7e45afbc73f072ac981da74deb6942f560b7 | 3,886 | h | C | client/ios_handler/exception_processor.h | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | 18 | 2022-01-11T17:24:50.000Z | 2022-03-30T04:35:25.000Z | client/ios_handler/exception_processor.h | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | 21 | 2022-01-07T19:20:04.000Z | 2022-03-24T14:32:28.000Z | client/ios_handler/exception_processor.h | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | 2 | 2022-01-15T16:45:34.000Z | 2022-03-01T22:37:48.000Z | // Copyright 2020 The Crashpad 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 CRASHPAD_UTIL_IOS_EXCEPTION_PROCESSOR_H_
#define CRASHPAD_UTIL_IOS_EXCEPTION_PROCESSOR_H_
#include "base/files/file_path.h"
#include "util/misc/capture_context.h"
namespace crashpad {
//! \brief An interface for notifying the CrashpadClient of NSExceptions.
class ObjcExceptionDelegate {
public:
//! \brief The exception processor detected an exception as it was thrown and
//! captured the cpu context.
//!
//! \param context The cpu context of the thread throwing an exception.
virtual void HandleUncaughtNSExceptionWithContext(
NativeCPUContext* context) = 0;
//! \brief The exception processor did not detect the exception as it was
//! thrown, and instead caught the exception via the
//! NSUncaughtExceptionHandler.
//!
//! \param frames An array of call stack frame addresses.
//! \param num_frames The number of frames in |frames|.
virtual void HandleUncaughtNSException(const uint64_t* frames,
const size_t num_frames) = 0;
//! \brief Generate an intermediate dump from an NSException caught with its
//! associated CPU context. Because the method for intercepting
//! exceptions is imperfect, write the the intermediate dump to a
//! temporary location specified by \a path. If the NSException matches
//! the one used in the UncaughtExceptionHandler, call
//! MoveIntermediateDumpAtPathToPending to move to the proper Crashpad
//! database pending location.
//!
//! \param[in] context The cpu context of the thread throwing an exception.
//! \param[in] path Path to write the intermediate dump.
virtual void HandleUncaughtNSExceptionWithContextAtPath(
NativeCPUContext* context,
const base::FilePath& path) = 0;
//! \brief Moves an intermediate dump to the pending directory. This is meant
//! to be used by the UncaughtExceptionHandler, when the NSException
//! caught by the preprocessor matches the UncaughtExceptionHandler.
//!
//! \param[in] path Path to the specific intermediate dump.
virtual bool MoveIntermediateDumpAtPathToPending(
const base::FilePath& path) = 0;
protected:
~ObjcExceptionDelegate() {}
};
//! \brief Installs the Objective-C exception preprocessor.
//!
//! When code raises an Objective-C exception, unwind the stack looking for
//! any exception handlers. If an exception handler is encountered, test to
//! see if it is a function known to be a catch-and-rethrow 'sinkhole' exception
//! handler. Various routines in UIKit do this, and they obscure the
//! crashing stack, since the original throw location is no longer present
//! on the stack (just the re-throw) when Crashpad captures the crash
//! report. In the case of sinkholes, trigger an immediate exception to
//! capture the original stack.
//!
//! This should be installed at the same time the CrashpadClient installs the
//! signal handler. It should only be installed once.
void InstallObjcExceptionPreprocessor(ObjcExceptionDelegate* delegate);
//! \brief Uninstalls the Objective-C exception preprocessor. Expected to be
//! used by tests only.
void UninstallObjcExceptionPreprocessor();
} // namespace crashpad
#endif // CRASHPAD_UTIL_IOS_EXCEPTION_PROCESSOR_H_
| 43.177778 | 80 | 0.740093 |
03bee5d564ca3d8a2009dff5b0236c5a5898057d | 2,249 | h | C | dev/Code/Tools/CryCommonTools/PakSystem.h | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Code/Tools/CryCommonTools/PakSystem.h | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Code/Tools/CryCommonTools/PakSystem.h | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H
#define CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H
#pragma once
#include "IPakSystem.h"
#include "ZipDir/ZipDir.h" // TODO: get rid of thid include
enum PakSystemFileType
{
PakSystemFileType_Unknown,
PakSystemFileType_File,
PakSystemFileType_PakFile
};
struct PakSystemFile
{
PakSystemFile();
PakSystemFileType type;
// PakSystemFileType_File
FILE* file;
// PakSystemFileType_PakFile
ZipDir::CachePtr zip;
ZipDir::FileEntry* fileEntry;
void* data;
int dataPosition;
};
struct PakSystemArchive
{
ZipDir::CacheRWPtr zip;
};
class PakSystem
: public IPakSystem
{
public:
PakSystem();
// IPakSystem
virtual PakSystemFile* Open(const char* filename, const char* mode);
virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0);
virtual void Close(PakSystemFile* file);
virtual int GetLength(PakSystemFile* file) const;
virtual int Read(PakSystemFile* file, void* buffer, int size);
virtual bool EoF(PakSystemFile* file);
virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]);
virtual void CloseArchive(PakSystemArchive* archive);
virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, __time64_t modTime, int compressionLevel);
virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path);
virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, __time64_t modTime);
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H
| 32.128571 | 139 | 0.755892 |
83cc715e0ff6de9c5a769ecc11219153579f8ac4 | 5,136 | c | C | src/libtomcrypt/tests/file_test.c | fpmuniz/stepmania | 984dc8668f1fedacf553f279a828acdebffc5625 | [
"MIT"
] | 1,514 | 2015-01-02T17:00:28.000Z | 2022-03-30T14:11:21.000Z | src/libtomcrypt/tests/file_test.c | fpmuniz/stepmania | 984dc8668f1fedacf553f279a828acdebffc5625 | [
"MIT"
] | 1,462 | 2015-01-01T10:53:29.000Z | 2022-03-27T04:35:53.000Z | src/libtomcrypt/tests/file_test.c | fpmuniz/stepmania | 984dc8668f1fedacf553f279a828acdebffc5625 | [
"MIT"
] | 552 | 2015-01-02T05:34:41.000Z | 2022-03-26T05:19:19.000Z | /* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* test file related functions */
#include <tomcrypt_test.h>
int file_test(void)
{
#ifdef LTC_NO_FILE
return CRYPT_NOP;
#else
unsigned char key[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F };
unsigned char buf[200];
unsigned long len;
const char *fname = "tests/test.key";
FILE *in;
int err, isha256, iaes;
/* expected results */
unsigned char exp_sha256[32] = { 0x76, 0xEC, 0x7F, 0xAE, 0xBD, 0xC4, 0x2A, 0x4D, 0xE3, 0x5C, 0xA7, 0x00, 0x24, 0xC2, 0xD2, 0x73,
0xE9, 0xF7, 0x85, 0x6C, 0xA6, 0x16, 0x12, 0xE8, 0x9F, 0x5F, 0x66, 0x35, 0x0B, 0xA8, 0xCF, 0x5F };
isha256 = find_hash("sha256");
iaes = find_cipher("aes");
len = sizeof(buf);
if ((in = fopen(fname, "rb")) == NULL) return CRYPT_FILE_NOTFOUND;
err = hash_filehandle(isha256, in, buf, &len);
fclose(in);
if (err != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_sha256, 32, "hash_filehandle", 1)) return 1;
len = sizeof(buf);
if ((err = hash_file(isha256, fname, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_sha256, 32, "hash_file", 1)) return 1;
#ifdef LTC_HMAC
{
unsigned char exp_hmacsha256[32] = { 0xE4, 0x07, 0x74, 0x95, 0xF1, 0xF8, 0x5B, 0xB5, 0xF1, 0x4F, 0x7D, 0x4F, 0x59, 0x8E, 0x4B, 0xBC,
0x8F, 0x68, 0xCF, 0xBA, 0x2E, 0xAD, 0xC4, 0x63, 0x9D, 0x7F, 0x02, 0x99, 0x8C, 0x08, 0xAC, 0xC0 };
len = sizeof(buf);
if ((err = hmac_file(isha256, fname, key, 32, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_hmacsha256, 32, "hmac_file", 1)) return 1;
}
#endif
#ifdef LTC_OMAC
{
unsigned char exp_omacaes[16] = { 0x50, 0xB4, 0x6C, 0x62, 0xE9, 0xCA, 0x48, 0xFC, 0x38, 0x8D, 0xF4, 0xA2, 0x7D, 0x6A, 0x1E, 0xD8 };
len = sizeof(buf);
if ((err = omac_file(iaes, key, 32, fname, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_omacaes, 16, "omac_file", 1)) return 1;
}
#endif
#ifdef LTC_PMAC
{
unsigned char exp_pmacaes[16] = { 0x7D, 0x65, 0xF0, 0x75, 0x4F, 0x8D, 0xE2, 0xB0, 0xE4, 0xFA, 0x54, 0x4E, 0x45, 0x01, 0x36, 0x1B };
len = sizeof(buf);
if ((err = pmac_file(iaes, key, 32, fname, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_pmacaes, 16, "pmac_file", 1)) return 1;
}
#endif
#ifdef LTC_XCBC
{
unsigned char exp_xcbcaes[16] = { 0x9C, 0x73, 0xA2, 0xD7, 0x90, 0xA5, 0x86, 0x25, 0x4D, 0x3C, 0x8A, 0x6A, 0x24, 0x6D, 0xD1, 0xAB };
len = sizeof(buf);
if ((err = xcbc_file(iaes, key, 32, fname, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_xcbcaes, 16, "xcbc_file", 1)) return 1;
}
#endif
#ifdef LTC_F9_MODE
{
unsigned char exp_f9aes[16] = { 0x6B, 0x6A, 0x18, 0x34, 0x13, 0x8E, 0x01, 0xEF, 0x33, 0x8E, 0x7A, 0x3F, 0x5B, 0x9A, 0xA6, 0x7A };
len = sizeof(buf);
if ((err = f9_file(iaes, key, 32, fname, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_f9aes, 16, "f9_file", 1)) return 1;
}
#endif
#ifdef LTC_POLY1305
{
unsigned char exp_poly1305[16] = { 0xD0, 0xC7, 0xFB, 0x13, 0xA8, 0x87, 0x84, 0x23, 0x21, 0xCC, 0xA9, 0x43, 0x81, 0x18, 0x75, 0xBE };
len = sizeof(buf);
if ((err = poly1305_file(fname, key, 32, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_poly1305, 16, "poly1305_file", 1)) return 1;
}
#endif
#ifdef LTC_BLAKE2SMAC
{
unsigned char exp_blake2smac[16] = { 0x4f, 0x94, 0x45, 0x15, 0xcd, 0xd1, 0xca, 0x02, 0x1a, 0x0c, 0x7a, 0xe4, 0x6d, 0x2f, 0xe8, 0xb3 };
len = 16;
if ((err = blake2smac_file(fname, key, 32, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_blake2smac, 16, "exp_blake2smac_file", 1)) return 1;
}
#endif
#ifdef LTC_BLAKE2BMAC
{
unsigned char exp_blake2bmac[16] = { 0xdf, 0x0e, 0x7a, 0xab, 0x96, 0x6b, 0x75, 0x4e, 0x52, 0x6a, 0x43, 0x96, 0xbd, 0xef, 0xab, 0x44 };
len = 16;
if ((err = blake2bmac_file(fname, key, 32, buf, &len)) != CRYPT_OK) return err;
if (compare_testvector(buf, len, exp_blake2bmac, 16, "exp_blake2bmac_file", 1)) return 1;
}
#endif
return CRYPT_OK;
#endif
}
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */
/* commit time: 2018-07-01 22:49:01 +0200 */
| 44.275862 | 142 | 0.597936 |
eabef8d72abe88884cb9c5a0866165d5db688939 | 2,524 | h | C | source/Classes/Models/ApigeeApp.h | RobertWalsh/apigee-ios-sdk | f23ca1fa4eed88de2f5c260a47cefe7f57701e06 | [
"Apache-2.0"
] | null | null | null | source/Classes/Models/ApigeeApp.h | RobertWalsh/apigee-ios-sdk | f23ca1fa4eed88de2f5c260a47cefe7f57701e06 | [
"Apache-2.0"
] | null | null | null | source/Classes/Models/ApigeeApp.h | RobertWalsh/apigee-ios-sdk | f23ca1fa4eed88de2f5c260a47cefe7f57701e06 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "ApigeeMonitoringSettings.h"
@interface ApigeeApp : NSObject
@property (strong, nonatomic) NSNumber *instaOpsApplicationId;
@property (strong, nonatomic) NSString *applicationUUID;
@property (strong, nonatomic) NSString *organizationUUID;
@property (strong, nonatomic) NSString *orgName;
@property (strong, nonatomic) NSString *appName;
@property (strong, nonatomic) NSString *fullAppName;
@property (strong, nonatomic) NSString *appOwner;
@property (strong, nonatomic) NSString *googleId;
@property (strong, nonatomic) NSString *appleId;
@property (strong, nonatomic) NSString *description;
@property (strong, nonatomic) NSString *environment;
@property (strong, nonatomic) NSString *customUploadUrl;
@property (strong, nonatomic) NSDate *createdDate;
@property (strong, nonatomic) NSDate *lastModifiedDate;
@property (assign, nonatomic) BOOL monitoringDisabled;
@property (assign, nonatomic) BOOL deleted;
@property (assign, nonatomic) BOOL deviceLevelOverrideEnabled;
@property (assign, nonatomic) BOOL deviceTypeOverrideEnabled;
@property (assign, nonatomic) BOOL ABTestingOverrideEnabled;
@property (strong, nonatomic) ApigeeMonitoringSettings *defaultSettings;
@property (strong, nonatomic) ApigeeMonitoringSettings *deviceLevelSettings;
@property (strong, nonatomic) ApigeeMonitoringSettings *deviceTypeSettings;
@property (strong, nonatomic) ApigeeMonitoringSettings *abTestingSettings;
@property (strong, nonatomic) NSNumber *abtestingPercentage;
@property (strong, nonatomic) NSArray *appConfigOverrideFilters;
@property (strong, nonatomic) NSArray *deviceNumberFilters;
@property (strong, nonatomic) NSArray *deviceIdFilters;
@property (strong, nonatomic) NSArray *deviceModelRegexFilters;
@property (strong, nonatomic) NSArray *devicePlatformRegexFilters;
@property (strong, nonatomic) NSArray *networkTypeRegexFilters;
@property (strong, nonatomic) NSArray *networkOperatorRegexFilters;
@end
| 40.063492 | 76 | 0.795959 |
d96118142d5fe7bff219da93f10a8960d309e5bf | 4,273 | h | C | include/udma/al_hal_udma_regs.h | delroth/alpine_hal | eb6b9f132c08eb3cd70a6a94586bcd689a244d0a | [
"Unlicense"
] | 1 | 2022-02-03T01:04:47.000Z | 2022-02-03T01:04:47.000Z | include/udma/al_hal_udma_regs.h | delroth/alpine_hal | eb6b9f132c08eb3cd70a6a94586bcd689a244d0a | [
"Unlicense"
] | null | null | null | include/udma/al_hal_udma_regs.h | delroth/alpine_hal | eb6b9f132c08eb3cd70a6a94586bcd689a244d0a | [
"Unlicense"
] | null | null | null | /*******************************************************************************
Copyright (C) 2015 Annapurna Labs Ltd.
This file may be licensed under the terms of the Annapurna Labs Commercial
License Agreement.
Alternatively, this file can be distributed under the terms of the GNU General
Public License V2 as published by the Free Software Foundation and can be
found at http://www.gnu.org/licenses/gpl-2.0.html
Alternatively, 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 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.
*******************************************************************************/
/**
* @{
* @file al_hal_udma_regs.h
*
* @brief udma registers definition
*
*
*/
#ifndef __AL_HAL_UDMA_REG_H
#define __AL_HAL_UDMA_REG_H
#include "al_hal_udma_regs_m2s.h"
#include "al_hal_udma_regs_s2m.h"
#include "al_hal_udma_regs_gen.h"
#ifdef AL_UDMA_EX
#include "al_hal_udma_regs_gen_ex.h"
#endif
#define AL_UDMA_REV_ID_REV0 0
#define AL_UDMA_REV_ID_REV1 1
#define AL_UDMA_REV_ID_REV2 2
#define AL_UDMA_REV_ID_REV4 4
#ifdef __cplusplus
extern "C" {
#endif
/** UDMA registers, either m2s or s2m */
union udma_regs {
struct udma_m2s_regs_v4 m2s;
struct udma_s2m_regs_v4 s2m;
};
struct unit_regs_v3 {
struct udma_m2s_regs_v3 m2s;
uint32_t rsrvd0[(0x10000 - sizeof(struct udma_m2s_regs_v3)) >> 2];
struct udma_s2m_regs_v3 s2m;
uint32_t rsrvd1[((0x1C000 - 0x10000) - sizeof(struct udma_s2m_regs_v3)) >> 2];
struct udma_gen_regs_v3 gen;
uint32_t rsrvd2[((0x1E800 - 0x1C000) - sizeof(struct udma_gen_regs_v3)) >> 2];
struct udma_gen_ex_regs gen_ex;
};
struct unit_regs_v4 {
struct udma_m2s_regs_v4 m2s;
uint32_t rsrvd0[(0x20000 - sizeof(struct udma_m2s_regs_v4)) >> 2];
struct udma_s2m_regs_v4 s2m;
uint32_t rsrvd1[((0x38000 - 0x20000) - sizeof(struct udma_s2m_regs_v4)) >> 2];
struct udma_gen_regs_v4 gen;
uint32_t rsrvd2[((0x3c000 - 0x38000) - sizeof(struct udma_gen_regs_v4)) >> 2];
struct udma_gen_ex_regs gen_ex;
};
/** UDMA submission and completion registers, M2S and S2M UDMAs have same stucture */
struct udma_rings_regs {
uint32_t rsrvd0[8];
uint32_t cfg; /* Descriptor ring configuration */
uint32_t status; /* Descriptor ring status and information */
uint32_t drbp_low; /* Descriptor Ring Base Pointer [31:4] */
uint32_t drbp_high; /* Descriptor Ring Base Pointer [63:32] */
uint32_t drl; /* Descriptor Ring Length[23:2] */
uint32_t drhp; /* Descriptor Ring Head Pointer */
uint32_t drtp_inc; /* Descriptor Tail Pointer increment */
uint32_t drtp; /* Descriptor Tail Pointer */
uint32_t dcp; /* Descriptor Current Pointer */
uint32_t crbp_low; /* Completion Ring Base Pointer [31:4] */
uint32_t crbp_high; /* Completion Ring Base Pointer [63:32] */
uint32_t crhp; /* Completion Ring Head Pointer */
uint32_t crhp_internal; /* Completion Ring Head Pointer internal, before AX ... */
};
/** M2S and S2M generic structure of Q registers */
union udma_q_regs {
struct udma_rings_regs rings;
struct udma_m2s_q m2s_q;
struct udma_s2m_q s2m_q;
};
#ifdef __cplusplus
}
#endif
#endif /* __AL_HAL_UDMA_REG_H */
/** @} end of UDMA group */
| 35.608333 | 85 | 0.737655 |
9ccc7a7f579d68ece107aabef0bd03ac206092d1 | 2,619 | h | C | printscan/faxsrv/admin/mmc/devicesandproviders.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/faxsrv/admin/mmc/devicesandproviders.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/faxsrv/admin/mmc/devicesandproviders.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /////////////////////////////////////////////////////////////////////////////
// FILE : DevicesAndProviders.h //
// //
// DESCRIPTION : Header file for CFaxDevicesAndProvidersNode class //
// This is the "Fax" node in the scope pane. //
// //
// AUTHOR : yossg //
// //
// HISTORY : //
// Sep 22 1999 yossg Create //
// Dec 9 1999 yossg Reorganize Populate ChildrenList, //
// and the call to InitDisplayName //
// //
// //
// Copyright (C) 1999 Microsoft Corporation All Rights Reserved //
/////////////////////////////////////////////////////////////////////////////
#ifndef H_DEVICESANDPROVIDERS_H
#define H_DEVICESANDPROVIDERS_H
//#pragma message( "H_DEVICESANDPROVIDERS_H" )
#include "snapin.h"
#include "snpnscp.h"
class CFaxServerNode;
class CFaxDevicesAndProvidersNode : public CNodeWithScopeChildrenList<CFaxDevicesAndProvidersNode, FALSE>
{
public:
BEGIN_SNAPINCOMMAND_MAP(CFaxDevicesAndProvidersNode, FALSE)
END_SNAPINCOMMAND_MAP()
BEGIN_SNAPINTOOLBARID_MAP(CFaxDevicesAndProvidersNode)
END_SNAPINTOOLBARID_MAP()
SNAPINMENUID(IDR_SNAPIN_MENU)
CFaxDevicesAndProvidersNode(CSnapInItem * pParentNode, CSnapin * pComponentData) :
CNodeWithScopeChildrenList<CFaxDevicesAndProvidersNode, FALSE>(pParentNode, pComponentData )
{
}
~CFaxDevicesAndProvidersNode()
{
}
virtual HRESULT PopulateScopeChildrenList();
virtual HRESULT InsertColumns(IHeaderCtrl* pHeaderCtrl);
virtual HRESULT SetVerbs(IConsoleVerb *pConsoleVerb);
void InitParentNode(CFaxServerNode *pParentNode)
{
m_pParentNode = pParentNode;
}
HRESULT InitDisplayName();
HRESULT OnShowContextHelp(
IDisplayHelp* pDisplayHelp, LPOLESTR helpFile);
private:
static CColumnsInfo m_ColsInfo;
CFaxServerNode * m_pParentNode;
};
#endif //H_DEVICESANDPROVIDERS_H
| 35.391892 | 106 | 0.476518 |
1432ac33ea57ba66fde6a9398083a1f306c04607 | 971 | h | C | Inc/ui.h | Eveneko/Tetris | 8e08ab18e243cf309f4b3b96fc7715f3bb9ee4ed | [
"MIT"
] | null | null | null | Inc/ui.h | Eveneko/Tetris | 8e08ab18e243cf309f4b3b96fc7715f3bb9ee4ed | [
"MIT"
] | null | null | null | Inc/ui.h | Eveneko/Tetris | 8e08ab18e243cf309f4b3b96fc7715f3bb9ee4ed | [
"MIT"
] | null | null | null | #ifndef __UI_H
#define __UI_H
#include "lcd.h"
#include "block.h"
#include "button.h"
#include "game.h"
#include "grid.h"
#define screen_height 320
#define screen_width 240
#define main_origin_x 10
#define main_origin_y 10
#define main_height 300
#define main_width 150
#define sub_origin_x 170
#define sub_origin_y 10
#define sub_height 60
#define sub_width 60
#define font_size 16
#define cell_length 15
void draw_background();
void fill_main_background(uint16_t color);
void fill_sub_background(uint16_t color);
void fill_all_white();
void draw_block(uint8_t x, uint8_t y, uint16_t color, uint8_t mode);
void grid_render();
void sub_grid_render(uint8_t mode);
void draw_main_block(uint8_t clear);
void draw_next_block1(uint8_t clear);
void draw_next_block2(uint8_t clear);
void draw_name(char* name);
void draw_main_grid();
void update_score(uint16_t score);
void update_level();
void game_start();
void choose_pattern();
void game_over(uint16_t score);
#endif
| 21.577778 | 68 | 0.796087 |
1eb57d0df884af03f2748296c2a4ffeec6a336ea | 1,786 | h | C | Geometry/Records/interface/CaloTowerGeometryRecord.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 2 | 2020-05-09T16:03:43.000Z | 2020-05-09T16:03:50.000Z | Geometry/Records/interface/CaloTowerGeometryRecord.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 26 | 2018-10-30T12:47:58.000Z | 2022-03-29T08:39:00.000Z | Geometry/Records/interface/CaloTowerGeometryRecord.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 3 | 2019-03-09T13:06:43.000Z | 2020-07-03T00:47:30.000Z | #ifndef RECORDS_CALOTOWERGEOMETRYRECORD_H
#define RECORDS_CALOTOWERGEOMETRYRECORD_H
// -*- C++ -*-
//
// Package: Records
// Class : CaloTowerGeometryRecord
//
//
// Author: Brian Heltsley
// Created: Tue April 1, 2008
//
#include "FWCore/Framework/interface/EventSetupRecordImplementation.h"
#include "FWCore/Framework/interface/DependentRecordImplementation.h"
#include "Geometry/Records/interface/IdealGeometryRecord.h"
#include "Geometry/Records/interface/HcalRecNumberingRecord.h"
#include "CondFormats/AlignmentRecord/interface/CaloTowerAlignmentRcd.h"
#include "CondFormats/AlignmentRecord/interface/CaloTowerAlignmentErrorRcd.h"
#include "CondFormats/AlignmentRecord/interface/CaloTowerAlignmentErrorExtendedRcd.h"
#include "Geometry/Records/interface/PCaloTowerRcd.h"
#include "CondFormats/AlignmentRecord/interface/GlobalPositionRcd.h"
#include "boost/mpl/vector.hpp"
class CaloTowerGeometryRecord
: public edm::eventsetup::DependentRecordImplementation<CaloTowerGeometryRecord,
boost::mpl::vector<IdealGeometryRecord,
HcalRecNumberingRecord,
CaloTowerAlignmentRcd,
CaloTowerAlignmentErrorRcd,
CaloTowerAlignmentErrorExtendedRcd,
GlobalPositionRcd,
PCaloTowerRcd> > {};
#endif /* RECORDS_CALOTOWERGEOMETRYRECORD_H */
| 51.028571 | 114 | 0.576708 |
bb2d65648b4d571a5d3b704fbb3bd18762326147 | 105,925 | h | C | benchmark_apps/elmerfem/misc/tetgen_plugin/plugin/tetgen.h | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T13:10:11.000Z | 2021-03-15T20:26:35.000Z | elmerfem/misc/tetgen_plugin/plugin/tetgen.h | jcmcmurry/pipelining | 8fface1a501b5050f58e7b902aacdcdde68e9648 | [
"MIT"
] | null | null | null | elmerfem/misc/tetgen_plugin/plugin/tetgen.h | jcmcmurry/pipelining | 8fface1a501b5050f58e7b902aacdcdde68e9648 | [
"MIT"
] | 2 | 2021-08-02T23:23:40.000Z | 2022-02-26T12:39:30.000Z | ///////////////////////////////////////////////////////////////////////////////
// //
// TetGen //
// //
// A Quality Tetrahedral Mesh Generator and 3D Delaunay Triangulator //
// //
// Version 1.4 //
// April 16, 2007 //
// //
// Copyright (C) 2002--2007 //
// Hang Si //
// Research Group Numerical Mathematics and Scientific Computing //
// Weierstrass Institute for Applied Analysis and Stochastics //
// Mohrenstr. 39, 10117 Berlin, Germany //
// si@wias-berlin.de //
// //
// TetGen is freely available through the website: http://tetgen.berlios.de. //
// It may be copied, modified, and redistributed for non-commercial use. //
// Please consult the file LICENSE for the detailed copyright notices. //
// //
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// //
// TetGen computes Delaunay tetrahedralizations, constrained Delaunay tetra- //
// hedralizations, and quality Delaunay tetrahedral meshes. The latter are //
// nicely graded and whose tetrahedra have radius-edge ratio bounded. Such //
// meshes are suitable for finite element and finite volume methods. //
// //
// TetGen incorporates a suit of geometrical and mesh generation algorithms. //
// A brief description of algorithms used in TetGen is found in the first //
// section of the user's manual. References are given for users who are //
// interesting in these approaches. The main references are given below: //
// //
// The efficient Delaunay tetrahedralization algorithm is: H. Edelsbrunner //
// and N. R. Shah, "Incremental Topological Flipping Works for Regular //
// Triangulations". Algorithmica 15: 223--241, 1996. //
// //
// The constrained Delaunay tetrahedralization algorithm is described in: //
// H. Si and K. Gaertner, "Meshing Piecewise Linear Complexes by Constr- //
// ained Delaunay Tetrahedralizations". In Proceeding of the 14th Inter- //
// national Meshing Roundtable. September 2005. //
// //
// The mesh refinement algorithm is from: Hang Si, "Adaptive Tetrahedral //
// Mesh Generation by Constrained Delaunay Refinement". WIAS Preprint No. //
// 1176, Berlin 2006. //
// //
// The mesh data structure of TetGen is a combination of two types of mesh //
// data structures. The tetrahedron-based mesh data structure introduced //
// by Shewchuk is eligible for tetrahedralization algorithms. The triangle //
// -edge data structure developed by Muecke is adopted for representing //
// boundary elements: subfaces and subsegments. //
// //
// J. R. Shewchuk, "Delaunay Refinement Mesh Generation". PhD thesis, //
// Carnegie Mellon University, Pittsburgh, PA, 1997. //
// //
// E. P. Muecke, "Shapes and Implementations in Three-Dimensional //
// Geometry". PhD thesis, Univ. of Illinois, Urbana, Illinois, 1993. //
// //
// The research of mesh generation is definitly on the move. Many State-of- //
// the-art algorithms need implementing and evaluating. I heartily welcome //
// any new algorithm especially for generating quality conforming Delaunay //
// meshes and anisotropic conforming Delaunay meshes. //
// //
// TetGen is supported by the "pdelib" project of Weierstrass Institute for //
// Applied Analysis and Stochastics (WIAS) in Berlin. It is a collection //
// of software components for solving non-linear partial differential //
// equations including 2D and 3D mesh generators, sparse matrix solvers, //
// and scientific visualization tools, etc. For more information please //
// visit: http://www.wias-berlin.de/software/pdelib. //
// //
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// //
// tetgen.h //
// //
// Header file of the TetGen library. Also is the user-level header file. //
// //
///////////////////////////////////////////////////////////////////////////////
// Here are the most general used head files for C/C++ programs.
#include <QtGlobal>
#include <stdio.h> // Standard IO: FILE, NULL, EOF, printf(), ...
#include <stdlib.h> // Standard lib: abort(), system(), getenv(), ...
#include <string.h> // String lib: strcpy(), strcat(), strcmp(), ...
#include <math.h> // Math lib: sin(), sqrt(), pow(), ...
#include <time.h> // Defined type clock_t, constant CLOCKS_PER_SEC.
#include <assert.h>
///////////////////////////////////////////////////////////////////////////////
// //
// TetGen Library Overview //
// //
// TetGen library is comprised by several data types and global functions. //
// //
// There are three main data types: tetgenio, tetgenbehavior, and tetgenmesh.//
// Tetgenio is used to pass data into and out of TetGen library; tetgenbeha- //
// vior keeps the runtime options and thus controls the behaviors of TetGen; //
// tetgenmesh, the biggest data type I've ever defined, contains mesh data //
// structures and mesh traversing and transformation operators. The meshing //
// algorithms are implemented on top of it. These data types are defined as //
// C++ classes. //
// //
// There are few global functions. tetrahedralize() is provided for calling //
// TetGen from another program. Two functions: orient3d() and insphere() are //
// incorporated from a public C code provided by Shewchuk. They performing //
// exact geometrical tests. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef tetgenH
#define tetgenH
// To compile TetGen as a library instead of an executable program, define
// the TETLIBRARY symbol.
// #define TETLIBRARY
// Uncomment the following line to disable assert macros. These macros are
// inserted in places where I hope to catch bugs.
// #define NDEBUG
// To insert lots of self-checks for internal errors, define the SELF_CHECK
// symbol. This will slow down the program significantly.
// #define SELF_CHECK
// For single precision ( which will save some memory and reduce paging ),
// define the symbol SINGLE by using the -DSINGLE compiler switch or by
// writing "#define SINGLE" below.
//
// For double precision ( which will allow you to refine meshes to a smaller
// edge length), leave SINGLE undefined.
// #define SINGLE
#ifdef SINGLE
#define REAL float
#else
#define REAL double
#endif // not defined SINGLE
///////////////////////////////////////////////////////////////////////////////
// //
// tetgenio Passing data into and out of the library of TetGen. //
// //
// The tetgenio data structure is actually a collection of arrays of points, //
// facets, tetrahedra, and so forth. The library will read and write these //
// arrays according to the options specified in tetgenbehavior structure. //
// //
// If you want to program with the library of TetGen, it's necessary for you //
// to understand this data type,while the other two structures can be hidden //
// through calling the global function "tetrahedralize()". Each array corre- //
// sponds to a list of data in the file formats of TetGen. It is necessary //
// to understand TetGen's input/output file formats (see user's manual). //
// //
// Once an object of tetgenio is declared, no array is created. One has to //
// allocate enough memory for them, e.g., use the "new" operator in C++. On //
// deletion of the object, the memory occupied by these arrays needs to be //
// freed. Routine deinitialize() will be automatically called. It will de- //
// allocate the memory for an array if it is not a NULL. However, it assumes //
// that the memory is allocated by the C++ "new" operator. If you use malloc //
// (), you should free() them and set the pointers to NULLs before reaching //
// deinitialize(). //
// //
// In all cases, the first item in an array is stored starting at index [0]. //
// However, that item is item number `firstnumber' which may be '0' or '1'. //
// Be sure to set the 'firstnumber' be '1' if your indices pointing into the //
// pointlist is starting from '1'. Default, it is initialized be '0'. //
// //
// Tetgenio also contains routines for reading and writing TetGen's files as //
// well. Both the library of TetGen and TetView use these routines to parse //
// input files, i.e., .node, .poly, .smesh, .ele, .face, and .edge files. //
// Other routines are provided mainly for debugging purpose. //
// //
///////////////////////////////////////////////////////////////////////////////
class tetgenio {
public:
// Maximum number of characters in a file name (including the null).
enum {FILENAMESIZE = 1024};
// Maxi. numbers of chars in a line read from a file (incl. the null).
enum {INPUTLINESIZE = 1024};
// The polygon data structure. A "polygon" is a planar polygon. It can
// be arbitrary shaped (convex or non-convex) and bounded by non-
// crossing segments, i.e., the number of vertices it has indictes the
// same number of edges.
// 'vertexlist' is a list of vertex indices (integers), its length is
// indicated by 'numberofvertices'. The vertex indices are odered in
// either counterclockwise or clockwise way.
typedef struct {
int *vertexlist;
int numberofvertices;
} polygon;
virtual void init(polygon* p) {
p->vertexlist = (int *) NULL;
p->numberofvertices = 0;
}
// The facet data structure. A "facet" is a planar facet. It is used
// to represent a planar straight line graph (PSLG) in two dimension.
// A PSLG contains a list of polygons. It also may conatin holes in it,
// indicated by a list of hole points (their coordinates).
typedef struct {
polygon *polygonlist;
int numberofpolygons;
REAL *holelist;
int numberofholes;
} facet;
virtual void init(facet* f) {
f->polygonlist = (polygon *) NULL;
f->numberofpolygons = 0;
f->holelist = (REAL *) NULL;
f->numberofholes = 0;
}
// A 'voroedge' is an edge of the Voronoi diagram. It corresponds to a
// Delaunay face. Each voroedge is either a line segment connecting
// two Voronoi vertices or a ray starting from a Voronoi vertex to an
// "infinite vertex". 'v1' and 'v2' are two indices pointing to the
// list of Voronoi vertices. 'v1' must be non-negative, while 'v2' may
// be -1 if it is a ray, in this case, the unit normal of this ray is
// given in 'vnormal'.
typedef struct {
int v1, v2;
REAL vnormal[3];
} voroedge;
// A 'vorofacet' is an facet of the Voronoi diagram. It corresponds to a
// Delaunay edge. Each Voronoi facet is a convex polygon formed by a
// list of Voronoi edges, it may not be closed. 'c1' and 'c2' are two
// indices pointing into the list of Voronoi cells, i.e., the two cells
// share this facet. 'elist' is an array of indices pointing into the
// list of Voronoi edges, 'elist[0]' saves the number of Voronoi edges
// (including rays) of this facet.
typedef struct {
int c1, c2;
int *elist;
} vorofacet;
// The periodic boundary condition group data structure. A "pbcgroup"
// contains the definition of a pbc and the list of pbc point pairs.
// 'fmark1' and 'fmark2' are the facetmarkers of the two pbc facets f1
// and f2, respectively. 'transmat' is the transformation matrix which
// maps a point in f1 into f2. An array of pbc point pairs are saved
// in 'pointpairlist'. The first point pair is at indices [0] and [1],
// followed by remaining pairs. Two integers per pair.
typedef struct {
int fmark1, fmark2;
REAL transmat[4][4];
int numberofpointpairs;
int *pointpairlist;
} pbcgroup;
public:
// Items are numbered starting from 'firstnumber' (0 or 1), default is 0.
int firstnumber;
// Dimension of the mesh (2 or 3), default is 3.
int mesh_dim;
// Does the lines in .node file contain index or not, default is TRUE.
bool useindex;
// 'pointlist': An array of point coordinates. The first point's x
// coordinate is at index [0] and its y coordinate at index [1], its
// z coordinate is at index [2], followed by the coordinates of the
// remaining points. Each point occupies three REALs.
// 'pointattributelist': An array of point attributes. Each point's
// attributes occupy 'numberofpointattributes' REALs.
// 'pointmtrlist': An array of metric tensors at points. Each point's
// tensor occupies 'numberofpointmtr' REALs.
// `pointmarkerlist': An array of point markers; one int per point.
REAL *pointlist;
REAL *pointattributelist;
REAL *pointmtrlist;
int *pointmarkerlist;
int numberofpoints;
int numberofpointattributes;
int numberofpointmtrs;
// `elementlist': An array of element (triangle or tetrahedron) corners.
// The first element's first corner is at index [0], followed by its
// other corners in counterclockwise order, followed by any other
// nodes if the element represents a nonlinear element. Each element
// occupies `numberofcorners' ints.
// `elementattributelist': An array of element attributes. Each
// element's attributes occupy `numberofelementattributes' REALs.
// `elementconstraintlist': An array of constraints, i.e. triangle's
// area or tetrahedron's volume; one REAL per element. Input only.
// `neighborlist': An array of element neighbors; 3 or 4 ints per
// element. Output only.
int *tetrahedronlist;
REAL *tetrahedronattributelist;
REAL *tetrahedronvolumelist;
int *neighborlist;
int numberoftetrahedra;
int numberofcorners;
int numberoftetrahedronattributes;
// `facetlist': An array of facets. Each entry is a structure of facet.
// `facetmarkerlist': An array of facet markers; one int per facet.
facet *facetlist;
int *facetmarkerlist;
int numberoffacets;
// `holelist': An array of holes. The first hole's x, y and z
// coordinates are at indices [0], [1] and [2], followed by the
// remaining holes. Three REALs per hole.
REAL *holelist;
int numberofholes;
// `regionlist': An array of regional attributes and volume constraints.
// The first constraint's x, y and z coordinates are at indices [0],
// [1] and [2], followed by the regional attribute at index [3], foll-
// owed by the maximum volume at index [4]. Five REALs per constraint.
// Note that each regional attribute is used only if you select the `A'
// switch, and each volume constraint is used only if you select the
// `a' switch (with no number following).
REAL *regionlist;
int numberofregions;
// `facetconstraintlist': An array of facet maximal area constraints.
// Two REALs per constraint. The first one is the facet marker (cast
// it to int), the second is its maximum area bound.
// Note the 'facetconstraintlist' is used only for the 'q' switch.
REAL *facetconstraintlist;
int numberoffacetconstraints;
// `segmentconstraintlist': An array of segment max. length constraints.
// Three REALs per constraint. The first two are the indices (pointing
// into 'pointlist') of the endpoints of the segment, the third is its
// maximum length bound.
// Note the 'segmentconstraintlist' is used only for the 'q' switch.
REAL *segmentconstraintlist;
int numberofsegmentconstraints;
// 'pbcgrouplist': An array of periodic boundary condition groups.
pbcgroup *pbcgrouplist;
int numberofpbcgroups;
// `trifacelist': An array of triangular face endpoints. The first
// face's endpoints are at indices [0], [1] and [2], followed by the
// remaining faces. Three ints per face.
// `adjtetlist': An array of adjacent tetrahedra to the faces of
// trifacelist. Each face has at most two adjacent tets, the first
// face's adjacent tets are at [0], [1]. Two ints per face. A '-1'
// indicates outside (no adj. tet). This list is output when '-nn'
// switch is used.
// `trifacemarkerlist': An array of face markers; one int per face.
int *trifacelist;
int *adjtetlist;
int *trifacemarkerlist;
int numberoftrifaces;
// `edgelist': An array of edge endpoints. The first edge's endpoints
// are at indices [0] and [1], followed by the remaining edges. Two
// ints per edge.
// `edgemarkerlist': An array of edge markers; one int per edge.
int *edgelist;
int *edgemarkerlist;
int numberofedges;
// 'vpointlist': An array of Voronoi vertex coordinates (like pointlist).
// 'vedgelist': An array of Voronoi edges. Each entry is a 'voroedge'.
// 'vfacetlist': An array of Voronoi facets. Each entry is a 'vorofacet'.
// 'vcelllist': An array of Voronoi cells. Each entry is an array of
// indices pointing into 'vfacetlist'. The 0th entry is used to store
// the length of this array.
REAL *vpointlist;
voroedge *vedgelist;
vorofacet *vfacetlist;
int **vcelllist;
int numberofvpoints;
int numberofvedges;
int numberofvfacets;
int numberofvcells;
public:
// Initialize routine.
virtual void initialize();
virtual void deinitialize();
// Input & output routines.
virtual bool load_node_call(FILE* infile, int markers, char* nodefilename);
virtual bool load_node(char* filename);
virtual bool load_pbc(char* filename);
virtual bool load_var(char* filename);
virtual bool load_mtr(char* filename);
virtual bool load_poly(char* filename);
virtual bool load_off(char* filename);
virtual bool load_ply(char* filename);
virtual bool load_stl(char* filename);
virtual bool load_medit(char* filename);
virtual bool load_plc(char* filename, int object);
virtual bool load_tetmesh(char* filename);
virtual bool load_voronoi(char* filename);
virtual void save_nodes(char* filename);
virtual void save_elements(char* filename);
virtual void save_faces(char* filename);
virtual void save_edges(char* filename);
virtual void save_neighbors(char* filename);
virtual void save_poly(char* filename);
// Read line and parse string functions.
virtual char *readline(char* string, FILE* infile, int *linenumber);
virtual char *findnextfield(char* string);
virtual char *readnumberline(char* string, FILE* infile, char* infilename);
virtual char *findnextnumber(char* string);
// Constructor and destructor.
tetgenio() {initialize();}
virtual ~tetgenio() {deinitialize();}
};
///////////////////////////////////////////////////////////////////////////////
// //
// tetgenbehavior Parsing command line switches and file names. //
// //
// It includes a list of variables corresponding to the commandline switches //
// for control the behavior of TetGen. These varibales are all initialized //
// to their default values. //
// //
// parse_commandline() provides an simple interface to set the vaules of the //
// variables. It accepts the standard parameters (e.g., 'argc' and 'argv') //
// that pass to C/C++ main() function. Alternatively a string which contains //
// the command line options can be used as its parameter. //
// //
// You don't need to understand this data type. It can be implicitly called //
// by the global function "tetrahedralize()" defined below. The necessary //
// thing you need to know is the meaning of command line switches of TetGen. //
// They are described in the third section of the user's manual. //
// //
///////////////////////////////////////////////////////////////////////////////
class tetgenbehavior {
public:
// Labels define the objects which are acceptable by TetGen. They are
// recognized by the file extensions.
// - NODES, a list of nodes (.node);
// - POLY, a piecewise linear complex (.poly or .smesh);
// - OFF, a polyhedron (.off, Geomview's file format);
// - PLY, a polyhedron (.ply, file format from gatech);
// - STL, a surface mesh (.stl, stereolithography format);
// - MEDIT, a surface mesh (.mesh, Medit's file format);
// - MESH, a tetrahedral mesh (.ele).
// If no extension is available, the imposed commandline switch
// (-p or -r) implies the object.
enum objecttype {NONE, NODES, POLY, OFF, PLY, STL, MEDIT, MESH};
// Variables of command line switches. Each variable corresponds to a
// switch and will be initialized. The meanings of these switches
// are explained in the user's manul.
int plc; // '-p' switch, 0.
int quality; // '-q' switch, 0.
int refine; // '-r' switch, 0.
int coarse; // '-R' switch, 0.
int metric; // '-m' switch, 0.
int varvolume; // '-a' switch without number, 0.
int fixedvolume; // '-a' switch with number, 0.
int insertaddpoints; // '-i' switch, 0.
int regionattrib; // '-A' switch, 0.
int conformdel; // '-D' switch, 0.
int diagnose; // '-d' switch, 0.
int zeroindex; // '-z' switch, 0.
int optlevel; // number specified after '-s' switch, 3.
int optpasses; // number specified after '-ss' switch, 5.
int order; // element order, specified after '-o' switch, 1.
int facesout; // '-f' switch, 0.
int edgesout; // '-e' switch, 0.
int neighout; // '-n' switch, 0.
int voroout; // '-v',switch, 0.
int meditview; // '-g' switch, 0.
int gidview; // '-G' switch, 0.
int geomview; // '-O' switch, 0.
int nobound; // '-B' switch, 0.
int nonodewritten; // '-N' switch, 0.
int noelewritten; // '-E' switch, 0.
int nofacewritten; // '-F' switch, 0.
int noiterationnum; // '-I' switch, 0.
int nomerge; // '-M',switch, 0.
int nobisect; // count of how often '-Y' switch is selected, 0.
int noflip; // do not perform flips. '-X' switch. 0.
int nojettison; // do not jettison redundants nodes. '-J' switch. 0.
int steiner; // number after '-S' switch. 0.
int fliprepair; // '-X' switch, 1.
int offcenter; // '-R' switch, 0.
int docheck; // '-C' switch, 0.
int quiet; // '-Q' switch, 0.
int verbose; // count of how often '-V' switch is selected, 0.
int useshelles; // '-p', '-r', '-q', '-d', or '-R' switch, 0.
REAL minratio; // number after '-q' switch, 2.0.
REAL goodratio; // number calculated from 'minratio', 0.0.
REAL minangle; // minimum angle bound, 20.0.
REAL goodangle; // cosine squared of minangle, 0.0.
REAL maxvolume; // number after '-a' switch, -1.0.
REAL mindihedral; // number after '-qq' switch, 5.0.
REAL maxdihedral; // number after '-qqq' switch, 165.0.
REAL alpha1; // number after '-m' switch, sqrt(2).
REAL alpha2; // number after '-mm' switch, 1.0.
REAL alpha3; // number after '-mmm' switch, 0.6.
REAL epsilon; // number after '-T' switch, 1.0e-8.
REAL epsilon2; // number after '-TT' switch, 1.0e-5.
enum objecttype object; // determined by -p, or -r switch. NONE.
// Variables used to save command line switches and in/out file names.
char commandline[1024];
char infilename[1024];
char outfilename[1024];
char addinfilename[1024];
char bgmeshfilename[1024];
tetgenbehavior();
virtual ~tetgenbehavior() {}
virtual void versioninfo();
virtual void syntax();
virtual void usage();
// Command line parse routine.
virtual bool parse_commandline(int argc, char **argv);
virtual bool parse_commandline(char *switches) {
return parse_commandline(0, &switches);
}
};
///////////////////////////////////////////////////////////////////////////////
// //
// Geometric predicates //
// //
// Return one of the values +1, 0, and -1 on basic geometric questions such //
// as the orientation of point sets, in-circle, and in-sphere tests. They //
// are basic units for implmenting geometric algorithms. TetGen uses two 3D //
// geometric predicates: the orientation and in-sphere tests. //
// //
// Orientation test: let a, b, c be a sequence of 3 non-collinear points in //
// R^3. They defines a unique hypeplane H. Let H+ and H- be the two spaces //
// separated by H, which are defined as follows (using the left-hand rule): //
// make a fist using your left hand in such a way that your fingers follow //
// the order of a, b and c, then your thumb is pointing to H+. Given any //
// point d in R^3, the orientation test returns +1 if d lies in H+, -1 if d //
// lies in H-, or 0 if d lies on H. //
// //
// In-sphere test: let a, b, c, d be 4 non-coplanar points in R^3. They //
// defines a unique circumsphere S. Given any point e in R^3, the in-sphere //
// test returns +1 if e lies inside S, or -1 if e lies outside S, or 0 if e //
// lies on S. //
// //
// The correctness of geometric predicates is crucial for the control flow //
// and hence for the correctness and robustness of an implementation of a //
// geometric algorithm. The following routines use arbitrary precision //
// floating-point arithmetic. They are fast and robust. It is provided by J. //
// Schewchuk in public domain (http://www.cs.cmu.edu/~quake/robust.html). //
// The source code are found in a separate file "predicates.cxx". //
// //
///////////////////////////////////////////////////////////////////////////////
REAL exactinit();
REAL orient3d(REAL *pa, REAL *pb, REAL *pc, REAL *pd);
REAL insphere(REAL *pa, REAL *pb, REAL *pc, REAL *pd, REAL *pe);
///////////////////////////////////////////////////////////////////////////////
// //
// The tetgenmesh data type //
// //
// Includes data types and mesh routines for creating tetrahedral meshes and //
// Delaunay tetrahedralizations, mesh input & output, and so on. //
// //
// An object of tetgenmesh can be used to store a triangular or tetrahedral //
// mesh and its settings. TetGen's functions operates on one mesh each time. //
// This type allows reusing of the same function for different meshes. //
// //
// The mesh data structure (tetrahedron-based and triangle-edge data struct- //
// ures) are declared. There are other accessary data type defined as well, //
// for efficient memory management and link list operations, etc. //
// //
// All algorithms TetGen used are implemented in this data type as member //
// functions. References of these algorithms can be found in user's manual. //
// //
// It's not necessary to understand this type. There is a global function //
// "tetrahedralize()" (defined at the end of this file) implicitly creates //
// the object and calls its member functions according to the command line //
// switches you specified. //
// //
///////////////////////////////////////////////////////////////////////////////
class tetgenmesh {
public:
// Maximum number of characters in a file name (including the null).
enum {FILENAMESIZE = 1024};
// For efficiency, a variety of data structures are allocated in bulk.
// The following constants determine how many of each structure is
// allocated at once.
enum {VERPERBLOCK = 4092, SUBPERBLOCK = 4092, ELEPERBLOCK = 8188};
// Used for the point location scheme of Mucke, Saias, and Zhu, to
// decide how large a random sample of tetrahedra to inspect.
enum {SAMPLEFACTOR = 11};
// Labels that signify two edge rings of a triangle defined in Muecke's
// triangle-edge data structure, one (CCW) traversing edges in count-
// erclockwise direction and one (CW) in clockwise direction.
enum {CCW = 0, CW = 1};
// Labels that signify whether a record consists primarily of pointers
// or of floating-point words. Used to make decisions about data
// alignment.
enum wordtype {POINTER, FLOATINGPOINT};
// Labels that signify the type of a vertex. An UNUSEDVERTEX is a vertex
// read from input (.node file or tetgenio structure) or an isolated
// vertex (outside the mesh). It is the default type for a newpoint.
enum verttype {UNUSEDVERTEX, DUPLICATEDVERTEX, NACUTEVERTEX, ACUTEVERTEX,
FREESEGVERTEX, FREESUBVERTEX, FREEVOLVERTEX, DEADVERTEX = -32768};
// Labels that signify the type of a subface/subsegment.
enum shestype {NSHARP, SHARP};
// Labels that signify the type of flips can be applied on a face.
// A flipable face has the one of the types T23, T32, T22, and T44.
// Types N32, N40 are unflipable.
enum fliptype {T23, T32, T22, T44, N32, N40, FORBIDDENFACE, FORBIDDENEDGE};
// Labels that signify the result of triangle-triangle intersection test.
// Two triangles are DISJOINT, or adjoint at a vertex SHAREVERTEX, or
// adjoint at an edge SHAREEDGE, or coincident SHAREFACE or INTERSECT.
enum interresult {DISJOINT, SHAREVERTEX, SHAREEDGE, SHAREFACE, INTERSECT};
// Labels that signify the result of point location. The result of a
// search indicates that the point falls inside a tetrahedron, inside
// a triangle, on an edge, on a vertex, or outside the mesh.
enum locateresult {INTETRAHEDRON, ONFACE, ONEDGE, ONVERTEX, OUTSIDE};
// Labels that signify the result of vertex insertion. The result
// indicates that the vertex was inserted with complete success, was
// inserted but encroaches upon a subsegment, was not inserted because
// it lies on a segment, or was not inserted because another vertex
// occupies the same location.
enum insertsiteresult {SUCCESSINTET, SUCCESSONFACE, SUCCESSONEDGE,
DUPLICATEPOINT, OUTSIDEPOINT};
// Labels that signify the result of direction finding. The result
// indicates that a segment connecting the two query points accross
// an edge of the direction triangle/tetrahedron, across a face of
// the direction tetrahedron, along the left edge of the direction
// triangle/tetrahedron, along the right edge of the direction
// triangle/tetrahedron, or along the top edge of the tetrahedron.
enum finddirectionresult {ACROSSEDGE, ACROSSFACE, LEFTCOLLINEAR,
RIGHTCOLLINEAR, TOPCOLLINEAR, BELOWHULL};
///////////////////////////////////////////////////////////////////////////////
// //
// The basic mesh element data structures //
// //
// There are four types of mesh elements: tetrahedra, subfaces, subsegments, //
// and points, where subfaces and subsegments are triangles and edges which //
// appear on boundaries. A tetrahedralization of a 3D point set comprises //
// tetrahedra and points; a surface mesh of a 3D domain comprises subfaces //
// subsegments and points. The elements of all the four types consist of a //
// tetrahedral mesh of a 3D domain. However, TetGen uses three data types: //
// 'tetrahedron', 'shellface', and 'point'. A 'tetrahedron' is a tetrahedron;//
// while a 'shellface' can be either a subface or a subsegment; and a 'point'//
// is a point. These three data types, linked by pointers comprise a mesh. //
// //
// A tetrahedron primarily consists of a list of 4 pointers to its corners, //
// a list of 4 pointers to its adjoining tetrahedra, a list of 4 pointers to //
// its adjoining subfaces (when subfaces are needed). Optinoally, (depending //
// on the selected switches), it may contain an arbitrary number of user- //
// defined floating-point attributes, an optional maximum volume constraint //
// (for -a switch), and a pointer to a list of high-order nodes (-o2 switch).//
// Since the size of a tetrahedron is not determined until running time, it //
// is not simply declared as a structure. //
// //
// The data structure of tetrahedron also stores the geometrical information.//
// Let t be a tetrahedron, v0, v1, v2, and v3 be the 4 nodes corresponding //
// to the order of their storage in t. v3 always has a negative orientation //
// with respect to v0, v1, v2 (ie,, v3 lies above the oriented plane passes //
// through v0, v1, v2). Let the 4 faces of t be f0, f1, f2, and f3. Vertices //
// of each face are stipulated as follows: f0 (v0, v1, v2), f1 (v0, v3, v1), //
// f2 (v1, v3, v2), f3 (v2, v3, v0). //
// //
// A subface has 3 pointers to vertices, 3 pointers to adjoining subfaces, 3 //
// pointers to adjoining subsegments, 2 pointers to adjoining tetrahedra, a //
// boundary marker(an integer). Like a tetrahedron, the pointers to vertices,//
// subfaces, and subsegments are ordered in a way that indicates their geom- //
// etric relation. Let s be a subface, v0, v1 and v2 be the 3 nodes corres- //
// ponding to the order of their storage in s, e0, e1 and e2 be the 3 edges,//
// then we have: e0 (v0, v1), e1 (v1, v2), e2 (v2, v0). //
// //
// A subsegment has exactly the same data fields as a subface has, but only //
// uses some of them. It has 2 pointers to its endpoints, 2 pointers to its //
// adjoining (and collinear) subsegments, a pointer to a subface containing //
// it (there may exist any number of subfaces having it, choose one of them //
// arbitrarily). The geometric relation between its endpoints and adjoining //
// subsegments is kept with respect to the storing order of its endpoints. //
// //
// The data structure of point is relatively simple. A point is a list of //
// floating-point numbers, starting with the x, y, and z coords, followed by //
// an arbitrary number of optional user-defined floating-point attributes, //
// an integer boundary marker, an integer for the point type, and a pointer //
// to a tetrahedron (used for speeding up point location). //
// //
// For a tetrahedron on a boundary (or a hull) of the mesh, some or all of //
// the adjoining tetrahedra may not be present. For an interior tetrahedron, //
// often no neighboring subfaces are present, Such absent tetrahedra and //
// subfaces are never represented by the NULL pointers; they are represented //
// by two special records: `dummytet', the tetrahedron fills "outer space", //
// and `dummysh', the vacuous subfaces which are omnipresent. //
// //
// Tetrahedra and adjoining subfaces are glued together through the pointers //
// saved in each data fields of them. Subfaces and adjoining subsegments are //
// connected in the same fashion. However, there are no pointers directly //
// gluing tetrahedra and adjoining subsegments. For the purpose of saving //
// space, the connections between tetrahedra and subsegments are entirely //
// mediated through subfaces. The following part explains how subfaces are //
// connected in TetGen. //
// //
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// //
// The subface-subface and subface-subsegment connections //
// //
// Adjoining subfaces sharing a common edge are connected in such a way that //
// they form a face ring around the edge. It is indeed a single linked list //
// which is cyclic, e.g., one can start from any subface in it and traverse //
// back. When the edge is not a subsegment, the ring only has two coplanar //
// subfaces which are pointing to each other. Otherwise, the face ring may //
// have any number of subfaces (and are not all coplanar). //
// //
// How is the face ring formed? Let s be a subsegment, f is one of subfaces //
// containing s as an edge. The direction of s is stipulated from its first //
// endpoint to its second (according to their storage in s). Once the dir of //
// s is determined, the other two edges of f are oriented to follow this dir.//
// The "directional normal" N_f is a vector formed from any point in f and a //
// points orthogonally above f. //
// //
// The face ring of s is a cyclic ordered set of subfaces containing s, i.e.,//
// F(s) = {f1, f2, ..., fn}, n >= 1. Where the order is defined as follows: //
// let fi, fj be two faces in F(s), the "normal-angle", NAngle(i,j) (range //
// from 0 to 360 degree) is the angle between the N_fi and N_fj; then fi is //
// in front of fj (or symbolically, fi < fj) if there exists another fk in //
// F(s), and NAangle(k, i) < NAngle(k, j). The face ring of s is: f1 < f2 < //
// ... < fn < f1. //
// //
// The easiest way to imagine how a face ring is formed is to use the right- //
// hand rule. Make a fist using your right hand with the thumb pointing to //
// the direction of the subsegment. The face ring is connected following the //
// direction of your fingers. //
// //
// The subface and subsegment are also connected through pointers stored in //
// their own data fields. Every subface has a pointer to its adjoining sub- //
// segment. However, a subsegment only has one pointer to a subface which is //
// containing it. Such subface can be chosen arbitrarily, other subfaces are //
// found through the face ring. //
// //
///////////////////////////////////////////////////////////////////////////////
// The tetrahedron data structure. Fields of a tetrahedron contains:
// - a list of four adjoining tetrahedra;
// - a list of four vertices;
// - a list of four subfaces (optional, used for -p switch);
// - a list of user-defined floating-point attributes (optional);
// - a volume constraint (optional, used for -a switch);
// - an integer of element marker (optional, used for -n switch);
// - a pointer to a list of high-ordered nodes (optional, -o2 switch);
typedef REAL **tetrahedron;
// The shellface data structure. Fields of a shellface contains:
// - a list of three adjoining subfaces;
// - a list of three vertices;
// - a list of two adjoining tetrahedra;
// - a list of three adjoining subsegments;
// - a pointer to a badface containing it (used for -q);
// - an area constraint (optional, used for -q);
// - an integer for boundary marker;
// - an integer for type: SHARPSEGMENT, NONSHARPSEGMENT, ...;
// - an integer for pbc group (optional, if in->pbcgrouplist exists);
typedef REAL **shellface;
// The point data structure. It is actually an array of REALs:
// - x, y and z coordinates;
// - a list of user-defined point attributes (optional);
// - a list of REALs of a user-defined metric tensor (optional);
// - a pointer to a simplex (tet, tri, edge, or vertex);
// - a pointer to a parent (or duplicate) point;
// - a pointer to a tet in background mesh (optional);
// - a pointer to another pbc point (optional);
// - an integer for boundary marker;
// - an integer for verttype: INPUTVERTEX, FREEVERTEX, ...;
typedef REAL *point;
///////////////////////////////////////////////////////////////////////////////
// //
// The mesh handle (triface, face) data types //
// //
// Two special data types, 'triface' and 'face' are defined for maintaining //
// and updating meshes. They are like pointers (or handles), which allow you //
// to hold one particular part of the mesh, i.e., a tetrahedron, a triangle, //
// an edge and a vertex. However, these data types do not themselves store //
// any part of the mesh. The mesh is made of the data types defined above. //
// //
// Muecke's "triangle-edge" data structure is the prototype for these data //
// types. It allows a universal representation for every tetrahedron, //
// triangle, edge and vertex. For understanding the following descriptions //
// of these handle data structures, readers are required to read both the //
// introduction and implementation detail of "triangle-edge" data structure //
// in Muecke's thesis. //
// //
// A 'triface' represents a face of a tetrahedron and an oriented edge of //
// the face simultaneously. It has a pointer 'tet' to a tetrahedron, an //
// integer 'loc' (range from 0 to 3) as the face index, and an integer 'ver' //
// (range from 0 to 5) as the edge version. A face of the tetrahedron can be //
// uniquly determined by the pair (tet, loc), and an oriented edge of this //
// face can be uniquly determined by the triple (tet, loc, ver). Therefore, //
// different usages of one triface are possible. If we only use the pair //
// (tet, loc), it refers to a face, and if we add the 'ver' additionally to //
// the pair, it is an oriented edge of this face. //
// //
// A 'face' represents a subface and an oriented edge of it simultaneously. //
// It has a pointer 'sh' to a subface, an integer 'shver'(range from 0 to 5) //
// as the edge version. The pair (sh, shver) determines a unique oriented //
// edge of this subface. A 'face' is also used to represent a subsegment, //
// in this case, 'sh' points to the subsegment, and 'shver' indicates the //
// one of two orientations of this subsegment, hence, it only can be 0 or 1. //
// //
// Mesh navigation and updating are accomplished through a set of mesh //
// manipulation primitives which operate on trifaces and faces. They are //
// introduced below. //
// //
///////////////////////////////////////////////////////////////////////////////
class triface {
public:
tetrahedron* tet;
int loc, ver;
// Constructors;
triface() : tet(0), loc(0), ver(0) {}
// Operators;
triface& operator=(const triface& t) {
tet = t.tet; loc = t.loc; ver = t.ver;
return *this;
}
bool operator==(triface& t) {
return tet == t.tet && loc == t.loc && ver == t.ver;
}
bool operator!=(triface& t) {
return tet != t.tet || loc != t.loc || ver != t.ver;
}
};
class face {
public:
shellface *sh;
int shver;
// Constructors;
face() : sh(0), shver(0) {}
// Operators;
face& operator=(const face& s) {
sh = s.sh; shver = s.shver;
return *this;
}
bool operator==(face& s) {return (sh == s.sh) && (shver == s.shver);}
bool operator!=(face& s) {return (sh != s.sh) || (shver != s.shver);}
};
///////////////////////////////////////////////////////////////////////////////
// //
// The badface structure //
// //
// A multiple usages structure. Despite of its name, a 'badface' can be used //
// to represent the following objects: //
// - a face of a tetrahedron which is (possibly) non-Delaunay; //
// - an encroached subsegment or subface; //
// - a bad-quality tetrahedron, i.e, has too large radius-edge ratio; //
// - a sliver, i.e., has good radius-edge ratio but nearly zero volume; //
// - a degenerate tetrahedron (see routine checkdegetet()). //
// - a recently flipped face (saved for undoing the flip later). //
// //
// It has the following fields: 'tt' holds a tetrahedron; 'ss' holds a sub- //
// segment or subface; 'cent' is the circumcent of 'tt' or 'ss', 'key' is a //
// special value depending on the use, it can be either the square of the //
// radius-edge ratio of 'tt' or the flipped type of 'tt'; 'forg', 'fdest', //
// 'fapex', and 'foppo' are vertices saved for checking the object in 'tt' //
// or 'ss' is still the same when it was stored; 'noppo' is the fifth vertex //
// of a degenerate point set. 'previtem' and 'nextitem' implement a double //
// link for managing many basfaces. //
// //
///////////////////////////////////////////////////////////////////////////////
struct badface {
triface tt;
face ss;
REAL key;
REAL cent[3];
point forg, fdest, fapex, foppo;
point noppo;
struct badface *previtem, *nextitem;
};
///////////////////////////////////////////////////////////////////////////////
// //
// The pbcdata structure //
// //
// A pbcdata stores data of a periodic boundary condition defined on a pair //
// of facets or segments. Let f1 and f2 define a pbcgroup. 'fmark' saves the //
// facet markers of f1 and f2; 'ss' contains two subfaces belong to f1 and //
// f2, respectively. Let s1 and s2 define a segment pbcgroup. 'segid' are //
// the segment ids of s1 and s2; 'ss' contains two segments belong to s1 and //
// s2, respectively. 'transmat' are two transformation matrices. transmat[0] //
// transforms a point of f1 (or s1) into a point of f2 (or s2), transmat[1] //
// does the inverse. //
// //
///////////////////////////////////////////////////////////////////////////////
struct pbcdata {
int fmark[2];
int segid[2];
face ss[2];
REAL transmat[2][4][4];
};
///////////////////////////////////////////////////////////////////////////////
// //
// The list, link and queue data structures //
// //
// These data types are used to manipulate a set of (same-typed) data items. //
// For a given set S = {a, b, c, ...}, a list stores the elements of S in a //
// piece of continuous memory. It allows quickly accessing each element of S,//
// thus is suitable for storing a fix-sized set. While a link stores its //
// elements incontinuously. It allows quickly inserting or deleting an item, //
// thus is suitable for storing a size-variable set. A queue is basically a //
// special case of a link where one data element joins the link at the end //
// and leaves in an ordered fashion at the other end. //
// //
///////////////////////////////////////////////////////////////////////////////
// The compfunc data type. "compfunc" is a pointer to a linear-order
// function, which takes two 'void*' arguments and returning an 'int'.
//
// A function: int cmp(const T &, const T &), is said to realize a
// linear order on the type T if there is a linear order <= on T such
// that for all x and y in T satisfy the following relation:
// -1 if x < y.
// comp(x, y) = 0 if x is equivalent to y.
// +1 if x > y.
typedef int (*compfunc) (const void *, const void *);
// The predefined compare functions for primitive data types. They
// take two pointers of the corresponding date type, perform the
// comparation, and return -1, 0 or 1 indicating the default linear
// order of them.
static int compare_2_ints(const void* x, const void* y);
static int compare_2_longs(const void* x, const void* y);
static int compare_2_unsignedlongs(const void* x, const void* y);
// The function used to determine the size of primitive data types and
// set the corresponding predefined linear order functions for them.
static void set_compfunc(char* str, int* itembytes, compfunc* pcomp);
///////////////////////////////////////////////////////////////////////////////
// //
// List data structure. //
// //
// A 'list' is an array of items with automatically reallocation of memory. //
// It behaves like an array. //
// //
// 'base' is the starting address of the array; The memory unit in list is //
// byte, i.e., sizeof(char). 'itembytes' is the size of each item in byte, //
// so that the next item in list will be found at the next 'itembytes' //
// counted from the current position. //
// //
// 'items' is the number of items stored in list. 'maxitems' indicates how //
// many items can be stored in this list. 'expandsize' is the increasing //
// size (items) when the list is full. //
// //
// 'comp' is a pointer pointing to a linear order function for the list. //
// default it is set to 'NULL'. //
// //
// The index of list always starts from zero, i.e., for a list L contains //
// n elements, the first element is L[0], and the last element is L[n-1]. //
// This feature lets lists like C/C++ arrays. //
// //
///////////////////////////////////////////////////////////////////////////////
class list {
public:
char *base;
int itembytes;
int items, maxitems, expandsize;
compfunc comp;
public:
list(int itbytes, compfunc pcomp, int mitems = 256, int exsize = 128) {
listinit(itbytes, pcomp, mitems, exsize);
}
list(char* str, int mitems = 256, int exsize = 128) {
set_compfunc(str, &itembytes, &comp);
listinit(itembytes, comp, mitems, exsize);
}
~list() { free(base); }
void *operator[](int i) { return (void *) (base + i * itembytes); }
void listinit(int itbytes, compfunc pcomp, int mitems, int exsize);
void setcomp(compfunc compf) { comp = compf; }
void clear() { items = 0; }
int len() { return items; }
void *append(void* appitem);
void *insert(int pos, void* insitem);
void del(int pos, int order);
int hasitem(void* checkitem);
void sort();
};
///////////////////////////////////////////////////////////////////////////////
// //
// Memorypool data structure. //
// //
// A type used to allocate memory. (It is incorporated from Shewchuk's //
// Triangle program) //
// //
// firstblock is the first block of items. nowblock is the block from which //
// items are currently being allocated. nextitem points to the next slab //
// of free memory for an item. deaditemstack is the head of a linked list //
// (stack) of deallocated items that can be recycled. unallocateditems is //
// the number of items that remain to be allocated from nowblock. //
// //
// Traversal is the process of walking through the entire list of items, and //
// is separate from allocation. Note that a traversal will visit items on //
// the "deaditemstack" stack as well as live items. pathblock points to //
// the block currently being traversed. pathitem points to the next item //
// to be traversed. pathitemsleft is the number of items that remain to //
// be traversed in pathblock. //
// //
// itemwordtype is set to POINTER or FLOATINGPOINT, and is used to suggest //
// what sort of word the record is primarily made up of. alignbytes //
// determines how new records should be aligned in memory. itembytes and //
// itemwords are the length of a record in bytes (after rounding up) and //
// words. itemsperblock is the number of items allocated at once in a //
// single block. items is the number of currently allocated items. //
// maxitems is the maximum number of items that have been allocated at //
// once; it is the current number of items plus the number of records kept //
// on deaditemstack. //
// //
///////////////////////////////////////////////////////////////////////////////
class memorypool {
public:
void **firstblock, **nowblock;
void *nextitem;
void *deaditemstack;
void **pathblock;
void *pathitem;
wordtype itemwordtype;
int alignbytes;
int itembytes, itemwords;
int itemsperblock;
long items, maxitems;
int unallocateditems;
int pathitemsleft;
public:
memorypool();
memorypool(int, int, enum wordtype, int);
~memorypool();
void poolinit(int, int, enum wordtype, int);
void restart();
void *alloc();
void dealloc(void*);
void traversalinit();
void *traverse();
};
///////////////////////////////////////////////////////////////////////////////
// //
// Link data structure. //
// //
// A 'link' is a double linked nodes. It uses the memorypool data structure //
// for memory management. Following is an image of a link. //
// //
// head-> ____0____ ____1____ ____2____ _________<-tail //
// |__next___|--> |__next___|--> |__next___|--> |__NULL___| //
// |__NULL___|<-- |__prev___|<-- |__prev___|<-- |__prev___| //
// | | |_ _| |_ _| | | //
// | | |_ Data1 _| |_ Data2 _| | | //
// |_________| |_________| |_________| |_________| //
// //
// The unit size for storage is size of pointer, which may be 4-byte (in 32- //
// bit machine) or 8-byte (in 64-bit machine). The real size of an item is //
// stored in 'linkitembytes'. //
// //
// 'head' and 'tail' are pointers pointing to the first and last nodes. They //
// do not conatin data (See above). //
// //
// 'nextlinkitem' is a pointer pointing to a node which is the next one will //
// be traversed. 'curpos' remembers the position (1-based) of the current //
// traversing node. //
// //
// 'linkitems' indicates how many items in link. Note it is different with //
// 'items' of memorypool. //
// //
// The index of link starts from 1, i.e., for a link K contains n elements, //
// the first element of the link is K[1], and the last element is K[n]. //
// See the above figure. //
// //
///////////////////////////////////////////////////////////////////////////////
class link : public memorypool {
public:
void **head, **tail;
void *nextlinkitem;
int linkitembytes;
int linkitems;
int curpos;
compfunc comp;
public:
link(int _itembytes, compfunc _comp, int itemcount) {
linkinit(_itembytes, _comp, itemcount);
}
link(char* str, int itemcount) {
set_compfunc(str, &linkitembytes, &comp);
linkinit(linkitembytes, comp, itemcount);
}
void linkinit(int _itembytes, compfunc _comp, int itemcount);
void setcomp(compfunc compf) { comp = compf; }
void rewind() { nextlinkitem = *head; curpos = 1; }
void goend() { nextlinkitem = *(tail + 1); curpos = linkitems; }
long len() { return linkitems; }
void clear();
bool move(int numberofnodes);
bool locate(int pos);
void *add(void* newitem);
void *insert(int pos, void* insitem);
void *deletenode(void** delnode);
void *del(int pos);
void *getitem();
void *getnitem(int pos);
int hasitem(void* checkitem);
};
///////////////////////////////////////////////////////////////////////////////
// //
// Queue data structure. //
// //
// A 'queue' is basically a link. Following is an image of a queue. //
// ___________ ___________ ___________ //
// Pop() <-- |_ _|<--|_ _|<--|_ _| <-- Push() //
// |_ Data0 _| |_ Data1 _| |_ Data2 _| //
// |___________| |___________| |___________| //
// queue head queue tail //
// //
///////////////////////////////////////////////////////////////////////////////
class queue : public link {
public:
queue(int bytes, int count = 256) : link(bytes, NULL, count) {}
bool empty() { return linkitems == 0; }
void *push(void* newitem) {return link::add(newitem);}
void *pop() {return link::deletenode((void **) *head);}
// Stack is implemented as a single link list.
void *stackpush() {
void **newnode = (void **) alloc();
// if (newitem != (void *) NULL) {
// memcpy((void *)(newnode + 2), newitem, linkitembytes);
// }
void **nextnode = (void **) *head;
*head = (void *) newnode;
*newnode = (void *) nextnode;
linkitems++;
return (void *)(newnode + 2);
}
void *stackpop() {
void **deadnode = (void **) *head;
*head = *deadnode;
linkitems--;
return (void *)(deadnode + 2);
}
};
///////////////////////////////////////////////////////////////////////////////
// //
// Global variables used for miscellaneous purposes. //
// //
///////////////////////////////////////////////////////////////////////////////
// Pointer to the input data (a set of nodes, a PLC, or a mesh).
tetgenio *in;
// Pointer to the options (and filenames).
tetgenbehavior *b;
// Pointer to a background mesh (contains size specification map).
tetgenmesh *bgm;
// Variables used to allocate and access memory for tetrahedra, subfaces
// subsegments, points, encroached subfaces, encroached subsegments,
// bad-quality tetrahedra, and so on.
memorypool *tetrahedrons;
memorypool *subfaces;
memorypool *subsegs;
memorypool *points;
memorypool *badsubsegs;
memorypool *badsubfaces;
memorypool *badtetrahedrons;
memorypool *flipstackers;
// Pointer to the 'tetrahedron' that occupies all of "outer space".
tetrahedron *dummytet;
tetrahedron *dummytetbase; // Keep base address so we can free it later.
// Pointer to the omnipresent subface. Referenced by any tetrahedron,
// or subface that isn't connected to a subface at that location.
shellface *dummysh;
shellface *dummyshbase; // Keep base address so we can free it later.
// A point above the plane in which the facet currently being used lies.
// It is used as a reference point for orient3d().
point *facetabovepointarray, abovepoint;
// Array (size = numberoftetrahedra * 6) for storing high-order nodes of
// tetrahedra (only used when -o2 switch is selected).
point *highordertable;
// Arrays for storing and searching pbc data. 'subpbcgrouptable', (size
// is numberofpbcgroups) for pbcgroup of subfaces. 'segpbcgrouptable',
// a list for pbcgroup of segments. Because a segment can have several
// pbcgroup incident on it, its size is unknown on input, it will be
// found in 'createsegpbcgrouptable()'.
pbcdata *subpbcgrouptable;
list *segpbcgrouptable;
// A map for searching the pbcgroups of a given segment. 'idx2segpglist'
// (size = number of input segments + 1), and 'segpglist'.
int *idx2segpglist, *segpglist;
// Queues that maintain the bad (badly-shaped or too large) tetrahedra.
// The tails are pointers to the pointers that have to be filled in to
// enqueue an item. The queues are ordered from 63 (highest priority)
// to 0 (lowest priority).
badface *subquefront[3], **subquetail[3];
badface *tetquefront[64], *tetquetail[64];
int nextnonemptyq[64];
int firstnonemptyq, recentq;
// Pointer to a recently visited tetrahedron. Improves point location
// if proximate points are inserted sequentially.
triface recenttet;
REAL xmax, xmin, ymax, ymin, zmax, zmin; // Bounding box of points.
REAL longest; // The longest possible edge length.
REAL lengthlimit; // The limiting length of a new edge.
long hullsize; // Number of faces of convex hull.
long insegments; // Number of input segments.
int steinerleft; // Number of Steiner points not yet used.
int sizeoftensor; // Number of REALs per metric tensor.
int pointmtrindex; // Index to find the metric tensor of a point.
int point2simindex; // Index to find a simplex adjacent to a point.
int pointmarkindex; // Index to find boundary marker of a point.
int point2pbcptindex; // Index to find a pbc point to a point.
int highorderindex; // Index to find extra nodes for highorder elements.
int elemattribindex; // Index to find attributes of a tetrahedron.
int volumeboundindex; // Index to find volume bound of a tetrahedron.
int elemmarkerindex; // Index to find marker of a tetrahedron.
int shmarkindex; // Index to find boundary marker of a subface.
int areaboundindex; // Index to find area bound of a subface.
int checksubfaces; // Are there subfaces in the mesh yet?
int checksubsegs; // Are there subsegs in the mesh yet?
int checkpbcs; // Are there periodic boundary conditions?
int varconstraint; // Are there variant (node, seg, facet) constraints?
int nonconvex; // Is current mesh non-convex?
int dupverts; // Are there duplicated vertices?
int unuverts; // Are there unused vertices?
int relverts; // The number of relocated vertices.
int suprelverts; // The number of suppressed relocated vertices.
int collapverts; // The number of collapsed relocated vertices.
int unsupverts; // The number of unsuppressed vertices.
int smoothsegverts; // The number of smoothed vertices.
int smoothvolverts; // The number of smoothed vertices.
int jettisoninverts; // The number of jettisoned input vertices.
int symbolic; // Use symbolic insphere test.
long samples; // Number of random samples for point location.
unsigned long randomseed; // Current random number seed.
REAL macheps; // The machine epsilon.
REAL cosmaxdihed, cosmindihed; // The cosine values of max/min dihedral.
REAL minfaceang, minfacetdihed; // The minimum input (dihedral) angles.
int maxcavfaces, maxcavverts; // The size of the largest cavity.
int expcavcount; // The times of expanding cavitys.
long abovecount; // Number of abovepoints calculation.
long bowatvolcount, bowatsubcount, bowatsegcount; // Bowyer-Watsons.
long updvolcount, updsubcount, updsegcount; // Bow-Wat cavities updates.
long failvolcount, failsubcount, failsegcount; // Bow-Wat fails.
long repairflipcount; // Number of flips for repairing segments.
long outbowatcircumcount; // Number of circumcenters outside Bowat-cav.
long r1count, r2count, r3count; // Numbers of edge splitting rules.
long cdtenforcesegpts; // Number of CDT enforcement points.
long rejsegpts, rejsubpts, rejtetpts; // Number of rejected points.
long optcount[10]; // Numbers of various optimizing operations.
long flip23s, flip32s, flip22s, flip44s; // Number of flips performed.
REAL tloctime, tfliptime; // Time (microseconds) of point location.
///////////////////////////////////////////////////////////////////////////////
// //
// Fast lookup tables for mesh manipulation primitives. //
// //
// Mesh manipulation primitives (given below) are basic operations on mesh //
// data structures. They answer basic queries on mesh handles, such as "what //
// is the origin (or destination, or apex) of the face?", "what is the next //
// (or previous) edge in the edge ring?", and "what is the next face in the //
// face ring?", and so on. //
// //
// The implementation of teste basic queries can take advangtage of the fact //
// that the mesh data structures additionally store geometric informations. //
// For example, we have ordered the 4 vertices (from 0 to 3) and the 4 faces //
// (from 0 to 3) of a tetrahedron, and for each face of the tetrahedron, a //
// sequence of vertices has stipulated, therefore the origin of any face of //
// the tetrahedron can be quickly determined by a table 'locver2org', which //
// takes the index of the face and the edge version as inputs. A list of //
// fast lookup tables are defined below. They're just like global variables. //
// These tables are initialized at the runtime. //
// //
///////////////////////////////////////////////////////////////////////////////
// For enext() primitive, uses 'ver' as the index.
static int ve[6];
// For org(), dest() and apex() primitives, uses 'ver' as the index.
static int vo[6], vd[6], va[6];
// For org(), dest() and apex() primitives, uses 'loc' as the first
// index and 'ver' as the second index.
static int locver2org[4][6];
static int locver2dest[4][6];
static int locver2apex[4][6];
// For oppo() primitives, uses 'loc' as the index.
static int loc2oppo[4];
// For fnext() primitives, uses 'loc' as the first index and 'ver' as
// the second index, returns an array containing a new 'loc' and a
// new 'ver'. Note: Only valid for 'ver' equals one of {0, 2, 4}.
static int locver2nextf[4][6][2];
// The edge number (from 0 to 5) of a tet is defined as follows:
static int locver2edge[4][6];
static int edge2locver[6][2];
// For enumerating three edges of a triangle.
static int plus1mod3[3];
static int minus1mod3[3];
///////////////////////////////////////////////////////////////////////////////
// //
// Mesh manipulation primitives //
// //
// A serial of mesh operations such as topological maintenance, navigation, //
// local modification, etc., is accomplished through a set of mesh manipul- //
// ation primitives. These primitives are indeed very simple functions which //
// take one or two handles ('triface's and 'face's) as parameters, perform //
// basic operations such as "glue two tetrahedra at a face", "return the //
// origin of a tetrahedron", "return the subface adjoining at the face of a //
// tetrahedron", and so on. //
// //
///////////////////////////////////////////////////////////////////////////////
// Primitives for tetrahedra.
inline void decode(tetrahedron ptr, triface& t);
inline tetrahedron encode(triface& t);
inline void sym(triface& t1, triface& t2);
inline void symself(triface& t);
inline void bond(triface& t1, triface& t2);
inline void dissolve(triface& t);
inline point org(triface& t);
inline point dest(triface& t);
inline point apex(triface& t);
inline point oppo(triface& t);
inline void setorg(triface& t, point pointptr);
inline void setdest(triface& t, point pointptr);
inline void setapex(triface& t, point pointptr);
inline void setoppo(triface& t, point pointptr);
inline void esym(triface& t1, triface& t2);
inline void esymself(triface& t);
inline void enext(triface& t1, triface& t2);
inline void enextself(triface& t);
inline void enext2(triface& t1, triface& t2);
inline void enext2self(triface& t);
inline bool fnext(triface& t1, triface& t2);
inline bool fnextself(triface& t);
inline void enextfnext(triface& t1, triface& t2);
inline void enextfnextself(triface& t);
inline void enext2fnext(triface& t1, triface& t2);
inline void enext2fnextself(triface& t);
inline void infect(triface& t);
inline void uninfect(triface& t);
inline bool infected(triface& t);
inline REAL elemattribute(tetrahedron* ptr, int attnum);
inline void setelemattribute(tetrahedron* ptr, int attnum, REAL value);
inline REAL volumebound(tetrahedron* ptr);
inline void setvolumebound(tetrahedron* ptr, REAL value);
// Primitives for subfaces and subsegments.
inline void sdecode(shellface sptr, face& s);
inline shellface sencode(face& s);
inline void spivot(face& s1, face& s2);
inline void spivotself(face& s);
inline void sbond(face& s1, face& s2);
inline void sbond1(face& s1, face& s2);
inline void sdissolve(face& s);
inline point sorg(face& s);
inline point sdest(face& s);
inline point sapex(face& s);
inline void setsorg(face& s, point pointptr);
inline void setsdest(face& s, point pointptr);
inline void setsapex(face& s, point pointptr);
inline void sesym(face& s1, face& s2);
inline void sesymself(face& s);
inline void senext(face& s1, face& s2);
inline void senextself(face& s);
inline void senext2(face& s1, face& s2);
inline void senext2self(face& s);
inline void sfnext(face&, face&);
inline void sfnextself(face&);
inline badface* shell2badface(face& s);
inline void setshell2badface(face& s, badface* value);
inline REAL areabound(face& s);
inline void setareabound(face& s, REAL value);
inline int shellmark(face& s);
inline void setshellmark(face& s, int value);
inline enum shestype shelltype(face& s);
inline void setshelltype(face& s, enum shestype value);
inline int shellpbcgroup(face& s);
inline void setshellpbcgroup(face& s, int value);
inline void sinfect(face& s);
inline void suninfect(face& s);
inline bool sinfected(face& s);
// Primitives for interacting tetrahedra and subfaces.
inline void tspivot(triface& t, face& s);
inline void stpivot(face& s, triface& t);
inline void tsbond(triface& t, face& s);
inline void tsdissolve(triface& t);
inline void stdissolve(face& s);
// Primitives for interacting subfaces and subsegs.
inline void sspivot(face& s, face& edge);
inline void ssbond(face& s, face& edge);
inline void ssdissolve(face& s);
inline void tsspivot1(triface& t, face& seg);
inline void tssbond1(triface& t, face& seg);
inline void tssdissolve1(triface& t);
// Primitives for points.
inline int pointmark(point pt);
inline void setpointmark(point pt, int value);
inline enum verttype pointtype(point pt);
inline void setpointtype(point pt, enum verttype value);
inline tetrahedron point2tet(point pt);
inline void setpoint2tet(point pt, tetrahedron value);
inline shellface point2sh(point pt);
inline void setpoint2sh(point pt, shellface value);
inline point point2ppt(point pt);
inline void setpoint2ppt(point pt, point value);
inline tetrahedron point2bgmtet(point pt);
inline void setpoint2bgmtet(point pt, tetrahedron value);
inline point point2pbcpt(point pt);
inline void setpoint2pbcpt(point pt, point value);
// Advanced primitives.
inline void adjustedgering(triface& t, int direction);
inline void adjustedgering(face& s, int direction);
inline bool isdead(triface* t);
inline bool isdead(face* s);
inline bool isfacehaspoint(triface* t, point testpoint);
inline bool isfacehaspoint(face* t, point testpoint);
inline bool isfacehasedge(face* s, point tend1, point tend2);
inline bool issymexist(triface* t);
void getnextsface(face*, face*);
void tsspivot(triface*, face*);
void sstpivot(face*, triface*);
bool findorg(triface* t, point dorg);
bool findorg(face* s, point dorg);
void findedge(triface* t, point eorg, point edest);
void findedge(face* s, point eorg, point edest);
void findface(triface *fface, point forg, point fdest, point fapex);
void getonextseg(face* s, face* lseg);
void getseghasorg(face* sseg, point dorg);
point getsubsegfarorg(face* sseg);
point getsubsegfardest(face* sseg);
void printtet(triface*);
void printsh(face*);
///////////////////////////////////////////////////////////////////////////////
// //
// Triangle-triangle intersection test //
// //
// The triangle-triangle intersection test is implemented with exact arithm- //
// etic. It exactly tells whether or not two triangles in three dimensions //
// intersect. Before implementing this test myself, I tried two C codes //
// (implemented by Thomas Moeller and Philippe Guigue, respectively), which //
// are all public available. However both of them failed frequently. Another //
// unconvenience is both codes only tell whether or not the two triangles //
// intersect without distinguishing the cases whether they exactly intersect //
// in interior or they just share a vertex or share an edge. The two latter //
// cases are acceptable and should return not intersection in TetGen. //
// //
///////////////////////////////////////////////////////////////////////////////
enum interresult edge_vert_col_inter(REAL*, REAL*, REAL*);
enum interresult edge_edge_cop_inter(REAL*, REAL*, REAL*, REAL*, REAL*);
enum interresult tri_vert_cop_inter(REAL*, REAL*, REAL*, REAL*, REAL*);
enum interresult tri_edge_cop_inter(REAL*, REAL*, REAL*,REAL*,REAL*,REAL*);
enum interresult tri_edge_inter_tail(REAL*, REAL*, REAL*, REAL*, REAL*,
REAL, REAL);
enum interresult tri_edge_inter(REAL*, REAL*, REAL*, REAL*, REAL*);
enum interresult tri_tri_inter(REAL*, REAL*, REAL*, REAL*, REAL*, REAL*);
// Geometric predicates
REAL insphere_sos(REAL*, REAL*, REAL*, REAL*, REAL*, int, int,int,int,int);
bool iscollinear(REAL*, REAL*, REAL*, REAL eps);
bool iscoplanar(REAL*, REAL*, REAL*, REAL*, REAL vol6, REAL eps);
bool iscospheric(REAL*, REAL*, REAL*, REAL*, REAL*, REAL vol24, REAL eps);
// Linear algebra functions
inline REAL dot(REAL* v1, REAL* v2);
inline void cross(REAL* v1, REAL* v2, REAL* n);
bool lu_decmp(REAL lu[4][4], int n, int* ps, REAL* d, int N);
void lu_solve(REAL lu[4][4], int n, int* ps, REAL* b, int N);
// Geometric quantities calculators.
inline REAL distance(REAL* p1, REAL* p2);
REAL shortdistance(REAL* p, REAL* e1, REAL* e2);
REAL shortdistance(REAL* p, REAL* e1, REAL* e2, REAL* e3);
REAL interiorangle(REAL* o, REAL* p1, REAL* p2, REAL* n);
void projpt2edge(REAL* p, REAL* e1, REAL* e2, REAL* prj);
void projpt2face(REAL* p, REAL* f1, REAL* f2, REAL* f3, REAL* prj);
void facenormal(REAL* pa, REAL* pb, REAL* pc, REAL* n, REAL* nlen);
void edgeorthonormal(REAL* e1, REAL* e2, REAL* op, REAL* n);
REAL facedihedral(REAL* pa, REAL* pb, REAL* pc1, REAL* pc2);
void tetalldihedral(point, point, point, point, REAL*, REAL*, REAL*);
void tetallnormal(point, point, point, point, REAL N[4][3], REAL* volume);
REAL tetaspectratio(point, point, point, point);
bool circumsphere(REAL*, REAL*, REAL*, REAL*, REAL* cent, REAL* radius);
void inscribedsphere(REAL*, REAL*, REAL*, REAL*, REAL* cent, REAL* radius);
void rotatepoint(REAL* p, REAL rotangle, REAL* p1, REAL* p2);
void spherelineint(REAL* p1, REAL* p2, REAL* C, REAL R, REAL p[7]);
void linelineint(REAL *p1,REAL *p2, REAL *p3, REAL *p4, REAL p[7]);
void planelineint(REAL*, REAL*, REAL*, REAL*, REAL*, REAL*, REAL*);
// Memory managment routines.
void dummyinit(int, int);
void initializepools();
void tetrahedrondealloc(tetrahedron*);
tetrahedron *tetrahedrontraverse();
void shellfacedealloc(memorypool*, shellface*);
shellface *shellfacetraverse(memorypool*);
void badfacedealloc(memorypool*, badface*);
badface *badfacetraverse(memorypool*);
void pointdealloc(point);
point pointtraverse();
void maketetrahedron(triface*);
void makeshellface(memorypool*, face*);
void makepoint(point*);
// Mesh items searching routines.
void makepoint2tetmap();
void makeindex2pointmap(point*& idx2verlist);
void makesegmentmap(int*& idx2seglist, shellface**& segsperverlist);
void makesubfacemap(int*& idx2facelist, shellface**& facesperverlist);
void maketetrahedronmap(int*& idx2tetlist, tetrahedron**& tetsperverlist);
// Point location routines.
unsigned long randomnation(unsigned int choices);
REAL distance2(tetrahedron* tetptr, point p);
enum locateresult preciselocate(point searchpt, triface* searchtet, long);
enum locateresult locate(point searchpt, triface* searchtet);
enum locateresult adjustlocate(point, triface*, enum locateresult, REAL);
enum locateresult hullwalk(point searchpt, triface* hulltet);
enum locateresult locatesub(point searchpt, face* searchsh, int, REAL);
enum locateresult adjustlocatesub(point, face*, enum locateresult, REAL);
enum locateresult locateseg(point searchpt, face* searchseg);
enum locateresult adjustlocateseg(point, face*, enum locateresult, REAL);
///////////////////////////////////////////////////////////////////////////////
// //
// Mesh Local Transformation Operators //
// //
// These operators (including flips, insert & remove vertices and so on) are //
// used to transform (or replace) a set of mesh elements into another set of //
// mesh elements. //
// //
///////////////////////////////////////////////////////////////////////////////
// Mesh transformation routines.
enum fliptype categorizeface(triface& horiz);
void enqueueflipface(triface& checkface, queue* flipqueue);
void enqueueflipedge(face& checkedge, queue* flipqueue);
void flip23(triface* flipface, queue* flipqueue);
void flip32(triface* flipface, queue* flipqueue);
void flip22(triface* flipface, queue* flipqueue);
void flip22sub(face* flipedge, queue* flipqueue);
long flip(queue* flipqueue, badface **plastflip);
long lawson(list *misseglist, queue* flipqueue);
void undoflip(badface *lastflip);
long flipsub(queue* flipqueue);
bool removetetbypeeloff(triface *striptet);
bool removefacebyflip23(REAL *key, triface*, triface*, queue*);
bool removeedgebyflip22(REAL *key, int, triface*, queue*);
bool removeedgebyflip32(REAL *key, triface*, triface*, queue*);
bool removeedgebytranNM(REAL*,int,triface*,triface*,point,point,queue*);
bool removeedgebycombNM(REAL*,int,triface*,int*,triface*,triface*,queue*);
void splittetrahedron(point newpoint, triface* splittet, queue* flipqueue);
void unsplittetrahedron(triface* splittet);
void splittetface(point newpoint, triface* splittet, queue* flipqueue);
void unsplittetface(triface* splittet);
void splitsubface(point newpoint, face* splitface, queue* flipqueue);
void unsplitsubface(face* splitsh);
void splittetedge(point newpoint, triface* splittet, queue* flipqueue);
void unsplittetedge(triface* splittet);
void splitsubedge(point newpoint, face* splitsh, queue* flipqueue);
void unsplitsubedge(face* splitsh);
enum insertsiteresult insertsite(point newpoint, triface* searchtet,
bool approx, queue* flipqueue);
void undosite(enum insertsiteresult insresult, triface* splittet,
point torg, point tdest, point tapex, point toppo);
void closeopenface(triface* openface, queue* flipque);
void inserthullsite(point inspoint, triface* horiz, queue* flipque);
void formbowatcavitysub(point, face*, list*, list*);
void formbowatcavityquad(point, list*, list*);
void formbowatcavitysegquad(point, list*, list*);
void formbowatcavity(point bp, face* bpseg, face* bpsh, int* n, int* nmax,
list** sublists, list** subceillists, list** tetlists,
list** ceillists);
void releasebowatcavity(face*, int, list**, list**, list**, list**);
bool validatebowatcavityquad(point bp, list* ceillist, REAL maxcosd);
void updatebowatcavityquad(list* tetlist, list* ceillist);
void updatebowatcavitysub(list* sublist, list* subceillist, int* cutcount);
bool trimbowatcavity(point bp, face* bpseg, int n, list** sublists,
list** subceillists, list** tetlists,list** ceillists,
REAL maxcosd);
void bowatinsertsite(point bp, face* splitseg, int n, list** sublists,
list** subceillists, list** tetlists,
list** ceillists, list* verlist, queue* flipque,
bool chkencseg, bool chkencsub, bool chkbadtet);
// Delaunay tetrahedralization routines.
void formstarpolyhedron(point pt, list* tetlist, list* verlist, bool);
bool unifypoint(point testpt, triface*, enum locateresult, REAL);
void incrflipdelaunay(triface*, point*, long, bool, bool, REAL, queue*);
long delaunizevertices();
// Surface triangulation routines.
void formstarpolygon(point pt, list* trilist, list* verlist);
void getfacetabovepoint(face* facetsh);
void collectcavsubs(point newpoint, list* cavsublist);
void collectvisiblesubs(int shmark, point inspoint, face* horiz, queue*);
void incrflipdelaunaysub(int shmark, REAL eps, list*, int, REAL*, queue*);
enum finddirectionresult finddirectionsub(face* searchsh, point tend);
void insertsubseg(face* tri);
bool scoutsegmentsub(face* searchsh, point tend);
void flipedgerecursive(face* flipedge, queue* flipqueue);
void constrainededge(face* startsh, point tend, queue* flipqueue);
void recoversegment(point tstart, point tend, queue* flipqueue);
void infecthullsub(memorypool* viri);
void plaguesub(memorypool* viri);
void carveholessub(int holes, REAL* holelist, memorypool* viri);
void triangulate(int shmark, REAL eps, list* ptlist, list* conlist,
int holes, REAL* holelist, memorypool* viri, queue*);
void retrievenewsubs(list* newshlist, bool removeseg);
void unifysegments();
void mergefacets(queue* flipqueue);
long meshsurface();
// Detect intersecting facets of PLC.
void interecursive(shellface** subfacearray, int arraysize, int axis,
REAL bxmin, REAL bxmax, REAL bymin, REAL bymax,
REAL bzmin, REAL bzmax, int* internum);
void detectinterfaces();
// Periodic boundary condition supporting routines.
void createsubpbcgrouptable();
void getsubpbcgroup(face* pbcsub, pbcdata** pd, int *f1, int *f2);
enum locateresult getsubpbcsympoint(point, face*, point, face*);
void createsegpbcgrouptable();
enum locateresult getsegpbcsympoint(point, face*, point, face*, int);
// Vertex perturbation routines.
REAL randgenerator(REAL range);
bool checksub4cocir(face* testsub, REAL eps, bool once, bool enqflag);
void tallcocirsubs(REAL eps, bool enqflag);
bool tallencsegsfsubs(point testpt, list* cavsublist);
void collectflipedges(point inspoint, face* splitseg, queue* flipqueue);
void perturbrepairencsegs(queue* flipqueue);
void perturbrepairencsubs(list* cavsublist, queue* flipqueue);
void incrperturbvertices(REAL eps);
// Segment recovery routines.
void markacutevertices(REAL acuteangle);
enum finddirectionresult finddirection(triface* searchtet, point, long);
void getsearchtet(point p1, point p2, triface* searchtet, point* tend);
bool isedgeencroached(point p1, point p2, point testpt, bool degflag);
point scoutrefpoint(triface* searchtet, point tend);
point getsegmentorigin(face* splitseg);
point getsplitpoint(face* splitseg, point refpoint);
bool insertsegment(face *insseg, list *misseglist);
void tallmissegs(list *misseglist);
void delaunizesegments();
// Facets recovery routines.
bool insertsubface(face* insertsh, triface* searchtet);
bool tritritest(triface* checktet, point p1, point p2, point p3);
void initializecavity(list* floorlist, list* ceillist, list* frontlist);
void delaunizecavvertices(triface*, list*, list*, list*, queue*);
void retrievenewtets(list* newtetlist);
void insertauxsubface(triface* front, triface* idfront);
bool scoutfront(triface* front, triface* idfront, list* newtetlist);
void gluefronts(triface* front, triface* front1);
bool identifyfronts(list* frontlist, list* misfrontlist, list* newtetlist);
void detachauxsubfaces(list* newtetlist);
void expandcavity(list* frontlist, list* misfrontlist, list* newtetlist,
list* crosstetlist, queue* missingshqueue, queue*);
void carvecavity(list* newtetlist, list* outtetlist, queue* flipque);
void delaunizecavity(list* floorlist, list* ceillist, list* ceilptlist,
list* floorptlist, list* frontlist,list* misfrontlist,
list* newtetlist, list* crosstetlist, queue*, queue*);
void formmissingregion(face* missingsh, list* missingshlist,
list* equatptlist, int* worklist);
void formcavity(list* missingshlist, list* crossedgelist,
list* equatptlist, list* crossshlist, list* crosstetlist,
list* belowfacelist, list* abovefacelist,
list* horizptlist, list* belowptlist, list* aboveptlist,
queue* missingshqueue, int* worklist);
bool scoutcrossingedge(list* missingshlist, list* boundedgelist,
list* crossedgelist, int* worklist);
void rearrangesubfaces(list* missingshlist, list* boundedgelist,
list* equatptlist, int* worklist);
void insertallsubfaces(queue* missingshqueue);
void constrainedfacets();
// Carving out holes and concavities routines.
void infecthull(memorypool *viri);
void plague(memorypool *viri);
void regionplague(memorypool *viri, REAL attribute, REAL volume);
void removeholetets(memorypool *viri);
void assignregionattribs();
void carveholes();
// Steiner points removing routines.
void replacepolygonsubs(list* oldshlist, list* newshlist);
void orientnewsubs(list* newshlist, face* orientsh, REAL* norm);
bool constrainedflip(triface* flipface, triface* front, queue* flipque);
bool recoverfront(triface* front, list* newtetlist, queue* flipque);
void repairflips(queue* flipque);
bool constrainedcavity(triface* oldtet, list* floorlist, list* ceillist,
list* ptlist, list* frontlist, list* misfrontlist,
list* newtetlist, queue* flipque);
void expandsteinercavity(point steinpt, REAL eps, list* frontlist, list*);
bool findrelocatepoint(point sp, point np, REAL* n, list*, list*);
void relocatepoint(point steinpt, triface* oldtet, list*, list*, queue*);
bool findcollapseedge(point suppt, point* conpt, list* oldtetlist, list*);
void collapseedge(point suppt, point conpt, list* oldtetlist, list*);
void deallocfaketets(list* frontlist);
void restorepolyhedron(list* oldtetlist);
bool suppressfacetpoint(face* supsh, list* frontlist, list* misfrontlist,
list* ptlist, list* conlist, memorypool* viri,
queue* flipque, bool noreloc, bool optflag);
bool suppresssegpoint(face* supseg, list* spinshlist, list* newsegshlist,
list* frontlist, list* misfrontlist, list* ptlist,
list* conlist, memorypool* viri, queue* flipque,
bool noreloc, bool optflag);
bool suppressvolpoint(triface* suptet, list* frontlist, list* misfrontlist,
list* ptlist, queue* flipque, bool optflag);
bool smoothpoint(point smthpt, point, point, list *starlist, bool, REAL*);
void removesteiners(bool coarseflag);
// Mesh reconstruction routines.
long reconstructmesh();
// Constrained points insertion routines.
void insertconstrainedpoints(tetgenio *addio);
// Background mesh operations.
bool p1interpolatebgm(point pt, triface* bgmtet, long *scount);
void interpolatesizemap();
void duplicatebgmesh();
// Delaunay refinement routines.
void marksharpsegments(REAL sharpangle);
void decidefeaturepointsizes();
void enqueueencsub(face* ss, point encpt, int quenumber, REAL* cent);
badface* dequeueencsub(int* quenumber);
void enqueuebadtet(triface* tt, REAL key, REAL* cent);
badface* topbadtetra();
void dequeuebadtet();
bool checkseg4encroach(face* testseg, point testpt, point*, bool enqflag);
bool checksub4encroach(face* testsub, point testpt, bool enqflag);
bool checktet4badqual(triface* testtet, bool enqflag);
bool acceptsegpt(point segpt, point refpt, face* splitseg);
bool acceptfacpt(point facpt, list* subceillist, list* verlist);
bool acceptvolpt(point volpt, list* ceillist, list* verlist);
void getsplitpoint(point e1, point e2, point refpt, point newpt);
void shepardinterpolate(point newpt, list* verlist);
void setnewpointsize(point newpt, point e1, point e2);
void splitencseg(point, face*, list*, list*, list*,queue*,bool,bool,bool);
bool tallencsegs(point testpt, int n, list** ceillists);
bool tallencsubs(point testpt, int n, list** ceillists);
void tallbadtetrahedrons();
void repairencsegs(bool chkencsub, bool chkbadtet);
void repairencsubs(bool chkbadtet);
void repairbadtets();
void enforcequality();
// Mesh optimization routines.
void dumpbadtets();
bool checktet4ill(triface* testtet, bool enqflag);
bool checktet4opt(triface* testtet, bool enqflag);
bool removeedge(badface* remedge, bool optflag);
bool smoothsliver(badface* remedge, list *starlist);
bool splitsliver(badface* remedge, list *tetlist, list *ceillist);
void tallslivers(bool optflag);
void optimizemesh(bool optflag);
// I/O routines
void transfernodes();
void jettisonnodes();
void highorder();
void outnodes(tetgenio* out);
void outmetrics(tetgenio* out);
void outelements(tetgenio* out);
void outfaces(tetgenio* out);
void outhullfaces(tetgenio* out);
void outsubfaces(tetgenio* out);
void outedges(tetgenio* out);
void outsubsegments(tetgenio* out);
void outneighbors(tetgenio* out);
void outvoronoi(tetgenio* out);
void outpbcnodes(tetgenio* out);
void outsmesh(char* smfilename);
void outmesh2medit(char* mfilename);
void outmesh2gid(char* gfilename);
void outmesh2off(char* ofilename);
// User interaction routines.
void internalerror();
void checkmesh();
void checkshells();
void checkdelaunay(REAL eps, queue* flipqueue);
void checkconforming();
void algorithmicstatistics();
void qualitystatistics();
void statistics();
public:
// Constructor and destructor.
tetgenmesh();
~tetgenmesh();
}; // End of class tetgenmesh.
///////////////////////////////////////////////////////////////////////////////
// //
// tetrahedralize() Interface for using TetGen's library to generate //
// Delaunay tetrahedralizations, constrained Delaunay //
// tetrahedralizations, quality tetrahedral meshes. //
// //
// 'in' is an object of 'tetgenio' which contains a PLC you want to tetrahed-//
// ralize or a previously generated tetrahedral mesh you want to refine. It //
// must not be a NULL. 'out' is another object of 'tetgenio' for storing the //
// generated tetrahedral mesh. It can be a NULL. If so, the output will be //
// saved to file(s). If 'bgmin' != NULL, it contains a background mesh which //
// defines a mesh size distruction function. //
// //
///////////////////////////////////////////////////////////////////////////////
void tetrahedralize(tetgenbehavior *b, tetgenio *in, tetgenio *out,
tetgenio *addin = NULL, tetgenio *bgmin = NULL);
void tetrahedralize(char *switches, tetgenio *in, tetgenio *out,
tetgenio *addin = NULL, tetgenio *bgmin = NULL);
extern "C"
#ifdef Q_WS_WIN
__declspec(dllexport)
#endif
void delegate_tetrahedralize(int bs, tetgenbehavior *b, char *switches,
tetgenio *in, tetgenio *out, tetgenio *addin = NULL, tetgenio *bgmin = NULL);
#endif // #ifndef tetgenH
| 55.025974 | 79 | 0.54768 |
63f019fada3bf2a1af25c1f4491b3853dd6682bb | 3,433 | h | C | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/et4000w32/w32/w32blt.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/et4000w32/w32/w32blt.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/et4000w32/w32/w32blt.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | /* $XFree86: xc/programs/Xserver/hw/xfree86/accel/et4000w32/w32/w32blt.h,v 3.7 1996/12/23 06:35:22 dawes Exp $ */
/*******************************************************************************
Copyright 1994 by Glenn G. Lai
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyr notice appear in all copies and that
both that copyr notice and this permission notice appear in
supporting documentation, and that the name of Glenn G. Lai not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
Glenn G. Lai DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, 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.
Glenn G. Lai
P.O. Box 4314
Austin, Tx 78765
glenn@cs.utexas.edu)
4/6/94
*******************************************************************************/
/* $XConsortium: w32blt.h /main/7 1996/10/23 18:41:06 kaleb $ */
#ifndef W32BLT_H
#define W32BLT_H
#include "w32.h"
/* initizliae a bitblt operation */
#define W32_INIT_WINWIN(OP, MASK, SRC_OFFSET, DST_OFFSET, XDIR, YDIR) \
{ \
int i; \
\
*ACL_SOURCE_WRAP = 0x77; \
if (MASK == 0xffffffff) \
*ACL_FOREGROUND_RASTER_OPERATION = W32OpTable[OP]; \
else \
{ \
*ACL_FOREGROUND_RASTER_OPERATION = \
(0xf0 & W32OpTable[OP]) | 0x0a; \
*ACL_PATTERN_ADDRESS = W32Pattern; \
*MBP0 = W32Pattern; \
*(LongP)W32Buffer = MASK; \
if (W32p || W32et6000) \
*ACL_PATTERN_WRAP = 0x02; \
else \
{ \
*(LongP)(W32Buffer + 4) = MASK; \
*ACL_PATTERN_WRAP = 0x12; \
*ACL_PATTERN_Y_OFFSET = 0x3; \
} \
} \
i = 0; \
if (XDIR == -1) i |= 0x1; \
if (YDIR == -1) i |= 0x2; \
*ACL_XY_DIRECTION = i; \
*ACL_DESTINATION_Y_OFFSET = DST_OFFSET; \
*ACL_SOURCE_Y_OFFSET = SRC_OFFSET; \
if (W32et6000) \
*ACL_MIX_CONTROL = 0x33; \
else \
*ACL_ROUTING_CONTROL = 0x00; \
}
#define W32_WINWIN(SRC, DST, X, Y) \
if (((X) | (Y) != 0)) \
{ \
SET_XY(X, Y) \
*(ACL_SOURCE_ADDRESS) = SRC; \
START_ACL(DST) \
}
#define W32_INIT_PIXWIN(OP, MASK, DST_OFFSET) \
{ \
if (MASK == 0xffffffff) \
*ACL_FOREGROUND_RASTER_OPERATION = W32OpTable[OP]; \
else \
{ \
*ACL_FOREGROUND_RASTER_OPERATION = \
(0xf0 & W32OpTable[OP]) | 0x0a; \
*ACL_PATTERN_ADDRESS = W32Pattern; \
*MBP0 = W32Pattern; \
*(LongP)W32Buffer = MASK; \
if (W32p || W32et6000) \
*ACL_PATTERN_WRAP = 0x02; \
else \
{ \
*(LongP)(W32Buffer + 4) = MASK; \
*ACL_PATTERN_WRAP = 0x12; \
*ACL_PATTERN_Y_OFFSET = 0x3; \
*ACL_VIRTUAL_BUS_SIZE = 0x2; \
} \
} \
*ACL_XY_DIRECTION = 0; \
*ACL_DESTINATION_Y_OFFSET = DST_OFFSET; \
*ACL_ROUTING_CONTROL = 0x1; \
}
#define W32_PIXWIN(SRC, DST, X, Y) \
if (((X) | (Y) != 0)) \
{ \
SET_XY(X, Y) \
W32InitPixWin(SRC, X); \
START_ACL(DST) \
W32PixWin(SRC, Y); \
}
#endif /* W32BLT_H */
| 28.371901 | 115 | 0.611127 |
eb722537605f8dd8723d6c65ea13a706909a464e | 589 | h | C | src/kll/Behaviours/ImplodeBehaviour.h | damian0815/kll | 85998f89c2a32f6678c0d5f2d2c2ca4819433e57 | [
"MIT"
] | 1 | 2018-12-14T08:38:21.000Z | 2018-12-14T08:38:21.000Z | src/kll/Behaviours/ImplodeBehaviour.h | damian0815/kll | 85998f89c2a32f6678c0d5f2d2c2ca4819433e57 | [
"MIT"
] | null | null | null | src/kll/Behaviours/ImplodeBehaviour.h | damian0815/kll | 85998f89c2a32f6678c0d5f2d2c2ca4819433e57 | [
"MIT"
] | null | null | null | //
// Created by Damian Stewart on 10/12/2016.
//
#ifndef OFAPP_IMPLODEBEHAVIOUR_H
#define OFAPP_IMPLODEBEHAVIOUR_H
#include "Behaviour.h"
#include "../Engine/gvec3.h"
#include <glm/glm.hpp>
using glm::vec3;
namespace kll {
class ImplodeBehaviour: public Behaviour
{
public:
void Setup(Object *target, kll::gvec3 scaleAffect);
void Update(float dt) override;
bool ShouldObjectBeDestroyed() override;
void Reset() override ;
private:
float mScale = 1;
vec3 mScaleAffect;
};
}
#endif //OFAPP_IMPLODEBEHAVIOUR_H
| 16.361111 | 59 | 0.663837 |
e46edb74f8a573c7f90dce00661ec12c73d41772 | 8,841 | h | C | openfpga/src/fpga_bitstream/fabric_bitstream.h | LNIS-Projects/POSH | 9a3c82039d40c3878549775264b0d769237a65d0 | [
"MIT"
] | 1 | 2022-03-26T23:19:26.000Z | 2022-03-26T23:19:26.000Z | openfpga/src/fpga_bitstream/fabric_bitstream.h | VHDL-Digital-Systems/OpenFPGA | 9d00308166b8800d245b265d7378b0593761a61f | [
"MIT"
] | 7 | 2022-03-17T16:27:46.000Z | 2022-03-31T06:34:30.000Z | openfpga/src/fpga_bitstream/fabric_bitstream.h | VHDL-Digital-Systems/OpenFPGA | 9d00308166b8800d245b265d7378b0593761a61f | [
"MIT"
] | null | null | null | /******************************************************************************
* This file introduces a data structure to store fabric-dependent bitstream information
*
* General concept
* ---------------
* The idea is to create a unified data structure that stores the sequence of configuration
* bit in the architecture bitstream database
* as well as the information (such as address of each bit) required by a specific
* configuration protocol
*
* Cross-reference
* ---------------
* By using the link between ArchBitstreamManager and FabricBitstream,
* we can build a sequence of configuration bits to fit different configuration protocols.
*
* +----------------------+ +-------------------+
* | | ConfigBitId | |
* | ArchBitstreamManager |---------------->| FabricBitstream |
* | | | |
* +----------------------+ +-------------------+
*
* Restrictions:
* 1. Each block inside BitstreamManager should have only 1 parent block
* and multiple child block
* 2. Each bit inside BitstreamManager should have only 1 parent block
*
******************************************************************************/
#ifndef FABRIC_BITSTREAM_H
#define FABRIC_BITSTREAM_H
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include "vtr_vector.h"
#include "bitstream_manager_fwd.h"
#include "fabric_bitstream_fwd.h"
/* begin namespace openfpga */
namespace openfpga {
class FabricBitstream {
public: /* Type implementations */
/*
* This class (forward delcared above) is a template used to represent a lazily calculated
* iterator of the specified ID type. The key assumption made is that the ID space is
* contiguous and can be walked by incrementing the underlying ID value. To account for
* invalid IDs, it keeps a reference to the invalid ID set and returns ID::INVALID() for
* ID values in the set.
*
* It is used to lazily create an iteration range (e.g. as returned by RRGraph::edges() RRGraph::nodes())
* just based on the count of allocated elements (i.e. RRGraph::num_nodes_ or RRGraph::num_edges_),
* and the set of any invalid IDs (i.e. RRGraph::invalid_node_ids_, RRGraph::invalid_edge_ids_).
*/
template<class ID>
class lazy_id_iterator : public std::iterator<std::bidirectional_iterator_tag, ID> {
public:
//Since we pass ID as a template to std::iterator we need to use an explicit 'typename'
//to bring the value_type and iterator names into scope
typedef typename std::iterator<std::bidirectional_iterator_tag, ID>::value_type value_type;
typedef typename std::iterator<std::bidirectional_iterator_tag, ID>::iterator iterator;
lazy_id_iterator(value_type init, const std::unordered_set<ID>& invalid_ids)
: value_(init)
, invalid_ids_(invalid_ids) {}
//Advance to the next ID value
iterator operator++() {
value_ = ID(size_t(value_) + 1);
return *this;
}
//Advance to the previous ID value
iterator operator--() {
value_ = ID(size_t(value_) - 1);
return *this;
}
//Dereference the iterator
value_type operator*() const { return (invalid_ids_.count(value_)) ? ID::INVALID() : value_; }
friend bool operator==(const lazy_id_iterator<ID> lhs, const lazy_id_iterator<ID> rhs) { return lhs.value_ == rhs.value_; }
friend bool operator!=(const lazy_id_iterator<ID> lhs, const lazy_id_iterator<ID> rhs) { return !(lhs == rhs); }
private:
value_type value_;
const std::unordered_set<ID>& invalid_ids_;
};
public: /* Types and ranges */
//Lazy iterator utility forward declaration
template<class ID>
class lazy_id_iterator;
typedef lazy_id_iterator<FabricBitId> fabric_bit_iterator;
typedef lazy_id_iterator<FabricBitRegionId> fabric_bit_region_iterator;
typedef vtr::Range<fabric_bit_iterator> fabric_bit_range;
typedef vtr::Range<fabric_bit_region_iterator> fabric_bit_region_range;
public: /* Public constructor */
FabricBitstream();
public: /* Public aggregators */
/* Find all the configuration bits */
size_t num_bits() const;
fabric_bit_range bits() const;
/* Find all the configuration regions */
size_t num_regions() const;
fabric_bit_region_range regions() const;
std::vector<FabricBitId> region_bits(const FabricBitRegionId& region_id) const;
public: /* Public Accessors */
/* Find the configuration bit id in architecture bitstream database */
ConfigBitId config_bit(const FabricBitId& bit_id) const;
/* Find the address of bitstream */
std::vector<char> bit_address(const FabricBitId& bit_id) const;
std::vector<char> bit_bl_address(const FabricBitId& bit_id) const;
std::vector<char> bit_wl_address(const FabricBitId& bit_id) const;
/* Find the data-in of bitstream */
char bit_din(const FabricBitId& bit_id) const;
/* Check if address data is accessible or not*/
bool use_address() const;
bool use_wl_address() const;
public: /* Public Mutators */
/* Reserve config bits */
void reserve_bits(const size_t& num_bits);
/* Add a new configuration bit to the bitstream manager */
FabricBitId add_bit(const ConfigBitId& config_bit_id);
void set_bit_address(const FabricBitId& bit_id,
const std::vector<char>& address,
const bool& tolerant_short_address = false);
void set_bit_bl_address(const FabricBitId& bit_id,
const std::vector<char>& address,
const bool& tolerant_short_address = false);
void set_bit_wl_address(const FabricBitId& bit_id,
const std::vector<char>& address,
const bool& tolerant_short_address = false);
void set_bit_din(const FabricBitId& bit_id,
const char& din);
/* Reserve regions */
void reserve_regions(const size_t& num_regions);
/* Add a new configuration region */
FabricBitRegionId add_region();
void add_bit_to_region(const FabricBitRegionId& region_id,
const FabricBitId& bit_id);
/* Reserve bits by region */
void reverse_region_bits(const FabricBitRegionId& region_id);
/* Reverse bit sequence of the fabric bitstream
* This is required by configuration chain protocol
*/
void reverse();
/* Enable the use of address-related data
* When this is enabled, data allocation will be applied to these data
* and users can access/modify the data
* Otherwise, it will NOT be allocated and accessible.
*
* This function is only applicable before any bits are added
*/
void set_use_address(const bool& enable);
void set_address_length(const size_t& length);
void set_bl_address_length(const size_t& length);
/* Enable the use of WL-address related data
* Same priniciple as the set_use_address()
*/
void set_use_wl_address(const bool& enable);
void set_wl_address_length(const size_t& length);
public: /* Public Validators */
bool valid_bit_id(const FabricBitId& bit_id) const;
bool valid_region_id(const FabricBitRegionId& bit_id) const;
private: /* Internal data */
/* Unique id of a region in the Bitstream */
size_t num_regions_;
std::unordered_set<FabricBitRegionId> invalid_region_ids_;
vtr::vector<FabricBitRegionId, std::vector<FabricBitId>> region_bit_ids_;
/* Unique id of a bit in the Bitstream */
size_t num_bits_;
std::unordered_set<FabricBitId> invalid_bit_ids_;
vtr::vector<FabricBitId, ConfigBitId> config_bit_ids_;
/* Flags to indicate if the addresses and din should be enabled */
bool use_address_;
bool use_wl_address_;
size_t address_length_;
size_t wl_address_length_;
/* Address bits: this is designed for memory decoders
* Here we store the binary format of the address, which can be loaded
* to the configuration protocol directly
*
* We use a 2-element array, as we may have a BL address and a WL address
*
* TODO: use nested vector may cause large memory footprint
* when bitstream size increases
* NEED TO THINK ABOUT A COMPACT MODELING
*/
vtr::vector<FabricBitId, std::vector<char>> bit_addresses_;
vtr::vector<FabricBitId, std::vector<char>> bit_wl_addresses_;
/* Data input (Din) bits: this is designed for memory decoders */
vtr::vector<FabricBitId, char> bit_dins_;
};
} /* end namespace openfpga */
#endif
| 38.776316 | 131 | 0.652076 |
e499f4ce303a0f33e33031764a52905e7dd08ca9 | 32,661 | h | C | trunk/source-opt/tools/include/program_analysis.h | Xilinx/merlin-compiler | f47241ccf26186c60bd8aa6e0390c7dd3edabb3c | [
"Apache-2.0"
] | 23 | 2021-09-04T02:12:02.000Z | 2022-03-21T01:10:53.000Z | trunk/source-opt/tools/include/program_analysis.h | Xilinx/merlin-compiler | f47241ccf26186c60bd8aa6e0390c7dd3edabb3c | [
"Apache-2.0"
] | 2 | 2022-03-04T02:57:29.000Z | 2022-03-25T15:58:18.000Z | trunk/source-opt/tools/include/program_analysis.h | Xilinx/merlin-compiler | f47241ccf26186c60bd8aa6e0390c7dd3edabb3c | [
"Apache-2.0"
] | 12 | 2021-09-22T10:38:47.000Z | 2022-03-28T02:41:56.000Z | // (C) Copyright 2016-2021 Xilinx, Inc.
// All Rights Reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// /////////////////////////////////// /
// Program Analysis Functionalities
// E.g. Linear expression analysis,
// range analysis and dependence analysis
//
// Create date: 2015-07-16 (pengzhang@falcon-computing.com)
// /////////////////////////////////// /
#pragma once
#include <assert.h>
#include <algorithm>
#include <utility>
#include <map>
#include <unordered_map>
#include <string>
#include <tuple>
#include <vector>
#include <list>
#include <memory>
#include "file_parser.h"
#include "rose.h"
#include "codegen.h"
#include "common.h"
using std::shared_ptr;
using std::unique_ptr;
using std::unordered_map;
class CSageCodeGen;
typedef CSageCodeGen CMarsAST_IF;
enum access_type {
NO_ACCESS = 0,
READ = 1,
WRITE = 2,
READWRITE = 3,
};
namespace MarsProgramAnalysis {
class CMarsExpression;
class CMarsRangeExpr;
CMarsRangeExpr get_variable_range(void *sg_node, CMarsAST_IF *ast, void *pos,
void *scope);
CMarsRangeExpr get_variable_range(CMarsAST_IF *ast,
const CMarsExpression &expr);
void clear_variable_range(void *sg_node);
void set_variable_range(void *sg_node, CMarsRangeExpr mr);
// ZP: 20170314 to support range copy for assert variables
void copy_variable_range(void *sg_from, void *sg_to);
bool has_variable_range(CMarsAST_IF *ast, void *sg_expr, void *pos, void *scope,
bool induct_check);
bool has_variable_range(CMarsAST_IF *ast, const CMarsExpression &);
std::unordered_map<void *, CMarsRangeExpr> get_range_analysis(CMarsAST_IF *ast);
// ZP: 20150822: for temporay insersion of the statements
class CTempASTStmt {
public:
CTempASTStmt(void *temp_expr, CMarsAST_IF *ast, void *pos);
~CTempASTStmt();
void reset_defuse();
protected:
void *m_temp_stmt;
CMarsAST_IF *m_ast;
int m_reset_defuse;
};
class CMarsVariable {
public:
CMarsVariable(void *var, CMarsAST_IF *ast, void *pos = nullptr,
void *scope = nullptr);
CMarsVariable(CMarsAST_IF *ast,
CMarsRangeExpr mr); // a dummy variable with a given range
// Can not clear the range because the range is shared by othre objects
// ~CMarsVariable() { if (m_ast->IsBasicBlock(m_var)) clear_range(); }
friend class CMarsExpression;
friend class DUMMY;
public:
std::string unparse() const;
// 0 iterator, 1 local, 2 expression, 3 argument
std::string GetTypeString();
CMarsRangeExpr get_range() const;
// Utility function: used for temporary CMarsExpression/CMarsRangeExpr
// objects
void set_range(CMarsRangeExpr mr);
// Variable ranges
int GetBoundAbs(int64_t *lb, int64_t *ub);
void *get_pointer() const { return m_var; }
CMarsAST_IF *get_ast() const { return m_ast; }
void *get_pos() { return m_pos; }
std::string print_var() const;
std::string print() const;
static bool is_tmp_var(void *var) {
return s_map_tmpvar_name.find(var) != s_map_tmpvar_name.end();
}
static std::string get_tmp_var_name(void *var) {
if (s_map_tmpvar_name.find(var) == s_map_tmpvar_name.end())
return "";
else
return s_map_tmpvar_name[var];
}
bool operator<(const CMarsVariable &var) const;
#if KEEP_UNUSED
int GetType();
void clear_range();
int IsConstantRange();
int64_t GetLBAbs();
int64_t GetUBAbs();
int GetBoundExpr(CMarsExpression *lb, CMarsExpression *ub);
#endif
protected:
void *m_var;
CMarsAST_IF *m_ast;
void *m_pos;
void *m_scope;
static map<void *, std::string> s_map_tmpvar_name;
};
// Initialized_name ->
extern map<void *, CMarsRangeExpr> g_variable_range_cache;
void analyze_all_variable_ranges(CMarsAST_IF *ast);
// map iv vector to order vector
class CMarsInterleaveOrderMap {
public:
// lexigraphic order comparison
protected:
std::vector<int> m_vec_even;
std::vector<void *> m_vec_odd;
};
class DUMMY;
class CMarsExpression {
friend class DUMMY;
public:
CMarsExpression(void *expr, CMarsAST_IF *ast, void *pos = nullptr,
void *scope = nullptr);
CMarsExpression(CMarsAST_IF *ast, int64_t val);
CMarsExpression(CMarsAST_IF *ast, int val);
CMarsExpression(const CMarsExpression &op);
CMarsExpression();
explicit CMarsExpression(CMarsVariable mv);
CMarsExpression(int64_t dummy0, int64_t dummy1, int64_t dummy2,
int64_t dummy3, int64_t dummy4, int finite_flag = 0) {
// dont care for other fields
m_finite = finite_flag;
m_int_type = V_SgTypeLong;
}
protected:
CMarsExpression(void *expr, map<void *, CMarsExpression> coeff,
CMarsAST_IF *ast, int64_t const_i, void *pos, void *scope,
int int_type, int finite_flag);
void print_debug();
public:
void *get_expr_from_coeff(bool final_expr = false) const;
public:
int is_INF() const { return m_finite != 0; }
int is_pINF() const { return (m_finite & 1) == 1; }
int is_nINF() const { return (m_finite & 2) == 2; }
int is_fINF() const { return is_nINF() && is_pINF(); }
public:
std::string unparse() const;
std::string print(int level = 0) const;
std::string print_s() const { return unparse(); }
std::string print_coeff(int level = 0) const;
void *get_pointer() const { return m_expr; }
CMarsAST_IF *get_ast() const { return m_ast; }
void set_ast(CMarsAST_IF *ast) { m_ast = ast; }
void *get_pos() const { return m_pos; }
void set_pos(void *new_pos);
void set_scope(void *new_scope) { m_scope = new_scope; }
void get_vars(std::vector<void *> *vars) const;
std::vector<void *> get_vars() const;
int has_var(void *var) const;
// zero-order
int IsSignned() const { return !m_ast->IsUnsignedType(m_int_type); }
int IsConstant() const;
int IsInteger() const { return m_ast && m_ast->IsIntegerType(m_int_type); }
int64_t GetConstant() const {
switch (m_int_type) {
case V_SgTypeBool:
return static_cast<bool>(m_const);
case V_SgTypeChar:
case V_SgTypeSignedChar:
return static_cast<char>(m_const);
case V_SgTypeUnsignedChar:
return static_cast<unsigned char>(m_const);
case V_SgTypeShort:
case V_SgTypeSignedShort:
return static_cast<int16_t>(m_const);
case V_SgTypeUnsignedShort:
return static_cast<uint16_t>(m_const);
case V_SgTypeInt:
case V_SgTypeSignedInt:
return static_cast<int>(m_const);
case V_SgTypeUnsignedInt:
return static_cast<unsigned int>(m_const);
case V_SgTypeUnsignedLong:
return static_cast<uint64_t>(m_const);
default:
return m_const;
}
}
void SetConstant(int64_t value) { m_const = value; }
int64_t get_const() const { return GetConstant(); }
void set_const(int64_t value) { SetConstant(value); }
int is_zero() const {
return !is_INF() && IsConstant() && 0 == GetConstant();
}
int IsAtomic() const;
int IsAtomicWithNonDeterminedRange() const;
int IsNormal() const; // all the coefficient are constant
// first-order
int IsLinearToIterator() const; //
int GetConstantCoeff(
void *var,
int64_t *value_out) const; // return 0 if not a constant
int64_t GetConstantCoeff(void *var) const;
bool IsLoopInvariant(void *for_loop) const;
bool IsStandardForm(void *for_loop, map<void *, int64_t> *iterators,
map<void *, int64_t> *invariants) const;
// high-order
map<void *, CMarsExpression> *get_coeff() { return &m_coeff; }
CMarsExpression get_coeff(void *var) const;
int64_t get_const_coeff(void *var);
void set_coeff(void *var, const CMarsExpression &coeff) {
m_coeff[var] = coeff;
reduce();
}
std::vector<std::vector<int64_t>> get_coeff_range_simple();
int has_coeff_range_simple() const;
CMarsRangeExpr get_range() const;
bool has_range() const;
int any_var_located_in_scope(void *scope);
int any_var_located_in_scope_except_loop_iterator(void *scope);
int is_movable_to(void *pos);
void operator=(const CMarsExpression &op);
void ParseVarBoundSimple(map<void *, void *> *lb, map<void *, void *> *ub);
friend CMarsExpression operator-(const CMarsExpression &op);
friend CMarsExpression operator+(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsExpression operator-(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsExpression operator+(const CMarsExpression &op1, int64_t op2);
friend CMarsExpression operator-(const CMarsExpression &op1, int64_t op2);
friend CMarsExpression operator*(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsExpression operator*(const CMarsExpression &op1, int64_t op2);
friend CMarsExpression operator/(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsExpression operator/(const CMarsExpression &op1, int64_t op2);
friend CMarsExpression operator%(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsExpression operator%(const CMarsExpression &op1, int64_t op2);
friend CMarsExpression operator<<(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsExpression operator>>(const CMarsExpression &op1,
const CMarsExpression &op2);
friend int divisible(const CMarsExpression &op1, int64_t op2,
bool check_range);
friend int operator==(const CMarsExpression &op1, const CMarsExpression &op2);
friend int operator!=(const CMarsExpression &op1, const CMarsExpression &op2);
friend int operator==(const CMarsExpression &op1, int64_t op2);
friend int operator!=(const CMarsExpression &op1, int64_t op2);
friend int operator>(const CMarsExpression &op1, const CMarsExpression &op2);
friend int operator<(const CMarsExpression &op1, const CMarsExpression &op2);
friend int operator>=(const CMarsExpression &op1, int64_t op2);
int IsNonNegative() const;
int IsNonPositive() const;
int substitute(void *sg_var, const CMarsExpression &sg_expr);
int substitute(void *sg_var, int64_t value);
// bool hasOnlyIteratorsInScope(void *scope);
//
#if KEEP_UNUSED
CMarsRangeExpr get_range_in_scope(void *range_scope);
#endif
friend int operator>=(const CMarsExpression &op1, const CMarsExpression &op2);
friend int operator<=(const CMarsExpression &op1, const CMarsExpression &op2);
friend int operator>(const CMarsExpression &op1, int64_t op2);
friend int operator<(const CMarsExpression &op1, int64_t op2);
friend int operator<=(const CMarsExpression &op1, int64_t op2);
protected:
// m_expr, m_ast -> m_coeff
void analysis();
void reduce(); // remove the zero terms
void induct(); // find substitutions for variables
// youxiang: 2016-09-22, the api can be replaced by operator +
// which can handle infinite expression
// void AddValueconst (const CMarsExpression &&exp);
protected:
CMarsAST_IF *m_ast;
void *m_expr; // The corresponding AST node, nullptr if no correspondence
void *m_pos; // used for scope or position purpose
void *m_scope;
int m_float_pos;
map<void *, CMarsExpression> m_coeff;
int64_t m_const;
int m_int_type;
int m_finite; // the flag for m_finite: 0 for normal, 1 for pos_infinite, 2
// for neg_infinite, 3 for infinite
};
extern const CMarsExpression pos_INF;
extern const CMarsExpression neg_INF;
extern const CMarsExpression full_INF;
class CMarsRangeExpr {
public:
static const int64_t MARS_INT64_MAX = 0x7fffffffffffffffl;
static const int64_t MARS_INT64_MIN = 0x8000000000000000l;
CMarsRangeExpr(const CMarsExpression &lb, const CMarsExpression &ub,
bool is_exact = false);
CMarsRangeExpr(const std::vector<CMarsExpression> &lb,
const std::vector<CMarsExpression> &ub, bool is_exact = false);
explicit CMarsRangeExpr(CMarsAST_IF *ast = nullptr) {
m_is_exact = false;
m_ast = ast;
} // full range
CMarsRangeExpr(CMarsAST_IF *ast,
void *type); // full range according to type
CMarsRangeExpr(int64_t lb, int64_t ub, CMarsAST_IF *ast,
bool is_exact = false);
CMarsRangeExpr(int64_t ublb, CMarsAST_IF *ast, bool is_exact = true);
// union operation
void AppendLB(const CMarsExpression &lb);
void AppendUB(const CMarsExpression &ub);
void set_lb(const CMarsExpression &lb);
void set_ub(const CMarsExpression &ub);
void append_lb(const CMarsExpression &lb) { AppendLB(lb); }
void append_ub(const CMarsExpression &ub) { AppendUB(ub); }
int has_lb() const { return m_lb.size() > 0; }
int has_ub() const { return m_ub.size() > 0; }
int has_bound() const { return has_lb() || has_ub(); }
void update_position(const t_func_call_path &fn_path, void *pos);
void set_pos(void *pos);
// FIXME: to be deprecated, using the set based one
CMarsExpression get_lb(int idx = 0) const;
CMarsExpression get_ub(int idx = 0) const;
std::vector<CMarsExpression> get_lb_set() const { return m_lb; }
std::vector<CMarsExpression> get_ub_set() const { return m_ub; }
int get_simple_bound(CMarsExpression *lb, CMarsExpression *ub) const;
int is_simple_bound() const {
CMarsExpression lb, ub;
return get_simple_bound(&lb, &ub);
}
void get_vars(std::vector<void *> *reduced_all_vars) const;
// conservative
int is_empty() const;
int is_infinite() const { return m_lb.size() <= 0 || m_ub.size() <= 0; }
void set_empty(CMarsAST_IF *ast = nullptr);
int any_var_located_in_scope_except_loop_iterator(void *scope);
int any_var_located_in_scope(void *scope);
int is_movable_to(void *pos);
int has_var(void *var);
int substitute(void *var, void *pos);
int substitute(void *var, const CMarsExpression &lb,
const CMarsExpression &ub, bool is_exact = false);
std::string print_const_bound() const;
std::string print() const;
std::string print_e() const;
bool length_is_greater_or_equal(int64_t len) const;
bool IsConstantLength(int64_t *len) const;
bool is_single_access() const;
bool is_full_access(int64_t size) const;
protected:
std::string print(const std::vector<CMarsExpression> &bound, int is_lb) const;
void reduce();
public:
CMarsAST_IF *get_ast() const;
void set_ast(CMarsAST_IF *ast) { m_ast = ast; }
public:
friend CMarsRangeExpr operator-(const CMarsRangeExpr &op);
friend bool operator==(const CMarsRangeExpr &op1, const CMarsRangeExpr &op2);
friend CMarsRangeExpr operator+(const CMarsRangeExpr &op1,
const CMarsRangeExpr &op2);
friend CMarsRangeExpr operator-(const CMarsRangeExpr &op1,
const CMarsRangeExpr &op2);
friend CMarsRangeExpr operator*(const CMarsRangeExpr &op1, int64_t op2);
friend CMarsRangeExpr operator/(const CMarsRangeExpr &op1,
const CMarsExpression &op2);
friend CMarsRangeExpr min(const CMarsRangeExpr &op1,
const CMarsRangeExpr &op2);
friend CMarsRangeExpr max(const CMarsRangeExpr &op1,
const CMarsRangeExpr &op2);
friend CMarsRangeExpr min(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsRangeExpr max(const CMarsExpression &op1,
const CMarsExpression &op2);
friend CMarsRangeExpr operator+(const CMarsRangeExpr &op1,
const CMarsExpression &op2);
#if KEEP_UNUSED
friend CMarsRangeExpr operator*(const CMarsRangeExpr &op1,
const CMarsExpression &op2);
friend CMarsRangeExpr operator*(const CMarsRangeExpr &op1,
const CMarsRangeExpr &op2);
#endif
int IsNonNegative() const;
int IsNonPositive() const;
int IsConstantBound() const { return is_const_bound(); }
int is_const_bound() const { return is_const_lb() && is_const_ub(); }
int is_const_lb() const;
int is_const_ub() const;
int64_t get_const_lb() const;
int64_t get_const_ub() const;
int IsConstant() const {
return is_const_bound() && get_const_lb() == get_const_ub();
}
CMarsExpression GetConstant();
// These operations are done in a conservative way
CMarsRangeExpr Union(const CMarsRangeExpr &range) const;
CMarsRangeExpr Intersect(const CMarsRangeExpr &range) const;
// return true if *this cover mr
// update the position to create new merged range
int is_cover(const CMarsRangeExpr &mr, CMarsRangeExpr *merged_range) const;
bool is_exact() const { return m_is_exact; }
void set_exact(bool is_exact) { m_is_exact = is_exact; }
void refine_range_in_scope(void *range_scope, void *pos);
void refine_range_in_scope_v2(void *range_scope, void *pos, void *array,
bool is_write, const t_func_call_path &path);
void refine_range_in_scope_v2(void *range_scope, void *pos,
const t_func_call_path &path);
void update_control_flag(void *range_scope, void *pos, void *array,
bool is_write, const t_func_call_path &path);
void
refine_range_get_remain_substitutes(void *range_scope, void *pos,
const t_func_call_path &fn_path,
std::vector<void *> *vec_sub_vars,
std::vector<CMarsExpression> *vec_sub_lbs,
std::vector<CMarsExpression> *vec_sub_ubs,
std::vector<bool> *vec_sub_is_exact);
int refine_range_in_scope_v2_exact(void *range_scope, void *pos,
const t_func_call_path &fn_path);
protected:
#if KEEP_UNUSED
int refine_range_in_scope_one_variable(void *range_scope,
std::vector<void *> *loops_in_scope);
#endif
protected:
// Note: vector is used to represent multiple bounds
// each bound is a requirement to satisfy
// and these conditinos are combined together by "or" operator
std::vector<CMarsExpression> m_lb;
std::vector<CMarsExpression> m_ub;
bool m_is_exact; // used to indicate full access of the range, ZP: 20160205
CMarsAST_IF *m_ast;
};
typedef pair<int, int> CMarsRangeInt;
class CMarsDepDistSet {
public:
CMarsDepDistSet() { set_empty(); }
CMarsDepDistSet(int64_t lb, int64_t ub) {
m_lb = lb;
m_ub = ub;
}
int has_lb() { return m_lb != CMarsRangeExpr::MARS_INT64_MIN; }
int has_ub() { return m_ub != CMarsRangeExpr::MARS_INT64_MAX; }
int64_t get_lb() { return m_lb; }
int64_t get_ub() { return m_ub; }
std::vector<int64_t> get_set();
int is_empty();
void set_empty() {
m_lb = CMarsRangeExpr::MARS_INT64_MAX;
m_ub = CMarsRangeExpr::MARS_INT64_MIN;
}
int64_t size();
std::string print();
protected:
int64_t m_lb;
int64_t m_ub;
};
class CMarsScope {
public:
explicit CMarsScope(void *scope) { m_scope = scope; }
int IsLoop();
int IsFuncbody();
void *get_pointer() { return m_scope; }
protected:
void *m_scope;
};
class CMarsResultFlags {
public:
void set_flag(std::string flag_name, int64_t value) {
m_flags[flag_name] = value;
}
int64_t get_flag(std::string flag_name) { return m_flags[flag_name]; }
protected:
map<std::string, int64_t> m_flags;
};
class CMarsAccess {
public:
CMarsAccess(void *ref, CMarsAST_IF *ast, void *scope, void *pos = nullptr);
void set_scope(void *scope);
void set_pos(void *pos);
// each CMarsRangeExpr for a dimension
std::vector<CMarsRangeExpr> GetRangeExpr();
CMarsRangeExpr GetRangeExpr(int idx);
void *GetRef() const { return m_ref; }
void *GetArray() const { return m_array; }
void *get_ref() const { return m_ref; }
CMarsAST_IF *get_ast() const { return m_ast; }
void *get_array() const { return m_array; }
void *get_scope() const { return m_scope; }
std::vector<CMarsExpression> GetIndexes() const { return m_expr_list; }
CMarsExpression GetIndex(size_t i) const {
assert(i < m_expr_list.size());
return m_expr_list[i];
}
int get_dim() const { return m_expr_list.size(); }
#if KEEP_UNUSED
CMarsRangeExpr GetRangeExpr_old(int idx);
#endif
public:
// Simple Access Type: Single Variable Continous access
// For each dimension: the index is like "i+1" or "i-2"
// 1. each dimension has at most one non-zero variable
// 2. the coefficient of the variable is constant 1 or -1
// 3. each variable exist in at most one dimension
bool is_simple_type_v1();
static bool is_simple_type_v1(const std::vector<CMarsExpression> &indexes);
// for each array dim: std::tuple<var, coeff, const>
std::vector<std::tuple<void *, int64_t, int64_t>>
simple_type_v1_get_dim_to_var();
// for each variable: array_dim(-1 if not found), coeff, const
// is compact: if true, only return the tuples that matches the array index
std::vector<std::tuple<int, int64_t, int64_t>>
simple_type_v1_get_var_to_dim(std::vector<void *> vec_vars,
int is_compact = 0);
public:
std::string print();
std::string print_s();
friend int GetDependence(CMarsAccess access1, CMarsAccess access2,
CMarsDepDistSet *dist_set,
CMarsResultFlags *results_flags);
protected:
void analysis_exp();
void analysis_var();
protected:
void *m_ref;
void *m_array;
CMarsAST_IF *m_ast;
std::vector<CMarsExpression> m_expr_list;
// CMarsScope m_scope;
void *m_scope;
std::vector<void *> m_iv;
std::vector<void *> m_pv;
// TODO(pengzh): not implemented
CMarsInterleaveOrderMap m_order_vector_map;
// for fake access nodes;
void *m_pos;
};
struct RangeInfo {
const void *sgnode;
CMarsRangeExpr range;
size_t acc_size;
t_func_call_path func_path;
RangeInfo(const void *sgnode, const CMarsRangeExpr &range, size_t acc_size)
: sgnode(sgnode), range(range), acc_size(acc_size) {}
explicit RangeInfo(const void *sgnode, const CMarsRangeExpr &range)
: RangeInfo(sgnode, range, 1) {}
};
using range = CMarsRangeExpr;
using list_range = std::list<CMarsRangeExpr>;
using list_rinfo = std::list<RangeInfo>;
using vec_range = std::vector<CMarsRangeExpr>;
using vec_rinfo = std::vector<RangeInfo>;
using vec_list_range = std::vector<list_range>;
using vec_list_rinfo = std::vector<list_rinfo>;
using map2vec_list_range = linked_map<void *, shared_ptr<vec_list_range>>;
using map2vec_list_rinfo = linked_map<void *, shared_ptr<vec_list_rinfo>>;
struct Result {
shared_ptr<vec_list_rinfo> vl_rinfo;
explicit Result(shared_ptr<vec_list_rinfo> vl_rinfo) : vl_rinfo(vl_rinfo) {}
explicit Result(size_t num_dims)
: Result(std::make_shared<vec_list_rinfo>(num_dims)) {}
void extend_1d(shared_ptr<Result> r2, size_t d) {
vl_rinfo->at(d).insert(vl_rinfo->at(d).end(), r2->vl_rinfo->at(d).begin(),
r2->vl_rinfo->at(d).end());
}
void merge(shared_ptr<Result> r2) {
for (size_t d = 0; d < r2->vl_rinfo->size(); ++d) {
extend_1d(r2, d);
}
}
};
struct MyAST {
string type;
const void *sgnode;
// -1:unitialized, 0:non_exact_condition, 1: exact_condition
int true_branch_is_exact_condition;
int false_branch_is_exact_condition;
size_t trip_count;
shared_ptr<Result> result;
vector<shared_ptr<MyAST>> body;
vector<shared_ptr<MyAST>> orelse;
const void *true_body;
const void *false_body;
MyAST(const string &type, void *sgnode, shared_ptr<Result> result)
: type(type), sgnode(sgnode), true_branch_is_exact_condition(-1),
false_branch_is_exact_condition(-1), trip_count(1), result(result),
true_body(nullptr), false_body(nullptr) {}
MyAST(const string &type, void *sgnode) : MyAST(type, sgnode, nullptr) {}
};
class ArrayRangeAnalysis {
private:
using DFS_cache =
std::map<std::pair<void *, // ptr to SgFunctionDeclaration
void *>, // ptr to SgInitializedName
std::pair<shared_ptr<Result>, // for read access
shared_ptr<Result>>>; // for write access
DFS_cache m_cache;
CMarsAST_IF *m_ast;
// must keep
range m_flatten_range_w;
range m_flatten_range_r;
vec_range m_range_w;
vec_range m_range_r;
int64_t m_access_size;
bool m_eval_access_size;
bool m_check_access_bound;
void *get_interesting_upper(void *node, void *root);
bool child_of(void *subnode, void *node);
bool child_of_if_true_body(void *node, void *ifstmt);
shared_ptr<MyAST> create_tree(void *range_scope,
const map2vec_list_rinfo &range_for);
shared_ptr<Result> postorder(shared_ptr<MyAST> tree, const void *range_scope,
int dim_size);
void try_merge(shared_ptr<vec_list_rinfo> ranges, int dim);
range try_merge(shared_ptr<list_range> ranges);
void union_group_range_exact(shared_ptr<vec_list_rinfo> rinfos,
const void *range_scope, const void *upper,
int dim, size_t upper_trip_count = 1);
range union_group_range(shared_ptr<vec_list_rinfo> rinfos,
const void *range_scope, int dim);
shared_ptr<Result> Union(const map2vec_list_rinfo &range_for,
void *range_scope, int dim_size);
std::pair<std::shared_ptr<Result>, std::shared_ptr<Result>>
DFS_analyze(void *range_scope, void *array, void *ref_scope);
void analyze(void *array, void *range_scope, void *ref_scope);
// base range analysis
bool equal_range(const list_rinfo &one_rinfos,
const list_rinfo &other_rinfos);
void analyze_ref(void *curr_ref, void *range_scope, void *ref_scope, int dim,
bool all_dimension_size_known, size_t total_flatten_size,
int data_unit_size, const vector<size_t> &sg_sizes,
shared_ptr<vec_list_rinfo> r_range,
shared_ptr<vec_list_rinfo> w_range, void **new_scope,
void **new_range_scope, void **new_array,
void **new_func_call, int *new_pointer_dim);
void propagate_range(void *curr_ref, void *range_scope,
const vec_list_rinfo &r1, const vec_list_rinfo &w1,
int dim, int new_pointer_dim,
shared_ptr<vec_list_rinfo> w_range,
shared_ptr<vec_list_rinfo> r_range);
void get_range_with_offset(const list_rinfo &old_range,
const CMarsRangeExpr &offset,
list_rinfo *new_range);
void substitute_parameter_atom_in_range(
void *array, shared_ptr<vec_list_rinfo> read_range,
shared_ptr<vec_list_rinfo> write_range, void *func_decl, void *func_call,
void *range_scope);
void check_exact_flag_for_loop(const void *loop, const void *range_scope,
shared_ptr<vec_list_rinfo> range_group);
void set_non_exact_flag(shared_ptr<vec_list_rinfo> range_group, int dim);
void get_array_dimension_size(void *array, size_t *dim, int *data_unit_size,
int *dim_fake, bool *all_dimension_size_known,
size_t *total_flatten_size,
vector<size_t> *sg_sizes);
bool is_empty_list_range(const list_rinfo &ranges);
void intersect_with_access_range_info(void *array, void *ref_scope,
void *range_scope);
void use_access_range_info(void *array, void *ref_scope, void *range_scope,
shared_ptr<vec_list_rinfo> read_ranges,
shared_ptr<vec_list_rinfo> write_ranges);
bool check_local_or_infinite_range(shared_ptr<vec_list_rinfo> ranges, int dim,
void *range_scope);
size_t merge_access_size(size_t one_access_size, size_t other_access_size);
public:
ArrayRangeAnalysis(void *array, CMarsAST_IF *ast, void *ref_scope,
void *range_scope, bool eval_access_size,
bool check_access_bound);
vec_range GetRangeExprWrite() { return m_range_w; }
vec_range GetRangeExprRead() { return m_range_r; }
range GetFlattenRangeExprWrite() { return m_flatten_range_w; }
range GetFlattenRangeExprRead() { return m_flatten_range_r; }
int has_read();
int has_write();
std::string print();
std::string print_s();
int64_t get_access_size() { return m_access_size; }
};
class CMarsArrayRangeInScope {
public:
CMarsArrayRangeInScope(void *array, CMarsAST_IF *ast,
const std::list<t_func_call_path> &vec_call_path,
void *ref_scope, void *range_scope,
bool eval_access_size, bool check_access_bound);
std::vector<CMarsRangeExpr> GetRangeExprWrite() { return m_range_w; }
std::vector<CMarsRangeExpr> GetRangeExprRead() { return m_range_r; }
CMarsRangeExpr GetFlattenRangeExprWrite() { return m_flatten_range_w; }
CMarsRangeExpr GetFlattenRangeExprRead() { return m_flatten_range_r; }
int has_read();
int has_write();
std::string print();
std::string print_s();
int64_t get_access_size() {
assert(m_eval_access_size);
return m_access_size;
}
protected:
void *m_array;
CMarsAST_IF *m_ast;
void *m_scope;
CMarsRangeExpr m_flatten_range_w;
CMarsRangeExpr m_flatten_range_r;
std::vector<CMarsRangeExpr> m_range_w;
std::vector<CMarsRangeExpr> m_range_r;
int64_t m_access_size;
bool m_eval_access_size;
bool m_check_access_bound;
};
void GetAccessRangeInScope(void *array, void *ref_scope, void *range_scope,
CMarsAST_IF *ast,
std::vector<CMarsRangeExpr> *r_range,
std::vector<CMarsRangeExpr> *w_range,
CMarsRangeExpr *r_flatten_range,
CMarsRangeExpr *w_flatten_range);
// ///////////////////////////////////// /
int CheckAccessSeparabilityInScope(CMarsAST_IF *ast, void *array,
void *ref_scope, void *boundary_scope,
CMerlinMessage *msg);
void *CopyAccessInScope(CMarsAST_IF *ast, void *array, void *ref_scope,
void *boundary_scope, int *is_write,
map<void *, void *> *map_spref2snref = nullptr,
std::vector<void *> *vec_params = nullptr);
// ///////////////////////////////////// /
int GetDependence(CMarsAccess access1, CMarsAccess access2,
CMarsDepDistSet *dist_set, CMarsResultFlags *results_flags);
std::vector<CMarsRangeExpr>
RangeUnioninVector(const std::vector<CMarsRangeExpr> &vec1,
const std::vector<CMarsRangeExpr> &vec2);
int is_exact_condition(CMarsAST_IF *ast, void *cond_stmt, void *scope,
bool true_branch);
void *GetAccessRangeFromIntrinsic(void *array, void *ref_scope,
void *range_scope, CMarsAST_IF *ast,
std::vector<CMarsRangeExpr> *range,
bool *valid);
class DUMMY {
std::vector<int64_t> v;
public:
explicit DUMMY(const CMarsExpression *exp);
explicit DUMMY(const CMarsVariable *var);
DUMMY(CMarsAST_IF *ast, void *expr, void *pos, void *scope);
bool operator<(const DUMMY &var) const;
std::string toString();
};
extern map<DUMMY, CMarsRangeExpr> cache_get_range_exp;
extern map<DUMMY, std::tuple<bool, int64_t>> cache_consts;
extern map<DUMMY, bool> cache_IsMatchedFuncAndCall;
} // namespace MarsProgramAnalysis
| 35.195043 | 80 | 0.676127 |
0211c97fc506dc35523e7465760cc637efba8fc7 | 855 | h | C | deprecated/imageutilities/src/iuio/pgrsource.h | mwerlberger/imp | 2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85 | [
"MIT"
] | 8 | 2015-10-24T18:31:58.000Z | 2019-10-16T03:27:27.000Z | deprecated/imageutilities/src/iuio/pgrsource.h | henrywen2011/imp | 2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85 | [
"MIT"
] | 7 | 2015-06-22T09:36:32.000Z | 2015-08-20T06:56:10.000Z | deprecated/imageutilities/src/iuio/pgrsource.h | henrywen2011/imp | 2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85 | [
"MIT"
] | 3 | 2015-05-13T14:46:48.000Z | 2017-01-11T09:20:03.000Z | #ifndef PGRSOURCE_H
#define PGRSOURCE_H
#include "videosource.h"
class PGRCameraData;
namespace FlyCapture2 {
class Error;
}
/** A videosource to read from Pointgrey Firewire cameras */
class PGRSource : public VideoSource
{
Q_OBJECT
public:
/** initialize camera camId */
PGRSource(unsigned int camId=0);
virtual ~PGRSource();
/** get image from camera */
cv::Mat getImage();
/** get image width */
unsigned int getWidth() { return width_; }
/** get image height */
unsigned int getHeight() { return height_; }
/** get current frame number */
unsigned int getCurrentFrameNr() { return frameNr_; }
private:
bool init(unsigned int camId);
bool connectToCamera(unsigned int camId);
bool startCapture();
void grab();
void printError(FlyCapture2::Error* error);
PGRCameraData* data_;
};
#endif // PGRSOURCE_H
| 19 | 60 | 0.700585 |
cbec23d75885e0f55e768fe63e91a1753d799074 | 2,148 | h | C | OnlineDB/EcalCondDB/interface/ODSRPConfig.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | OnlineDB/EcalCondDB/interface/ODSRPConfig.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | OnlineDB/EcalCondDB/interface/ODSRPConfig.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef ODSRPCONFIG_H
#define ODSRPCONFIG_H
#include <map>
#include <stdexcept>
#include "OnlineDB/Oracle/interface/Oracle.h"
#include "OnlineDB/EcalCondDB/interface/IODConfig.h"
#define USE_NORM 1
#define USE_CHUN 2
#define USE_BUFF 3
/* Buffer Size */
#define BUFSIZE 200;
class ODSRPConfig : public IODConfig {
public:
friend class EcalCondDBInterface;
ODSRPConfig();
~ODSRPConfig();
// User data methods
inline std::string getTable() { return "ECAL_SRP_CONFIGURATION"; }
inline void setId(int id) { m_ID = id; }
inline int getId() const { return m_ID; }
inline void setDebugMode(int x) { m_debug = x; }
inline int getDebugMode() const { return m_debug; }
inline void setDummyMode(int x) { m_dummy= x; }
inline int getDummyMode() const { return m_dummy; }
inline void setPatternDirectory(std::string x) { m_patdir = x; }
inline std::string getPatternDirectory() const { return m_patdir; }
inline void setAutomaticMasks(int x) { m_auto = x; }
inline int getAutomaticMasks() const { return m_auto; }
inline void setAutomaticSrpSelect(int x) { m_auto_srp = x; }
inline int getAutomaticSrpSelect() const { return m_auto_srp; }
inline void setSRP0BunchAdjustPosition(int x) { m_bnch = x; }
inline int getSRP0BunchAdjustPosition() const { return m_bnch; }
inline void setConfigFile(std::string x) { m_file = x; }
inline std::string getConfigFile() const { return m_file; }
inline void setSRPClob(unsigned char* x) { m_srp_clob = x; }
inline unsigned char* getSRPClob() const { return m_srp_clob; }
inline unsigned int getSRPClobSize() const { return m_size; }
void setParameters(const std::map<std::string,std::string>& my_keys_map);
private:
void prepareWrite() noexcept(false);
void writeDB() noexcept(false);
void clear();
void fetchData(ODSRPConfig * result) noexcept(false);
int fetchID() noexcept(false);
int fetchNextId() noexcept(false);
// User data
int m_ID;
unsigned char* m_srp_clob;
int m_debug;
int m_dummy;
std::string m_file;
std::string m_patdir;
int m_auto, m_auto_srp;
int m_bnch;
unsigned int m_size;
};
#endif
| 26.85 | 75 | 0.714153 |
8b1eef7f48e264f6fd7b7ef0cd9efb35c243301c | 5,172 | h | C | install/TexGen/Core/VoxelMesh.h | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 14 | 2021-06-17T17:17:07.000Z | 2022-03-26T05:20:20.000Z | install/TexGen/Core/VoxelMesh.h | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 6 | 2021-11-01T20:37:39.000Z | 2022-03-11T17:18:53.000Z | install/TexGen/Core/VoxelMesh.h | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 8 | 2021-07-20T09:24:23.000Z | 2022-02-26T16:32:00.000Z | /*=============================================================================
TexGen: Geometric textile modeller.
Copyright (C) 2010 Louise Brown
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
=============================================================================*/
#pragma once
#include "Mesh.h"
#include "Materials.h"
namespace TexGen
{
using namespace std;
class CTextile;
class CPeriodicBoundaries;
class CMaterials;
/// Class used to generate voxel mesh for output to ABAQUS
class CLASS_DECLSPEC CVoxelMesh
{
public:
CVoxelMesh(string Type = "CPeriodicBoundaries");
virtual ~CVoxelMesh(void);
/** Save the voxel mesh as an Abaqus input file with periodic boundary conditions
\param bOutputMatrix True to output the matrix area of the mesh
\param bOutputYarns True to output the yarn areas
\param iBoundaryConditions as in enum PERIODIC_BOUNDARY_CONDITIONS
\param iElementType 0 for C3D8R, 1 for C3D8
*/
virtual void SaveVoxelMesh(CTextile &Textile, string OutputFilename, int XVoxNum, int YVoxNum, int ZVoxNum, bool bOutputMatrix, bool bOutputYarns, int iBoundaryConditions, int iElementType = 0, int FileType = INP_EXPORT);
/// Add a row of element information
void AddElementInfo(vector<POINT_INFO> &RowInfo);
/// Outputs yarn orientations and element sets to .ori and .eld files
void OutputOrientationsAndElementSets( string Filename );
CTextileMaterials& GetMaterials() { return m_Materials; }
protected:
CTextileMaterials m_Materials;
private:
CVoxelMesh( const CVoxelMesh& CopyMe ); // Shouldn't need to copy - implement if need arises
CVoxelMesh& operator=( const CVoxelMesh& CopyMe );
protected:
/// Calculate voxel size based on number of voxels on each axis and domain size
virtual bool CalculateVoxelSizes(CTextile &Textile) = 0;
/// Add nodes for whole domain
//void AddNodes();
/// Add hex elements
//void AddElements();
/// Save voxel mesh in VTK format without boundary conditions
void SaveVoxelMeshToVTK(string Filename, CTextile &Textile, bool bOutputYarns);
/// Save voxel mesh in Abaqus .inp format with periodic boundary conditions
/// bOutputMatrix and bOutput yarn specify which of these are saved to the Abaqus file
void SaveToAbaqus( string Filename, CTextile &Textile, bool bOutputMatrix, bool bOutputYarn, int iBoundaryConditions, int iElementType );
/// Save voxel mesh in SCIRun .pts and .hex format without boundary conditions
void SaveToSCIRun( string Filename, CTextile &Textile );
/// Outputs nodes to .inp file and gets element information
virtual void OutputNodes(ostream &Output, CTextile &Textile, int Filetype = INP_EXPORT) = 0;
/// Output hex elements to .inp file
/**
\ return Maximum element index
*/
virtual int OutputHexElements(ostream &Output, bool bOutputMatrix, bool bOutputYarn, int Filetype = INP_EXPORT );
/// Outputs yarn orientations and element sets to .ori and .eld files
void OutputOrientationsAndElementSets( string Filename, ostream &Output );
/// Outputs all elements when only outputting matrix
void OutputMatrixElementSet( string Filename, ostream &Output, int iNumHexElements, bool bMatrixOnly );
/// Output node set containing all nodes
void OutputAllNodesSet( string Filename, ostream &Output );
/// Output periodic boundary conditions to .inp file
virtual void OutputPeriodicBoundaries(ostream &Output, CTextile& Textile, int iBoundaryConditions, bool bMatrixOnly);
//void OutputSets( ostream& Output, vector<int>& GroupA, vector<int>& GroupB, int i, int iDummyNodeNum );
/// Find intersections of yarn surfaces with grid of lines from node points in each axis
//void GetYarnGridIntersections( CTextile &Textile );
/// Calculate intersections for one orientation of grid lines
//void CalculateIntersections( CMesh &Mesh, vector<pair<XYZ,XYZ> > &Lines, int YarnIndex, vector<vector<pair<int, double> > > &Intersections);
//template <typename T>
/// Output data with iMaxPerLine elements per line
//static void WriteValues(ostream &Output, T &Values, int iMaxPerLine);
/// Mesh stored when saving to VTK
CMesh m_Mesh;
/// Number of voxels along x,y and z axes
int m_XVoxels;
int m_YVoxels;
int m_ZVoxels;
/// Domain limits
pair<XYZ, XYZ> m_DomainAABB;
/// Element information as calculated by GetPointInformation
vector<POINT_INFO> m_ElementsInfo;
//CObjectContainer<CPeriodicBoundaries> m_PeriodicBoundaries;
CPeriodicBoundaries* m_PeriodicBoundaries;
};
}; // namespace TexGen
| 42.393443 | 223 | 0.738206 |
5389398a96ba8eb61366e1466967ac5b59133012 | 3,144 | h | C | macOS/10.13/Foundation.framework/NSRTFD.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 30 | 2016-10-09T20:13:00.000Z | 2022-01-24T04:14:57.000Z | macOS/10.13/Foundation.framework/NSRTFD.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | null | null | null | macOS/10.13/Foundation.framework/NSRTFD.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 7 | 2017-08-29T14:41:25.000Z | 2022-01-19T17:14:54.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation
*/
@interface NSRTFD : NSMutableDictionary {
NSMutableDictionary * dict;
}
+ (void)initialize;
- (id)_getDocInfoForKey:(id)arg1;
- (id)addCommon:(id)arg1 docInfo:(id)arg2 value:(id)arg3 zone:(struct _NSZone { }*)arg4;
- (id)addData:(id)arg1 name:(id)arg2;
- (id)addFile:(id)arg1;
- (id)addLink:(id)arg1;
- (id)copy;
- (id)copy:(id)arg1 into:(id)arg2;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (unsigned long long)count;
- (id)createRandomKey:(id)arg1;
- (id)createUniqueKey:(id)arg1;
- (id)dataForFile:(id)arg1;
- (id)dataRepresentation;
- (void)dealloc;
- (id)getDocument:(id)arg1 docInfo:(id)arg2;
- (id)init;
- (unsigned long long)initFromDocument:(id)arg1;
- (unsigned long long)initUnixFile:(id)arg1;
- (id)initWithCapacity:(unsigned long long)arg1;
- (id)initWithContentsOfFile:(id)arg1;
- (id)initWithDataRepresentation:(id)arg1;
- (id)initWithDictionary:(id)arg1;
- (id)initWithDictionary:(id)arg1 copyItems:(BOOL)arg2;
- (id)initWithObjects:(const id*)arg1 forKeys:(const id*)arg2 count:(unsigned long long)arg3;
- (unsigned long long)internalSaveTo:(id)arg1 removeBackup:(BOOL)arg2 errorHandler:(id)arg3;
- (unsigned long long)internalSaveTo:(id)arg1 removeBackup:(BOOL)arg2 errorHandler:(id)arg3 temp:(id)arg4 backup:(id)arg5;
- (unsigned long long)internalWritePath:(id)arg1 errorHandler:(id)arg2 remapContents:(BOOL)arg3 hardLinkPath:(id)arg4;
- (BOOL)isPackage;
- (id)keyEnumerator;
- (id)nameFromPath:(id)arg1 extra:(id)arg2;
- (id)objectForKey:(id)arg1;
- (id)removeFile:(id)arg1;
- (void)removeObjectForKey:(id)arg1;
- (id)replaceFile:(id)arg1 data:(id)arg2;
- (id)replaceFile:(id)arg1 path:(id)arg2;
- (unsigned long long)saveToDocument:(id)arg1 removeBackup:(BOOL)arg2 errorHandler:(id)arg3;
- (void)setObject:(id)arg1 forKey:(id)arg2;
- (id)setPackage:(BOOL)arg1;
- (id)tmpNameFromPath:(id)arg1;
- (id)tmpNameFromPath:(id)arg1 extension:(id)arg2;
- (id)uniqueKey:(id)arg1;
- (long long)validatePath:(id)arg1 ignore:(id)arg2;
- (unsigned long long)writePath:(id)arg1 docInfo:(id)arg2 errorHandler:(id)arg3 remapContents:(BOOL)arg4 hardLinkPath:(id)arg5;
- (unsigned long long)writePath:(id)arg1 docInfo:(id)arg2 errorHandler:(id)arg3 remapContents:(BOOL)arg4 markBusy:(BOOL)arg5 hardLinkPath:(id)arg6;
// NSRTFD (NSInternalUseOnly)
- (unsigned long long)addDirNamed:(id)arg1 lazy:(BOOL)arg2;
- (unsigned long long)addFileNamed:(id)arg1 fileAttributes:(id)arg2;
- (id)getDirInfo:(BOOL)arg1;
- (unsigned long long)insertItem:(id)arg1 path:(id)arg2 dirInfo:(id)arg3 zone:(struct _NSZone { }*)arg4 plist:(id)arg5;
- (unsigned long long)realAddDirNamed:(id)arg1;
// NSRTFD (NSNewTextSupport)
- (BOOL)_isLink:(id)arg1;
// NSRTFD (NSSerializationSupport)
- (id)freeSerialized:(void*)arg1 length:(unsigned long long)arg2;
- (id)initFromSerialized:(id)arg1;
- (id)initWithPasteboardDataRepresentation:(id)arg1;
- (id)pasteboardDataRepresentation;
- (id)serialize:(void**)arg1 length:(unsigned long long*)arg2;
// NSRTFD (NSTextDocumentPboard)
- (id)initFromElement:(id)arg1 ofDocument:(id)arg2;
@end
| 38.814815 | 147 | 0.743003 |
85d7cb173b44aa428d17a11ec0285ceabf0ef1fe | 1,423 | h | C | Ricardo_OS/Ricardo_OS/src/Pyros/pyroHandler.h | icl-rocketry/Avionics | 4fadbccb1cafe4be80c76e15a2546bbb8414398b | [
"MIT"
] | 8 | 2020-01-28T18:35:21.000Z | 2021-11-20T13:34:25.000Z | Ricardo_OS/Ricardo_OS/src/Pyros/pyroHandler.h | icl-rocketry/Avionics | 4fadbccb1cafe4be80c76e15a2546bbb8414398b | [
"MIT"
] | 2 | 2022-02-15T08:29:49.000Z | 2022-02-28T02:13:06.000Z | Ricardo_OS/Ricardo_OS/src/Pyros/pyroHandler.h | icl-rocketry/Avionics | 4fadbccb1cafe4be80c76e15a2546bbb8414398b | [
"MIT"
] | 1 | 2020-12-06T05:20:51.000Z | 2020-12-06T05:20:51.000Z | #ifndef PYROHANDLER_H
#define PYROHANDLER_H
#include "pyro.h"
#include "rnp_networkmanager.h"
#include "rnp_packet.h"
#include "Storage/systemstatus.h"
#include "Storage/logController.h"
#include <vector>
#include <memory>
#include <ArduinoJson.h>
#include <unordered_map>
/****
* TODO:
* Add deployment lockout using a system wide flag
* disable deploment when debug is entered
* add deployment full test option where all deploymet channels are tested
* add servo specialization as deployers can either by pyro or servo based
*
****/
class PyroHandler{
public:
PyroHandler(RnpNetworkManager& rnpnetman,SystemStatus& systemstatus,LogController& logcontroller);
void setup(JsonArray pyroConfig); // manages construciton of pyro objects
void update(); // update pyro status
Pyro* get(int pyroID);
static constexpr uint8_t PyroHandlerServiceID = static_cast<uint8_t>(DEFAULT_SERVICES::PYRO);
private:
RnpNetworkManager& _rnpnetman;
SystemStatus& _systemstatus;
LogController& _logcontroller;
std::vector<std::unique_ptr<Pyro> > _pyroList; // vector containing pointers to all pyro objects
/**
* @brief network callback used when registering the pyro serivce
*
* @param packet
*/
void networkCallback(std::unique_ptr<RnpPacketSerialized> packet);
};
#endif | 25.872727 | 106 | 0.696416 |
c4444b9a9eb58e90cba2861912e025450a728928 | 710 | h | C | PSA_fmindex.h | Guuhua/CLUSTAR | c15d630a08cd19afcb18b62562dd814924058285 | [
"MIT"
] | null | null | null | PSA_fmindex.h | Guuhua/CLUSTAR | c15d630a08cd19afcb18b62562dd814924058285 | [
"MIT"
] | null | null | null | PSA_fmindex.h | Guuhua/CLUSTAR | c15d630a08cd19afcb18b62562dd814924058285 | [
"MIT"
] | null | null | null | #include "FMindex.h"
#include "PSA_kband.h"
#define DIM 3
int cmp2(const void *a, const void *b);
FM *FMbulid(char *);
int *selectprefixs(FM *fmA, char *p, int length);
int (*findALLCommonStrings(FM *fmA, char *B, int *numCS))[DIM];
int MultiToOne(int *idxs, int length, float offset);
int (*dpSelect(int (*results)[DIM], int *num))[DIM];
int (*trace(int (*results)[DIM], int *p, int *num))[DIM];
int getMAXidx(int *p, int num);
int (*eval(int (*results)[DIM], int *num, int lenA, int lenB))[DIM];
int (*selectCommonStrings(FM *fmA, char *B, int *num))[DIM];
char **chipAlign(char *A, char *B, int sA, int tA, int sB, int tB);
char **AlignStr(FM *fmA, char *A, char *B); | 25.357143 | 69 | 0.625352 |
c45cdef1a3333cad0263f997b31bb209aa053d12 | 526 | c | C | src/main.c | zear/TripleTrapled | a8b7fecbab436127bea32728d9fb13dd53e00f12 | [
"MIT"
] | 1 | 2015-02-04T02:51:16.000Z | 2015-02-04T02:51:16.000Z | src/main.c | zear/TripleTrapled | a8b7fecbab436127bea32728d9fb13dd53e00f12 | [
"MIT"
] | null | null | null | src/main.c | zear/TripleTrapled | a8b7fecbab436127bea32728d9fb13dd53e00f12 | [
"MIT"
] | null | null | null | #include "main.h"
#include <stdlib.h>
#include <time.h>
#include "fileio.h"
#include "input.h"
#include "states.h"
#include "video.h"
int quit;
int init()
{
getConfigDir();
getConfig();
if(initSDL())
{
return -1;
}
return 0;
}
void deinit()
{
if(configDir)
{
free(configDir);
}
}
int main(int argc, char *argv[])
{
quit = 0;
if(init())
{
quit = 1;
}
srand(time(NULL));
while(!quit)
{
if(!frameLimiter())
{
input();
logic();
draw();
}
}
storeConfig();
deinit();
return 0;
}
| 8.915254 | 32 | 0.562738 |
3fc37f3e053961f32cdb4c92cb3f6b2267b08e58 | 2,258 | h | C | loan.h | mircomannino/Book-on-Loan-Administration | 6d6e65847aae825086b119576d94bd315c8204d7 | [
"MIT"
] | 1 | 2019-09-27T18:42:05.000Z | 2019-09-27T18:42:05.000Z | loan.h | mircomannino/Book-on-Loan-Administration | 6d6e65847aae825086b119576d94bd315c8204d7 | [
"MIT"
] | null | null | null | loan.h | mircomannino/Book-on-Loan-Administration | 6d6e65847aae825086b119576d94bd315c8204d7 | [
"MIT"
] | null | null | null | #ifndef __LOAN_H__
#define __LOAN_H__
#include "date.h"
#include <iostream>
#include <sstream>
#include <iomanip>
class Loan {
private:
std::string title;
std::string person;
Date start;
Date end;
public:
/* Constructor */
Loan(const std::string& title, const std::string& person, Date start, Date end) {
this->title = title;
this->person = person;
this->start = start;
this->end = end;
}
Loan() {
this->title = "";
this->person = "";
this->start = "--/--/--";
this->end = "--/--/--";
}
/* Setters */
void setTitle(const std::string& title) { this->title = title; }
void setPerson(const std::string& person) { this->person = person; }
void setStart(const Date& start) { this->start = start; }
void setEnd(const Date& end) {this->end = end; }
/* Getters */
std::string getTitle() const { return this->title; }
std::string getPerson() const { return this->person; }
Date getStart() const { return this->start; }
Date getEnd() const { return this->end; }
/* Read from string */
void readFromString(const std::string& line) {
std::stringstream is(line);
is >> this->title;
is >> this->person;
is >> this->start;
is >> this->end;
}
};
/* Operator ">>" overloading */
std::istream& operator>>(std::istream& in, Loan& loan) {
std::string loanString;
std::string word;
for(int i = 0; i < 4; i++) {
in >> word;
loanString += word + " ";
}
std::istringstream loanStringStream(loanString);
std::string titleInput;
std::string personInput;
Date startInput;
Date endInput;
loanStringStream >> titleInput;
loanStringStream >> personInput;
loanStringStream >> startInput;
loanStringStream >> endInput;
loan.setTitle(titleInput);
loan.setPerson(personInput);
loan.setStart(startInput);
loan.setEnd(endInput);
return in;
}
/* Operator "<<" overloading */
std::ostream& operator<<(std::ostream& out, const Loan& loan) {
out << loan.getTitle() << "\t\t";
out << loan.getPerson() << "\t\t";
out << loan.getStart() << "\t\t";
out << loan.getEnd();
return out;
}
#endif
| 26.255814 | 85 | 0.581488 |
3feb12d5c6f067a48f631257ba88faaeb800723e | 418 | h | C | FAITHMainUIDemo/FAITHMainUIDemo/Classes/Other/Catagroy/NSDate(Extension).h | faith939339094/FAITHMainUIDemo | f2dcfa8f56168ab9d291ee4f8b189025475cb836 | [
"MIT"
] | null | null | null | FAITHMainUIDemo/FAITHMainUIDemo/Classes/Other/Catagroy/NSDate(Extension).h | faith939339094/FAITHMainUIDemo | f2dcfa8f56168ab9d291ee4f8b189025475cb836 | [
"MIT"
] | null | null | null | FAITHMainUIDemo/FAITHMainUIDemo/Classes/Other/Catagroy/NSDate(Extension).h | faith939339094/FAITHMainUIDemo | f2dcfa8f56168ab9d291ee4f8b189025475cb836 | [
"MIT"
] | null | null | null | //
// NSDate(Extension)
// FAITH
//
// Created by apple on 16-5-9.
// Copyright (c) 2014年 FAITH. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDate(Extension)
/**
* 是否为今天
*/
- (BOOL)isToday;
/**
* 是否为昨天
*/
- (BOOL)isYesterday;
/**
* 是否为今年
*/
- (BOOL)isThisYear;
/**
* 返回一个只有年月日的时间
*/
- (NSDate *)dateWithYMD;
/**
* 获得与当前时间的差距
*/
- (NSDateComponents *)deltaWithNow;
@end
| 11.942857 | 51 | 0.605263 |
273ab54c5fe2dc3dd167f4e322e3a24618a85295 | 8,512 | c | C | debian_specs/nginx/modules/nchan/src/subscribers/internal.c | xluffy-fork/passenger_apt_automation | 37dd0198c793d92277aacc9935cf0a4bdb455d9b | [
"MIT"
] | 9 | 2015-03-06T01:58:51.000Z | 2020-03-04T08:06:53.000Z | debian_specs/nginx/modules/nchan/src/subscribers/internal.c | xluffy-fork/passenger_apt_automation | 37dd0198c793d92277aacc9935cf0a4bdb455d9b | [
"MIT"
] | 33 | 2015-03-13T13:14:11.000Z | 2022-02-26T03:31:51.000Z | debian_specs/nginx/modules/nchan/src/subscribers/internal.c | xluffy-fork/passenger_apt_automation | 37dd0198c793d92277aacc9935cf0a4bdb455d9b | [
"MIT"
] | 12 | 2015-03-02T09:16:00.000Z | 2022-01-19T02:56:12.000Z | #include <nchan_module.h>
#include <subscribers/common.h>
#include "internal.h"
#include <assert.h>
//#define DEBUG_LEVEL NGX_LOG_WARN
#define DEBUG_LEVEL NGX_LOG_DEBUG
#define DBG(fmt, arg...) ngx_log_error(DEBUG_LEVEL, ngx_cycle->log, 0, "SUB:INTERNAL:" fmt, ##arg)
#define ERR(fmt, arg...) ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "SUB:INTERNAL:" fmt, ##arg)
static const subscriber_t new_internal_sub;
static ngx_int_t empty_callback(ngx_int_t code, void *ptr, void *d) {
return NGX_OK;
}
ngx_int_t internal_subscriber_set_enqueue_handler(subscriber_t *sub, callback_pt handler) {
((internal_subscriber_t *)sub)->enqueue = handler;
return NGX_OK;
}
ngx_int_t internal_subscriber_set_dequeue_handler(subscriber_t *sub, callback_pt handler) {
((internal_subscriber_t *)sub)->dequeue = handler;
return NGX_OK;
}
ngx_int_t internal_subscriber_set_notify_handler(subscriber_t *sub, callback_pt handler) {
((internal_subscriber_t *)sub)->notify = handler;
return NGX_OK;
}
ngx_int_t internal_subscriber_set_respond_message_handler(subscriber_t *sub, callback_pt handler) {
((internal_subscriber_t *)sub)->respond_message = handler;
return NGX_OK;
}
ngx_int_t internal_subscriber_set_respond_status_handler(subscriber_t *sub, callback_pt handler) {
((internal_subscriber_t *)sub)->respond_status = handler;
return NGX_OK;
}
ngx_int_t internal_subscriber_set_destroy_handler(subscriber_t *sub, callback_pt handler) {
((internal_subscriber_t *)sub)->destroy = handler;
return NGX_OK;
}
static ngx_str_t subscriber_name = ngx_string("internal");
subscriber_t *internal_subscriber_create(ngx_str_t *name, nchan_loc_conf_t *cf, size_t pd_size, void **pd) {
internal_subscriber_t *fsub;
if((fsub = ngx_alloc(sizeof(*fsub) + pd_size, ngx_cycle->log)) == NULL) {
ERR("Unable to allocate");
return NULL;
}
if(pd) {
*pd = pd_size > 0 ? &fsub[1] : NULL;
}
nchan_subscriber_init(&fsub->sub, &new_internal_sub, NULL, NULL);
nchan_subscriber_init_timeout_timer(&fsub->sub, &fsub->timeout_ev);
fsub->sub.cf = cf;
fsub->sub.name= (name == NULL ? &subscriber_name : name);
fsub->enqueue = empty_callback;
fsub->dequeue = empty_callback;
fsub->respond_message = empty_callback;
fsub->respond_status = empty_callback;
fsub->notify = empty_callback;
fsub->destroy = empty_callback;
DBG("%p create %V with privdata %p", fsub, fsub->sub.name, *pd);
fsub->privdata = pd_size == 0 ? NULL : *pd;
fsub->already_dequeued = 0;
fsub->awaiting_destruction = 0;
fsub->dequeue_handler_data = NULL;
#if NCHAN_SUBSCRIBER_LEAK_DEBUG
subscriber_debug_add(&fsub->sub);
#endif
return &fsub->sub;
}
subscriber_t *internal_subscriber_create_init(ngx_str_t *sub_name, nchan_loc_conf_t *cf, size_t pd_sz, void **pd, callback_pt enqueue, callback_pt dequeue, callback_pt respond_message, callback_pt respond_status, callback_pt notify_handler, callback_pt destroy_handler) {
subscriber_t *sub;
if(pd == NULL) {
ERR("nowhere to allocate %V subscriber data", sub_name);
return NULL;
}
sub = internal_subscriber_create(sub_name, cf, pd_sz, pd);
if(enqueue)
internal_subscriber_set_enqueue_handler(sub, enqueue);
if(dequeue)
internal_subscriber_set_dequeue_handler(sub, dequeue);
if(respond_message)
internal_subscriber_set_respond_message_handler(sub, respond_message);
if(respond_status)
internal_subscriber_set_respond_status_handler(sub, respond_status);
if(notify_handler)
internal_subscriber_set_notify_handler(sub, notify_handler);
if(destroy_handler)
internal_subscriber_set_destroy_handler(sub, destroy_handler);
return sub;
}
ngx_int_t internal_subscriber_destroy(subscriber_t *sub) {
internal_subscriber_t *fsub = (internal_subscriber_t *)sub;
if(sub->reserved > 0) {
DBG("%p not ready to destroy (reserved for %i)", sub, sub->reserved);
fsub->awaiting_destruction = 1;
}
else {
DBG("%p (%V) destroy", sub, fsub->sub.name);
#if NCHAN_SUBSCRIBER_LEAK_DEBUG
subscriber_debug_remove(sub);
#endif
fsub->destroy(NGX_OK, NULL, fsub->privdata);
nchan_free_msg_id(&sub->last_msgid);
ngx_free(fsub);
}
return NGX_OK;
}
static ngx_int_t internal_reserve(subscriber_t *self) {
internal_subscriber_t *fsub = (internal_subscriber_t *)self;
DBG("%p ) (%V) reserve", self, fsub->sub.name);
self->reserved++;
return NGX_OK;
}
static ngx_int_t internal_release(subscriber_t *sub, uint8_t nodestroy) {
internal_subscriber_t *fsub = (internal_subscriber_t *)sub;
DBG("%p (%V) release", sub, fsub->sub.name);
sub->reserved--;
if(nodestroy == 0 && fsub->awaiting_destruction == 1 && sub->reserved == 0) {
DBG("%p (%V) free", sub, fsub->sub.name);
fsub->destroy(NGX_OK, NULL, fsub->privdata);
nchan_free_msg_id(&sub->last_msgid);
ngx_free(fsub);
return NGX_ABORT;
}
else {
return NGX_OK;
}
}
void *internal_subscriber_get_privdata(subscriber_t *sub) {
internal_subscriber_t *fsub = (internal_subscriber_t *)sub;
return fsub->privdata;
}
static void reset_timer(internal_subscriber_t *f) {
if(f->sub.cf->subscriber_timeout > 0) {
if(f->timeout_ev.timer_set) {
ngx_del_timer(&f->timeout_ev);
}
ngx_add_timer(&f->timeout_ev, f->sub.cf->subscriber_timeout * 1000);
}
}
static ngx_int_t internal_enqueue(subscriber_t *self) {
internal_subscriber_t *fsub = (internal_subscriber_t *)self;
DBG("%p (%V) enqueue", self, fsub->sub.name);
if(self->cf->subscriber_timeout > 0 && !fsub->timeout_ev.timer_set) {
//add timeout timer
reset_timer(fsub);
}
fsub->enqueue(NGX_OK, NULL, fsub->privdata);
self->enqueued = 1;
return NGX_OK;
}
static ngx_int_t internal_dequeue(subscriber_t *self) {
internal_subscriber_t *f = (internal_subscriber_t *)self;
assert(!f->already_dequeued);
f->already_dequeued = 1;
DBG("%p (%V) dequeue sub", self, f->sub.name);
f->dequeue(NGX_OK, NULL, f->privdata);
f->dequeue_handler(self, f->dequeue_handler_data);
if(self->cf->subscriber_timeout > 0 && f->timeout_ev.timer_set) {
ngx_del_timer(&f->timeout_ev);
}
self->enqueued = 0;
if(self->destroy_after_dequeue) {
internal_subscriber_destroy(self);
}
return NGX_OK;
}
static ngx_int_t dequeue_maybe(subscriber_t *self) {
if(self->dequeue_after_response) {
self->fn->dequeue(self);
}
return NGX_OK;
}
static ngx_int_t internal_respond_message(subscriber_t *self, nchan_msg_t *msg) {
internal_subscriber_t *f = (internal_subscriber_t *)self;
update_subscriber_last_msg_id(self, msg);
DBG("%p (%V) respond msg %p", self, f->sub.name, msg);
f->respond_message(NGX_OK, msg, f->privdata);
reset_timer(f);
return dequeue_maybe(self);
}
static ngx_int_t internal_respond_status(subscriber_t *self, ngx_int_t status_code, const ngx_str_t *status_line) {
internal_subscriber_t *f = (internal_subscriber_t *)self;
DBG("%p status %i", self, status_code);
if(status_code == NGX_HTTP_GONE) {
self->dequeue_after_response = 1;
}
f->respond_status(status_code, (void *)status_line, f->privdata);
reset_timer(f);
return dequeue_maybe(self);
}
static ngx_int_t internal_set_dequeue_callback(subscriber_t *self, subscriber_callback_pt cb, void *privdata) {
internal_subscriber_t *f = (internal_subscriber_t *)self;
if(cb != NULL) {
DBG("%p set dequeue handler to %p", self, cb);
f->dequeue_handler = cb;
}
if(privdata != NULL) {
DBG("%p set dequeue handler data to %p", self, cb);
f->dequeue_handler_data = privdata;
}
return NGX_OK;
}
ngx_int_t internal_subscriber_set_name(subscriber_t *self, ngx_str_t *name) {
self->name = name;
return NGX_OK;
}
static ngx_int_t internal_notify(subscriber_t *self, ngx_int_t code, void *data) {
internal_subscriber_t *fsub = (internal_subscriber_t *)self;
return fsub->notify(code, data, fsub->privdata);
}
static const subscriber_fn_t internal_sub_fn = {
&internal_enqueue,
&internal_dequeue,
&internal_respond_message,
&internal_respond_status,
&internal_set_dequeue_callback,
&internal_reserve,
&internal_release,
&internal_notify,
&nchan_subscriber_subscribe
};
static const subscriber_t new_internal_sub = {
&subscriber_name,
INTERNAL,
&internal_sub_fn,
UNKNOWN,
NCHAN_ZERO_MSGID,
NULL,
NULL,
0, //reserved
0, //stick around after response
1, //destroy after dequeue
0, //enqueued
#if NCHAN_SUBSCRIBER_LEAK_DEBUG
NULL, NULL, NULL
#endif
};
| 31.525926 | 271 | 0.725564 |
5be954cf2cd50d25b52e4b49b2bb1ce22610a9eb | 1,359 | c | C | libraries/libft/tests/math/ft_uitobase_test.c | Eduard953/Cub3D | 969175e9604f2fb35a2b4bd6c70b7999e23bb043 | [
"Unlicense"
] | null | null | null | libraries/libft/tests/math/ft_uitobase_test.c | Eduard953/Cub3D | 969175e9604f2fb35a2b4bd6c70b7999e23bb043 | [
"Unlicense"
] | 12 | 2022-03-30T14:02:37.000Z | 2022-03-31T15:29:31.000Z | libraries/libft/tests/math/ft_uitobase_test.c | Eduard953/Cub3D | 969175e9604f2fb35a2b4bd6c70b7999e23bb043 | [
"Unlicense"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_uitobase_bonus_test.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pstengl <pstengl@student.42wolfsburg. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/20 15:59:13 by pstengl #+# #+# */
/* Updated: 2021/06/23 18:39:34 by pstengl ### ########.fr */
/* */
/* ************************************************************************** */
#include <assert.h>
#include <string.h>
#include "libft.h"
static void ft_test(int n, char *base, char *ref)
{
char *dest;
dest = ft_uitobase(n, base);
assert(strcmp(dest, ref) == 0);
free(dest);
}
int main(void)
{
char *hex;
char *dec;
char *oct;
char *bin;
hex = "0123456789ABCDEF";
dec = "0123456789";
oct = "01234567";
bin = "01";
ft_test(256, hex, "100");
ft_test(256, dec, "256");
ft_test(256, oct, "400");
ft_test(256, bin, "100000000");
}
| 32.357143 | 80 | 0.300957 |
8abaa650c07946bf756dc4afe4fe4325be411b00 | 574 | h | C | RobotNodeMCU/Conexion.h | MarcosAmaro/RobotIoT | 1ca38b9ea9a95beea99cd24581cdac5e886d38ee | [
"Unlicense"
] | null | null | null | RobotNodeMCU/Conexion.h | MarcosAmaro/RobotIoT | 1ca38b9ea9a95beea99cd24581cdac5e886d38ee | [
"Unlicense"
] | null | null | null | RobotNodeMCU/Conexion.h | MarcosAmaro/RobotIoT | 1ca38b9ea9a95beea99cd24581cdac5e886d38ee | [
"Unlicense"
] | null | null | null | #ifndef __CONEXION_H__
#define __CONEXION_H__
#include <FS.h> //Este include debe ir siempre primero
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager o en el gestor de librerías poner WiFiManager
/**
Función para conectar al WIFI.
En primera instancia usa el AP guardado en la placa.
Si no se puede conectar, da la opción de elegir el AP,
conectándose a la AP AutoConnectAP y
a través de un navegador yendo a: 192.168.1.4
*/
void conectarWifi();
#endif
| 28.7 | 110 | 0.735192 |
dbcf2e21c6ceb56d9bc61b7ed371e02546fe0922 | 23 | c | C | src/lib/vm_dev/c/common/vm_dev_init.c | wukong-m2m/wukong-darjeeling | 429ffdd62384c0a6b7f6695bb780359fc58a804c | [
"BSD-2-Clause-FreeBSD"
] | 16 | 2015-01-07T10:32:47.000Z | 2019-01-16T16:13:51.000Z | src/lib/vm_dev/c/common/vm_dev_init.c | wukong-m2m/wukong-darjeeling | 429ffdd62384c0a6b7f6695bb780359fc58a804c | [
"BSD-2-Clause-FreeBSD"
] | 14 | 2015-05-01T04:45:45.000Z | 2016-05-11T01:29:23.000Z | src/lib/vm_dev/c/common/vm_dev_init.c | wukong-m2m/wukong-darjeeling | 429ffdd62384c0a6b7f6695bb780359fc58a804c | [
"BSD-2-Clause-FreeBSD"
] | 13 | 2015-06-17T06:42:17.000Z | 2020-11-27T18:23:08.000Z | void vm_dev_init() { }
| 11.5 | 22 | 0.652174 |
3359a207f3c5791bdab3ad57409c28b446d3b393 | 291 | h | C | gpuHelpers.h | issaclin32/LIBLINEAR.gpu | bb8be9ca99fa35dc7379e98babcc388d3cb9b4e5 | [
"BSD-3-Clause"
] | 5 | 2017-02-06T10:03:22.000Z | 2020-03-05T13:18:58.000Z | gpuHelpers.h | issaclin32/LIBLINEAR.gpu | bb8be9ca99fa35dc7379e98babcc388d3cb9b4e5 | [
"BSD-3-Clause"
] | null | null | null | gpuHelpers.h | issaclin32/LIBLINEAR.gpu | bb8be9ca99fa35dc7379e98babcc388d3cb9b4e5 | [
"BSD-3-Clause"
] | 1 | 2018-10-09T12:37:13.000Z | 2018-10-09T12:37:13.000Z |
#ifndef gpuHelpers
#define gpuHelpers
#include <cublas_v2.h>
#include <cusparse_v2.h>
#include <helper_cuda.h>
void checkCublas(cublasStatus_t s);
void checkCusparse(cusparseStatus_t s);
unsigned long long getGFlopsOfDeviceId (unsigned int deviceID);
int getMaxGflopsDeviceId();
#endif
| 19.4 | 63 | 0.800687 |
352a747a3370626339ac8546fff13689429e8a79 | 23,386 | h | C | ToyLanguage/src/Program.h | himanshu520/HerbrandEquivalence | bfe056d9d370d9e5fe2782381b872bf102a960ba | [
"MIT"
] | null | null | null | ToyLanguage/src/Program.h | himanshu520/HerbrandEquivalence | bfe056d9d370d9e5fe2782381b872bf102a960ba | [
"MIT"
] | null | null | null | ToyLanguage/src/Program.h | himanshu520/HerbrandEquivalence | bfe056d9d370d9e5fe2782381b872bf102a960ba | [
"MIT"
] | null | null | null | /**
* @file Program.h
* This file defines classes to capture a program, and
* also provides functionalities for working with it.
**/
#ifndef PROGRAM_H
#define PROGRAM_H
#include<cassert>
#include<fstream>
#include<iostream>
#include<set>
#include<sstream>
#include<string>
#include<queue>
#include"MapVector.h"
// simple macro to print a header line to standard output
#ifndef PRINT_HEADER
#define PRINT_HEADER(str) std::cout << std::string(100, '=') << '\n' << (str) \
<< '\n' << std::string(100, '=') << '\n';
#endif
// forward declaration of `Program` class. This is required because
// `CustomOStream` and `Program` classes are interdependent.
class Program;
/**
* @struct CustomOStream
* @brief
* The << operator is overloaded for this structure, which then
* uses its data field `program`, to provide `std::cout` like
* functionalities for `Program` class.
*
* @see Program
**/
struct CustomOStream {
/**
* @brief
* The Program object over which this structure is parameterized
**/
Program &program;
/**
* @brief Constructor for the structure
*
* @param program Program object over which the new object is to
* be parameterised
**/
CustomOStream(Program &program) : program(program) {}
};
/**
* @brief
* Defines structures and methods to capture a program,
* and operate with it.
**/
class Program {
public:
/**
* @struct Program::ValueTy
*
* @brief
* Used to capture variables and constants used in
* the program.
*
* @note
* The default value (when the variable does not
* represent a valid constant/variable) for this class
* is {false, -1}.
*
* @see Program::Variables, Program::Constants
**/
struct ValueTy {
/**
* @brief
* Whether the value represented is a constant
* or a variable.
**/
bool isConst;
/**
* @brief
* The corresponding index of the constant or
* variable as given by `Program::Variables` and
* `Program::Constants`.
*
* @see Program::Variables, Program::Constants
**/
int index;
};
/**
* @struct Program::ExpressionTy
*
* @brief
* Captures expressions.
*
* @details
* An expression can either be a constant or a variable
* or a length two expression.
*
* @see Program::ValueTy
**/
struct ExpressionTy {
/**
* @brief
* Operator in the expression. If the expression represents
* non-deterministic assignment then this field holds `#`.
* Otherwise, if it is not a two length expression then this
* field defaults to `\0` for consistency. For these two
* exceptional cases the other two fields are irrelavent and
* holds their default values (which is {false, -1}).
**/
char op;
/**
* @brief
* If the expression is of length two it holds the left
* operand, else the constant/variable corresponding to
* the expression.
**/
ValueTy leftOp;
/**
* @brief
* If the expression is of length two it holds the right
* operand, else it defaults to {false, -1} for consistency.
**/
ValueTy rightOp;
};
/**
* @struct Program::InstructionTy
*
* @brief
* Captures instructions in the program
*
* @details
* An instruction is combination of an lvalue and a
* rvalue, where lvalue is a variable and rvalue is
* an expression.
*
* @see Program::ExpressionTy, Program::ValueTy
**/
struct InstructionTy {
/**
* @brief
* Lvalue of the instruction, which is a variable.
**/
ValueTy lValue;
/**
* @brief
* Rvalue of the instruction, which is an expression.
**/
ExpressionTy rValue;
/**
* @brief
* Boolean for whether this instruction is reachable
* from the beginning of the program.
**/
bool reachable;
/**
* @brief
* Index of the node representing this instruction in
* the control flow graph corresponding to the program
* (as given by `Program::CFG` data member).
*
* @see Program::CFG
**/
int cfgIndex;
/**
* @brief
* Index of the predecessors of this instructions as given
* by `Program::Instructions` data member.
*
* @note
* Only predecessors which are reachable from the start of
* the program are included.
*
* @see Program::Instructions
**/
std::set<int> predecessors;
};
/**
* @struct Program::CfgNodeTy
*
* @brief
* Represents a node in the control flow graph of the program.
**/
struct CfgNodeTy {
/**
* @brief
* Index of predecessor control flow nodes as given
* by `Program::CFG`.
*
* @see Program::CFG
**/
std::vector<int> predecessors;
/**
* @brief
* Index of the instruction which this node represents
* as given by `Program::Instructions`, if the node does
* not corresponds to an actual instruction then this
* field defaults to -1 (such nodes can represent START
* or END or confluence point).
*
* @see Program::Instructions
**/
int instructionIndex;
};
/**
* @brief Variables used in the program.
*
* @details
* It is a `MapVector` object which maps variable
* names to unique integers, so that we finally
* have to work only with integers instead of
* working with strings. Also `MapVector` maps
* unique strings to unique integers, which also
* helps to identify same variable used at different
* places.
*
* @see MapVector
**/
MapVector<std::string> Variables;
/**
* @brief Constants used in the program.
*
* @details
* It is a `MapVector` object which maps unique integers
* to new unique integers. The new mapped integers are
* used to while working with the program.
*
* @see MapVector
**/
MapVector<int> Constants;
/**
* @brief Instructions in the program.
*
* @details
* The first and last element of this vector are
* dummy which stands for START and END instructions.
* They facilitates branching and confluence at the
* start and the end of the program respectively.
*
* @see Program::InstructionTy
**/
std::vector<InstructionTy> Instructions;
/**
* @brief Control flow graph corresponding to the program.
*
* @details
* It contains nodes corresponding to the START, END,
* reachable instructions and confluence points.
*
* @see Program::CfgNodeTy
**/
std::vector<CfgNodeTy> CFG;
/**
* @brief
* To provide `std::cout` like functionality for `Program` class.
*
* @note
* Any use of `cout` refers to `Program::cout`, unless it
* is `std::cout`.
*
* @see CustomOStream
**/
CustomOStream cout;
/**
* @brief Constructor for Program class
**/
Program() : cout(*this) {}
/**
* @brief
* Parses and captures a program.
*
* @param fname Filename which contains the program text
* @return None
*
* @see Constants, Instructions, Variables
**/
void parse(std::string fname);
/**
* @brief
* Prints the program to standard output in a readable format.
*
* @return None
**/
void print();
/**
* @brief
* Creates control flow graph corresponding to the program.
*
* @return None
*
* @see CFG
**/
void createCFG();
/**
* @brief
* Prints the control flow graph corresponding to the program
* in a readable format.
*
* @return None
**/
void printCFG();
};
/**
* @brief
* Overloading < operator for some strict ordering on
* Program::ValueTy. It is required for creating
* `std::set` and `std::map` objects.
**/
bool operator<(Program::ValueTy const &first,
Program::ValueTy const &second) {
if(first.isConst == second.isConst)
return first.index < second.index;
return first.isConst;
}
/**
* @brief
* Overloading < operator for some strict ordering
* on Program::ExpressionTy. It is required for
* creating `std::set` and `std::map` objects.
**/
bool operator<(Program::ExpressionTy const &first,
Program::ExpressionTy const &second) {
if(first.op != second.op) return first.op < second.op;
if(first.leftOp < second.leftOp) return true;
if(second.leftOp < first.leftOp) return false;
return first.rightOp < second.rightOp;
}
CustomOStream& operator<<(CustomOStream &os, char ch) {
std::cout << ch;
return os;
}
CustomOStream& operator<<(CustomOStream &os, int i) {
std::cout << i;
return os;
}
CustomOStream& operator<<(CustomOStream &os, std::string s) {
std::cout << s;
return os;
}
CustomOStream& operator<<(CustomOStream &os, Program::ValueTy const &v) {
if(v.isConst) std::cout << os.program.Constants[v.index];
else std::cout << os.program.Variables[v.index];
return os;
}
CustomOStream& operator<<(CustomOStream &os, Program::ExpressionTy const &e) {
if(e.op == '\0') return os << e.leftOp;
if(e.op == '#') return os << '*';
return os << e.leftOp << ' ' << e.op << ' ' << e.rightOp;
}
CustomOStream& operator<<(CustomOStream &os, Program::InstructionTy const &i) {
return os << i.lValue << " = " << i.rValue;
}
/**
* @brief Parses and captures a program.
*
* @param fname Filename which contains the program text
* @return None
*
* @see Constants, Instructions, Variables
**/
void Program::parse(std::string fname) {
std::ifstream fin(fname);
assert(fin && "Error opening file");
// keeps count of the current instruction number. It is
// initialised 1 because 0th instruction is the dummy START
// instruction
int instCnt = 1;
// holds a program line
std::string buf;
// holds jump labels for instructions corresponding to their indexes.
// If `jumps` vector is empty for an instruction, it means a default
// jump to the instruction corresponding to the next index
std::vector<std::vector<std::string>> jumps;
// holds the instruction indexes to which the labels refer to
std::map<std::string, int> labels;
// updating `jumps` and `Program::Instructions` for START instruction
InstructionTy dummy = {{false, -1}, {'\0', {false, -1}, {false, -1}}, false, {}};
Instructions.emplace_back(dummy);
jumps.emplace_back(std::vector<std::string>());
// read the program, processing each instruction type and checking
// the validity. The jumps can not be resolved at this stage (before
// the whole program is processed), as labels can be used before
// definitions
while(getline(fin, buf)) {
// ignores empty lines in the program text
if(buf.empty()) continue;
// buffer holding current instruction
std::stringstream ss(buf);
// holds the tokens in the instruction while they are processed
// in succession
std::string in;
// read the first token in the instruction
ss >> in;
if(in == "GOTO") {
while(ss >> in)
jumps[instCnt - 1].push_back(in);
} else if(in == "LABEL") {
// current instruction defines a label
while(ss >> in) {
assert(labels.find(in) == labels.end() && "Duplicate label found");
labels[in] = instCnt;
}
} else {
// current instruction is an assignment instruction
int constVal;
ValueTy lValue, leftOp, rightOp;
char op = '\0';
try {
// ideally lvalue should be a variable (a string that does
// not starts with a digit). So this must throw an exception
// and we should reach catch block.
constVal = std::stoi(in.c_str());
assert(false && "LValue is not a variable");
} catch(std::invalid_argument) {
// storing lvalue of current instruction
lValue = {false, Variables.insert(in).first};
// read and ignore the `=` in the instruction buffer
in.clear(), ss >> in;
assert(in == "=" && "No RValue specified");
// read the first operand from the instruction buffer
in.clear(), ss >> in;
assert(!in.empty() && "No RValue specified");
// store left operand of rvalue of current instruction
try {
constVal = std::stoi(in.c_str());
leftOp = {true, Constants.insert(constVal).first};
} catch(std::invalid_argument) {
if(in == "*") op = '#', leftOp = {false, -1};
else leftOp = {false, Variables.insert(in).first};
}
// read the next token in the instruction buffer (which should
// be the operator if any)
in.clear(), ss >> in;
// if the current instruction is non-deterministic assignment
// then it can not have a second operand. Note that if the
// rvalue is non-deterministic only then `op` has value `#`.
assert((op != '#' || in.empty()) && "Invalid instruction");
if(!in.empty()) {
// if the current instruction has rvalue, which is two
// length expression
// determine the operator and check if it is valid.
// If the operator is invalid then op will have value
// '\0', by which it was initialised
if(in.length() == 1) {
switch(in[0]) {
case '+':
case '-':
case '*':
case '/': op = in[0];
}
}
assert(op != '\0' && "Invalid operand");
// read the second operand from the instruction buffer
in.clear(), ss >> in;
assert(!in.empty() && "Second operand not specified");
// store right operand of rvalue of current instruction
try {
constVal = std::stoi(in.c_str());
rightOp = {true, Constants.insert(constVal).first};
} catch(std::invalid_argument) {
rightOp = {false, Variables.insert(in).first};
}
} else {
// if rvalue is not two length expression, a default value
// value for right operand for consistency
rightOp = {false, -1};
}
}
// push the current instruction in `Instructions` vector
// at index `instCnt`. For now `reachable` and `cfgIndex`
// fields are set to default value of false and -1. These
// would be set to actual values later.
Instructions.push_back({lValue, {op, leftOp, rightOp}, false, -1, {}});
jumps.emplace_back(std::vector<std::string>());
instCnt++;
}
}
// updating `jumps` and `Program::Instructions` for END instruction
Instructions.push_back(dummy);
jumps.emplace_back(std::vector<std::string>());
instCnt++;
// now process the jumps as given by the labels. Reachability
// is determined by performing breadth first search (BFS) from
// index 0 in `Instructions` (the START instruction).
// Instructions for which `jumps` list is empty has by default
// jump to the instruction corresponding to the next index.
std::queue<int> q;
q.push(0), Instructions[0].reachable = true;
while(not q.empty()) {
int cur = q.front();
q.pop();
if(not jumps[cur].empty()) {
// process the jumps
for(auto el : jumps[cur]) {
auto it = labels.find(el);
assert(it != labels.end() && "Undefined label found");
// if the label points to index `instCnt`, it means
// the current instruction being processed is the dummy
// END instruction and this has to be ignored
if(it->second == instCnt) continue;
Instructions[it->second].predecessors.insert(cur);
if(not Instructions[it->second].reachable) {
Instructions[it->second].reachable = true;
q.push(it->second);
}
}
} else {
// if the index of the next instruction is `instCnt`, it
// means the current instruction being processed is the
// dummy END instruction and this has to be ignored
if(cur + 1 == instCnt) continue;
// the successor of current instruction is the next
// instruction index
Instructions[cur + 1].predecessors.insert(cur);
if(not Instructions[cur + 1].reachable) {
Instructions[cur + 1].reachable = true;
q.push(cur + 1);
}
}
}
fin.close();
}
/**
* @brief
* Prints the program to standard output in a readable format.
*
* @return None
**/
void Program::print() {
// print all the variables
PRINT_HEADER("Variables");
for(auto &el : Variables)
cout << el << ", ";
cout << "\n\n";
// print all the constants
PRINT_HEADER("Constants");
for(auto &el : Constants)
cout << el << ", ";
cout << "\n\n";
// now print all the instructions, if they are
// reachable print their predecessors else mark
// them as unreachable
PRINT_HEADER("Input Program");
int sz = Instructions.size();
for(int i = 0; i < sz; i++) {
cout << '[' << i << "] : ";
if(i == 0) cout << "START";
else if(i == sz - 1) cout << "END";
else cout << Instructions[i];
if(Instructions[i].reachable) {
cout << "\t[ Predecessor Instructions : ";
for(auto el : Instructions[i].predecessors)
cout << el << " ";
cout << "]\n";
} else cout << "\t[ Unreachable ]\n";
}
cout << "\n\n";
}
/**
* @brief
* Creates control flow graph corresponding to the program.
*
* @return None
*
* @see CFG
**/
void Program::createCFG() {
// holds the size of the control flow graph
int cfgSize = 0;
// first set `cfgIndex` for each instruction
for(auto &el : Instructions) {
// there are no node in CFG corresponding to unreachable
// instructions, so we skip them
if(not el.reachable) continue;
if(el.predecessors.size() > 1) {
// if the current instruction is a confluence point.
// Note that this condition is not `!= 1`, because it
// must also be false for the START instruction (for which
// `== 0` is true and hence `!= 1` would then be true)
// there would be a node for the instruction as well as
// for the confluence point. The confluence point gets
// index `cfgSize` and the instruction gets index
// `cfgSize + 1`. Only 'cfgSize + 1' is stored, and
// the index of confluence point in CFG can be inferred
// with its help
el.cfgIndex = cfgSize + 1;
// update `cfgSize`
cfgSize += 2;
} else {
// there would only be node for the instruction which
// gets index `cfgSize` and `cfgSize` is incremented
el.cfgIndex = cfgSize++;
}
}
// now create control flow graph, using assigned `cfgIndex`
// for each instructions
CFG.resize(cfgSize);
for(int i = 0; i < Instructions.size(); i++) {
InstructionTy &I = Instructions[i];
// ignore unreachable instructions
if(not I.reachable) continue;
int idx = I.cfgIndex;
int sz = I.predecessors.size();
if(sz > 1) {
// if the instruction has more than one predecessors
// node for the confluence point
int confIdx = idx - 1;
CFG[confIdx].instructionIndex = -1;
for(auto el : I.predecessors) {
int predIdx = Instructions[el].cfgIndex;
CFG[confIdx].predecessors.push_back(predIdx);
}
// node for the instruction
CFG[idx].predecessors.push_back(confIdx);
CFG[idx].instructionIndex = i;
} else {
// if the instruction is not the START instruction
// update the predecessor for the node corresponding
// to the instruction
if(sz != 0) {
int predIdx = Instructions[*(I.predecessors.begin())].cfgIndex;
CFG[idx].predecessors.push_back(predIdx);
}
CFG[idx].instructionIndex = i;
}
}
}
/**
* @brief
* Prints the control flow graph corresponding to the program
* in a readable format.
*
* @return None
**/
void Program::printCFG() {
PRINT_HEADER("Control Flow Graph");
int cfgSize = CFG.size();
for(int i = 0; i < cfgSize; i++) {
cout << '[' << i << "] : ";
int sz = CFG[i].predecessors.size();
int idx = CFG[i].instructionIndex;
if(sz == 0) cout << "START\n";
else if(sz == 1) {
// for normal control flow graph nodes, print the
// instruction index (as given by `Instructions`),
// the instruction itself and then the index of
// the predecssor control flow graph node
if(idx == Instructions.size() - 1) cout << "END";
else cout << "Transfer Point => (" << idx << ") "
<< Instructions[idx];
cout << " [ Predecessor CFG Node : "
<< CFG[i].predecessors[0] << " ]\n";
} else {
// for confluence points print the indexes of the
// predecessor control flow graph nodes
cout << "Confluence Point => [ Predecessor CFG Nodes : ";
for(auto el : CFG[i].predecessors)
cout << el << " ";
cout << "]\n";
}
}
cout << "\n\n";
}
#endif | 31.015915 | 85 | 0.543231 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.