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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b07f03868e904e830135265f1fd279195cdd369 | 155 | h | C | STEER/STEERBase/AliMagFastDip5k/AliMagFastDip5k.h | shahor02/AliRoot | 37118c83effe7965a2a24b3b868bf9012727fb7e | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | STEER/STEERBase/AliMagFastDip5k/AliMagFastDip5k.h | shahor02/AliRoot | 37118c83effe7965a2a24b3b868bf9012727fb7e | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | STEER/STEERBase/AliMagFastDip5k/AliMagFastDip5k.h | shahor02/AliRoot | 37118c83effe7965a2a24b3b868bf9012727fb7e | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | #include "AliMagFastDip5k_0.h"
#include "AliMagFastDip5k_1.h"
#include "AliMagFastDip5k_2.h"
#include "AliMagFastDip5k_3.h"
#include "AliMagFastDip5k_4.h"
| 25.833333 | 30 | 0.806452 |
9f293629f6e84de3ae680b25c0bd56ee77da17fb | 474 | h | C | include/blt_tof.h | rdissauer/blt_tof_ros_pkg | a51356db5bb23087690733a1a7513542c6292d0d | [
"MIT"
] | null | null | null | include/blt_tof.h | rdissauer/blt_tof_ros_pkg | a51356db5bb23087690733a1a7513542c6292d0d | [
"MIT"
] | null | null | null | include/blt_tof.h | rdissauer/blt_tof_ros_pkg | a51356db5bb23087690733a1a7513542c6292d0d | [
"MIT"
] | null | null | null | #ifndef BLT_TOF_H_INCLUDED
#define BLT_TOF_H_INCLUDED
#include <pcl_ros/point_cloud.h>
#include <bta.h>
#ifdef __cplusplus
extern "C"
{
#endif
//typedef pcl::PointCloud<pcl::PointXYZ> FrameXYZ;
typedef pcl::PointCloud<pcl::PointXYZI> FrameXYZAmp;
static void BTA_CALLCONV infoEvent(BTA_EventId eventId, int8_t *msg);
void blt_tof_connect(BTA_Handle *btaHandle);
void blt_tof_get_frame(BTA_Handle btaHandle, FrameXYZAmp::Ptr msg);
#ifdef __cplusplus
}
#endif
#endif
| 18.96 | 69 | 0.78903 |
23f6d318c019db89984bdec4111984550204f720 | 191 | h | C | MagicThought-master/Classes/MagicThought/MTPageScroll/MTPageScroll.h | alrjqow/MagicThought-master | fbcca8cb3e8640419bb8e39b92bc1f7c77599cf8 | [
"MIT"
] | 1 | 2022-03-01T06:58:49.000Z | 2022-03-01T06:58:49.000Z | MagicThought-master/Classes/MagicThought/MTPageScroll/MTPageScroll.h | alrjqow/MagicThought-master | fbcca8cb3e8640419bb8e39b92bc1f7c77599cf8 | [
"MIT"
] | null | null | null | MagicThought-master/Classes/MagicThought/MTPageScroll/MTPageScroll.h | alrjqow/MagicThought-master | fbcca8cb3e8640419bb8e39b92bc1f7c77599cf8 | [
"MIT"
] | null | null | null | //
// MTPageScroll.h
// QXProject
//
// Created by monda on 2020/4/14.
// Copyright © 2020 monda. All rights reserved.
//
#import "MTPageSumController.h"
#import "MTPageControllModel.h"
| 17.363636 | 48 | 0.691099 |
f0695d7cbf3f2cfb050476d0cf3c508b78f386b3 | 430 | h | C | apps/lighttpd-1.4.32/src/mod_cml_funcs.h | XinShuYang/mtcp-epoll_event | a3fb0ea87417f70bd0fb7885e17e186f47f22a02 | [
"BSD-3-Clause"
] | 979 | 2015-01-05T03:50:43.000Z | 2018-11-23T02:36:46.000Z | apps/lighttpd-1.4.32/src/mod_cml_funcs.h | XinShuYang/mtcp-epoll_event | a3fb0ea87417f70bd0fb7885e17e186f47f22a02 | [
"BSD-3-Clause"
] | 195 | 2015-04-03T15:55:02.000Z | 2018-11-22T08:52:33.000Z | apps/lighttpd-1.4.32/src/mod_cml_funcs.h | XinShuYang/mtcp-epoll_event | a3fb0ea87417f70bd0fb7885e17e186f47f22a02 | [
"BSD-3-Clause"
] | 308 | 2015-01-01T05:25:52.000Z | 2018-11-20T17:31:52.000Z | #ifndef _MOD_CML_FUNCS_H_
#define _MOD_CML_FUNCS_H_
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef HAVE_LUA_H
#include <lua.h>
int f_crypto_md5(lua_State *L);
int f_file_mtime(lua_State *L);
int f_file_isreg(lua_State *L);
int f_file_isdir(lua_State *L);
int f_dir_files(lua_State *L);
int f_memcache_exists(lua_State *L);
int f_memcache_get_string(lua_State *L);
int f_memcache_get_long(lua_State *L);
#endif
#endif
| 19.545455 | 40 | 0.788372 |
185ce41b246249131f7c14faa73fb528177346b4 | 10,793 | h | C | src/QtTypes.h | mgb4/qui | d3b5726333a2278286e0876427771393e1a09b9c | [
"MIT"
] | 1 | 2020-03-28T16:17:27.000Z | 2020-03-28T16:17:27.000Z | src/QtTypes.h | mgb4/qui | d3b5726333a2278286e0876427771393e1a09b9c | [
"MIT"
] | null | null | null | src/QtTypes.h | mgb4/qui | d3b5726333a2278286e0876427771393e1a09b9c | [
"MIT"
] | null | null | null | #pragma once
#include "qui.h"
#include <QVariant>
#include <QJSValue>
#include <QJSValueIterator>
#include "QtSimpleTypes.h"
#include "Holder.h"
template<> struct Type<QVariant>;
template<> struct Type<QJSValue>;
py::object variantToPython(const QVariant& v);
//-----------------------------------------------------------------------------
// VariantHolder
//-----------------------------------------------------------------------------
template<>
struct Type<VariantHolder>
{
static py::object toPython(const VariantHolder& v)
{
return py::cast(v);
}
static VariantHolder fromPython(const py::object& o)
{
return py::cast<VariantHolder>(o);
}
static QVariant get(const py::object& o)
{
return py::cast<VariantHolder>(o).get();
}
static bool isValid(const py::object& o)
{
return py::isinstance<VariantHolder>(o);
}
};
//-----------------------------------------------------------------------------
// QJSValue / QVariant
//-----------------------------------------------------------------------------
template<>
struct Type<QJSValue>
{
static py::object toPython(const QJSValue& v)
{
if (v.isNull())
return py::none();
else if (v.isNumber())
return Float::toPython(v.toNumber());
else if (v.isBool())
return Bool::toPython(v.toBool());
else if (v.isString())
return Type<QString>::toPython(v.toString());
else if (v.isDate())
return Type<QDateTime>::toPython(v.toDateTime());
else if (v.isArray())
{
// Array needs to be before isObject, because an array is also an object
py::list list;
int len = v.property("length").toInt();
for (int i = 0; i < len; i++)
list.append(Type<QJSValue>::toPython(v.property(i)));
return list;
}
else if (v.isVariant())
return variantToPython(v.toVariant());
else if (v.isQObject())
return Type<QObject*>::toPython(v.toQObject());
else if (v.isQMetaObject())
return Type<QMetaObject*>::toPython(v.toQMetaObject());
else if (v.isObject())
{
py::dict dict;
QJSValueIterator it(v);
while (it.hasNext())
{
it.next();
py::object key = Type<QString>::toPython(it.name());
py::object value = Type<QJSValue>::toPython(it.value());
dict[key] = value;
}
return dict;
}
else
throw std::invalid_argument("Unsupported QJSValue");
}
static QJSValue fromPython(const py::object& o)
{
throw std::runtime_error("Cannot convert QJSValue");
}
static bool isValid(const py::object& o)
{
return false;
}
};
template<>
struct Type<QVariant>
{
static py::object toPython(const QVariant& v)
{
return Conversion::convertObject<py::object, const QVariant&, Conversion::Py>(v.userType(), v);
}
static QVariant fromPython(const py::object& o)
{
// If the PyObject is a basic type extract it, otherwise store the object
if (Bool::isValid(o))
return Bool::fromPython(o);
if (Long::isValid(o))
return Long::variantFromPython(o);
if (Float::isValid(o))
return Float::fromPython<double>(o);
if (Type<QString>::isValid(o))
return Type<QString>::fromPython(o);
if (Type<QDateTime>::isValid(o))
return Type<QDateTime>::fromPython(o);
if (Type<VariantHolder>::isValid(o))
return Type<VariantHolder>::get(o);
return QVariant::fromValue(ObjectHolder(o));
}
static bool isValid(const py::object& o)
{
// Every Python object can be converted into a QVariant
return true;
}
static QVariant extractType(int dataType, const py::object& o)
{
return Conversion::convertObject<QVariant, py::object, Conversion::QVar>(dataType, o);
}
static bool isValidType(int dataType, const py::object& o)
{
return Conversion::convertObject<bool, py::object, Conversion::Valid>(dataType, o);
}
struct Conversion
{
// PyObject*
struct Py
{
static py::object unsupported(const QVariant&) { throw std::invalid_argument("Unsupported type"); }
template<class T> static py::object create(const QVariant& v) { return Type<T>::toPython(v.value<T>()); }
template<> static py::object create<void>(const QVariant& v) { return py::none(); }
};
// QVariant
struct QVar
{
static QVariant unsupported(const py::object&) { throw std::invalid_argument("Unsupported type"); }
template<class T> static QVariant create(const py::object& o) { return QVariant::fromValue(Type<T>::fromPython(o)); }
template<> static QVariant create<void>(const py::object&) { return QVariant(); }
template<> static QVariant create<QVariant>(const py::object& o) { return Type<QVariant>::fromPython(o); }
};
struct Valid
{
static bool unsupported(const py::object&) { return false; }
template<class T> static bool create(const py::object&) { return true; }
};
template<class R, class V, class Conv>
static R convertObject(int dataType, V v)
{
switch (dataType)
{
case QMetaType::Void: return Conv::create<void>(v);
case QMetaType::UnknownType: return Conv::create<void>(v);
case QMetaType::QVariant: return Conv::create<QVariant>(v);
case QMetaType::Bool: return Conv::create<bool>(v);
case QMetaType::Char: return Conv::create<char>(v);
case QMetaType::SChar: return Conv::create<signed char>(v);
case QMetaType::UChar: return Conv::create<unsigned char>(v);
case QMetaType::Short: return Conv::create<short>(v);
case QMetaType::UShort: return Conv::create<unsigned short>(v);
case QMetaType::Int: return Conv::create<int>(v);
case QMetaType::UInt: return Conv::create<unsigned int>(v);
case QMetaType::Long: return Conv::create<long>(v);
case QMetaType::ULong: return Conv::create<unsigned long>(v);
case QMetaType::LongLong: return Conv::create<long long>(v);
case QMetaType::ULongLong: return Conv::create<unsigned long long>(v);
case QMetaType::Float: return Conv::create<float>(v);
case QMetaType::Double: return Conv::create<double>(v);
case QMetaType::QString: return Conv::create<QString>(v);
case QMetaType::QUrl: return Conv::create<QUrl>(v);
case QMetaType::QByteArray: return Conv::create<QByteArray>(v);
case QMetaType::QSize: return Conv::create<QSize>(v);
case QMetaType::QSizeF: return Conv::create<QSizeF>(v);
case QMetaType::QRect: return Conv::create<QRect>(v);
case QMetaType::QRectF: return Conv::create<QRectF>(v);
case QMetaType::QPoint: return Conv::create<QPoint>(v);
case QMetaType::QPointF: return Conv::create<QPointF>(v);
case QMetaType::QMatrix: return Conv::create<QMatrix>(v);
case QMetaType::QMatrix4x4: return Conv::create<QMatrix4x4>(v);
case QMetaType::QTransform: return Conv::create<QTransform>(v);
case QMetaType::QQuaternion: return Conv::create<QQuaternion>(v);
case QMetaType::QVector2D: return Conv::create<QVector2D>(v);
case QMetaType::QVector3D: return Conv::create<QVector3D>(v);
case QMetaType::QVector4D: return Conv::create<QVector4D>(v);
case QMetaType::QPolygon: return Conv::create<QPolygon>(v);
case QMetaType::QPolygonF: return Conv::create<QPolygonF>(v);
case QMetaType::QColor: return Conv::create<QColor>(v);
case QMetaType::QDateTime: return Conv::create<QDateTime>(v);
case QMetaType::QImage: return Conv::create<QImage>(v);
case QMetaType::QObjectStar: return Conv::create<QObject*>(v);
/*
case QMetaType::QJsonValue: return Converter<QJsonValue>::create(v.value<QJsonValue>());
case QMetaType::QJsonObject: return Converter<QJsonObject>::create(v.value<QJsonObject>());
case QMetaType::QJsonArray: return Converter<QJsonArray>::create(v.value<QJsonArray>());
case QMetaType::QJsonDocument: return Converter<QJsonDocument>::create(v.value<QJsonDocument>());
case QMetaType::QStringList: return Converter<QStringList>::toPython(v.value<QStringList>());
case QMetaType::QVariantHash: return Converter<QVariantHash>::toPython(v.value<QVariantHash>());
case QMetaType::QVariantMap: return Converter<QVariantMap>::toPython(v.value<QVariantMap>());
*/
}
if (QMetaType::typeFlags(dataType) & QMetaType::PointerToQObject) return Conv::create<QObject*>(v);
if (dataType == qMetaTypeId<ObjectHolder>()) return Conv::create<ObjectHolder>(v);
if (dataType == qMetaTypeId<py::object>()) return Conv::create<py::object>(v);
if (dataType == qMetaTypeId<QJSValue>()) return Conv::create<QJSValue>(v);
if (dataType == qMetaTypeId<QVector<QPoint>>()) return Conv::create<QVector<QPoint>>(v);
if (dataType == qMetaTypeId<QVector<QPointF>>()) return Conv::create<QVector<QPointF>>(v);
if (dataType == qMetaTypeId<QVector<QVector2D>>()) return Conv::create<QVector<QVector2D>>(v);
if (dataType == qMetaTypeId<QVector<QVector3D>>()) return Conv::create<QVector<QVector3D>>(v);
if (dataType == qMetaTypeId<QVector<QVector4D>>()) return Conv::create<QVector<QVector4D>>(v);
return Conv::unsupported(v);
}
};
};
inline py::object variantToPython(const QVariant& v)
{
return Type<QVariant>::toPython(v);
}
| 36.962329 | 129 | 0.55221 |
9bcbd88732420d9f8b31ab0b4e2fd8b01d7ddf64 | 41,690 | c | C | subversion/svn/shelf-cmd.c | foundations/subversion | 5c3f94d322ed579400eba5981e47810284cbfed9 | [
"Apache-2.0"
] | null | null | null | subversion/svn/shelf-cmd.c | foundations/subversion | 5c3f94d322ed579400eba5981e47810284cbfed9 | [
"Apache-2.0"
] | null | null | null | subversion/svn/shelf-cmd.c | foundations/subversion | 5c3f94d322ed579400eba5981e47810284cbfed9 | [
"Apache-2.0"
] | null | null | null | /*
* shelf-cmd.c -- Shelving commands.
*
* ====================================================================
* 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.
* ====================================================================
*/
/* We define this here to remove any further warnings about the usage of
experimental functions in this file. */
#define SVN_EXPERIMENTAL
#include "svn_client.h"
#include "svn_error_codes.h"
#include "svn_error.h"
#include "svn_hash.h"
#include "svn_path.h"
#include "svn_props.h"
#include "svn_pools.h"
#include "svn_utf.h"
#include "cl.h"
#include "svn_private_config.h"
#include "private/svn_sorts_private.h"
#include "private/svn_client_private.h"
/* Open the newest version of SHELF; error if no versions found. */
static svn_error_t *
get_newest_version_existing(svn_client__shelf_version_t **shelf_version_p,
svn_client__shelf_t *shelf,
apr_pool_t *result_pool,
apr_pool_t *scratch_pool)
{
SVN_ERR(svn_client__shelf_get_newest_version(shelf_version_p, shelf,
result_pool, scratch_pool));
if (!*shelf_version_p)
{
return svn_error_createf(SVN_ERR_ILLEGAL_TARGET, NULL,
_("Shelf '%s': no versions found"),
shelf->name);
}
return SVN_NO_ERROR;
}
/* Fetch the next argument. */
static svn_error_t *
get_next_argument(const char **arg,
apr_getopt_t *os,
apr_pool_t *result_pool,
apr_pool_t *scratch_pool)
{
apr_array_header_t *args;
SVN_ERR(svn_opt_parse_num_args(&args, os, 1, scratch_pool));
SVN_ERR(svn_utf_cstring_to_utf8(arg,
APR_ARRAY_IDX(args, 0, const char *),
result_pool));
return SVN_NO_ERROR;
}
/* Parse the remaining arguments as paths relative to a WC.
*
* TARGETS are relative to current working directory.
*
* Set *targets_by_wcroot to a hash mapping (char *)wcroot_abspath to
* (apr_array_header_t *)array of relpaths relative to that WC root.
*/
static svn_error_t *
targets_relative_to_wcs(apr_hash_t **targets_by_wcroot_p,
apr_array_header_t *targets,
svn_client_ctx_t *ctx,
apr_pool_t *result_pool,
apr_pool_t *scratch_pool)
{
apr_hash_t *targets_by_wcroot = apr_hash_make(result_pool);
int i;
/* Make each target relative to the WC root. */
for (i = 0; i < targets->nelts; i++)
{
const char *target = APR_ARRAY_IDX(targets, i, const char *);
const char *wcroot_abspath;
apr_array_header_t *paths;
SVN_ERR(svn_dirent_get_absolute(&target, target, result_pool));
SVN_ERR(svn_client_get_wc_root(&wcroot_abspath, target,
ctx, result_pool, scratch_pool));
paths = svn_hash_gets(targets_by_wcroot, wcroot_abspath);
if (! paths)
{
paths = apr_array_make(result_pool, 0, sizeof(char *));
svn_hash_sets(targets_by_wcroot, wcroot_abspath, paths);
}
target = svn_dirent_skip_ancestor(wcroot_abspath, target);
if (target)
APR_ARRAY_PUSH(paths, const char *) = target;
}
*targets_by_wcroot_p = targets_by_wcroot;
return SVN_NO_ERROR;
}
/* Return targets relative to a WC. Error if they refer to more than one WC. */
static svn_error_t *
targets_relative_to_a_wc(const char **wc_root_abspath_p,
apr_array_header_t **paths_p,
apr_getopt_t *os,
const apr_array_header_t *known_targets,
svn_client_ctx_t *ctx,
apr_pool_t *result_pool,
apr_pool_t *scratch_pool)
{
apr_array_header_t *targets;
apr_hash_t *targets_by_wcroot;
apr_hash_index_t *hi;
SVN_ERR(svn_cl__args_to_target_array_print_reserved(&targets, os,
known_targets,
ctx, FALSE, result_pool));
svn_opt_push_implicit_dot_target(targets, result_pool);
SVN_ERR(targets_relative_to_wcs(&targets_by_wcroot, targets,
ctx, result_pool, scratch_pool));
if (apr_hash_count(targets_by_wcroot) != 1)
return svn_error_create(SVN_ERR_ILLEGAL_TARGET, NULL,
_("All targets must be in the same WC"));
hi = apr_hash_first(scratch_pool, targets_by_wcroot);
*wc_root_abspath_p = apr_hash_this_key(hi);
*paths_p = apr_hash_this_val(hi);
return SVN_NO_ERROR;
}
/* Return a human-friendly description of DURATION.
*/
static char *
friendly_age_str(apr_time_t mtime,
apr_time_t time_now,
apr_pool_t *result_pool)
{
int minutes = (int)((time_now - mtime) / 1000000 / 60);
char *s;
if (minutes >= 60 * 24)
s = apr_psprintf(result_pool,
Q_("%d day ago", "%d days ago",
minutes / 60 / 24),
minutes / 60 / 24);
else if (minutes >= 60)
s = apr_psprintf(result_pool,
Q_("%d hour ago", "%d hours ago",
minutes / 60),
minutes / 60);
else
s = apr_psprintf(result_pool,
Q_("%d minute ago", "%d minutes ago",
minutes),
minutes);
return s;
}
/* A comparison function for svn_sort__hash(), comparing the mtime of two
svn_client_shelf_info_t's. */
static int
compare_shelf_infos_by_mtime(const svn_sort__item_t *a,
const svn_sort__item_t *b)
{
svn_client__shelf_info_t *a_val = a->value;
svn_client__shelf_info_t *b_val = b->value;
return (a_val->mtime < b_val->mtime)
? -1 : (a_val->mtime > b_val->mtime) ? 1 : 0;
}
/* Return a list of shelves sorted by their mtime, oldest first.
*/
static svn_error_t *
list_sorted_by_date(apr_array_header_t **list,
const char *local_abspath,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
apr_hash_t *shelf_infos;
SVN_ERR(svn_client__shelf_list(&shelf_infos, local_abspath,
ctx, scratch_pool, scratch_pool));
*list = svn_sort__hash(shelf_infos,
compare_shelf_infos_by_mtime,
scratch_pool);
return SVN_NO_ERROR;
}
/* */
static svn_error_t *
stats(svn_client__shelf_t *shelf,
int version,
svn_client__shelf_version_t *shelf_version,
apr_time_t time_now,
svn_boolean_t with_logmsg,
apr_pool_t *scratch_pool)
{
char *age_str;
char *version_str;
apr_hash_t *paths;
const char *paths_str = "";
if (! shelf_version)
{
return SVN_NO_ERROR;
}
age_str = friendly_age_str(shelf_version->mtime, time_now, scratch_pool);
if (version == shelf->max_version)
version_str = apr_psprintf(scratch_pool,
_("version %d"), version);
else
version_str = apr_psprintf(scratch_pool,
Q_("version %d of %d", "version %d of %d",
shelf->max_version),
version, shelf->max_version);
SVN_ERR(svn_client__shelf_paths_changed(&paths, shelf_version,
scratch_pool, scratch_pool));
paths_str = apr_psprintf(scratch_pool,
Q_("%d path changed", "%d paths changed",
apr_hash_count(paths)),
apr_hash_count(paths));
SVN_ERR(svn_cmdline_printf(scratch_pool,
"%-30s %s, %s, %s\n",
shelf->name, version_str, age_str, paths_str));
if (with_logmsg)
{
char *log_message;
SVN_ERR(svn_client__shelf_get_log_message(&log_message, shelf,
scratch_pool));
if (log_message)
{
SVN_ERR(svn_cmdline_printf(scratch_pool,
_(" %.50s\n"),
log_message));
}
}
return SVN_NO_ERROR;
}
/* Display a list of shelves */
static svn_error_t *
shelves_list(const char *local_abspath,
svn_boolean_t quiet,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
apr_time_t time_now = apr_time_now();
apr_array_header_t *list;
int i;
SVN_ERR(list_sorted_by_date(&list,
local_abspath, ctx, scratch_pool));
for (i = 0; i < list->nelts; i++)
{
const svn_sort__item_t *item = &APR_ARRAY_IDX(list, i, svn_sort__item_t);
const char *name = item->key;
svn_client__shelf_t *shelf;
svn_client__shelf_version_t *shelf_version;
SVN_ERR(svn_client__shelf_open_existing(&shelf, name, local_abspath,
ctx, scratch_pool));
SVN_ERR(svn_client__shelf_get_newest_version(&shelf_version, shelf,
scratch_pool, scratch_pool));
if (quiet)
SVN_ERR(svn_cmdline_printf(scratch_pool, "%s\n", shelf->name));
else if (!shelf_version)
SVN_ERR(svn_cmdline_printf(scratch_pool, "%-30s no versions\n",
shelf->name));
else
SVN_ERR(stats(shelf, shelf->max_version, shelf_version, time_now,
TRUE /*with_logmsg*/, scratch_pool));
SVN_ERR(svn_client__shelf_close(shelf, scratch_pool));
}
return SVN_NO_ERROR;
}
/* Print info about each checkpoint of the shelf named NAME.
*/
static svn_error_t *
shelf_log(const char *name,
const char *local_abspath,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
apr_time_t time_now = apr_time_now();
svn_client__shelf_t *shelf;
apr_array_header_t *versions;
int i;
SVN_ERR(svn_client__shelf_open_existing(&shelf, name, local_abspath,
ctx, scratch_pool));
SVN_ERR(svn_client__shelf_get_all_versions(&versions, shelf,
scratch_pool, scratch_pool));
for (i = 0; i < versions->nelts; i++)
{
svn_client__shelf_version_t *shelf_version
= APR_ARRAY_IDX(versions, i, void *);
SVN_ERR(stats(shelf, i + 1, shelf_version, time_now,
FALSE /*with_logmsg*/, scratch_pool));
}
SVN_ERR(svn_client__shelf_close(shelf, scratch_pool));
return SVN_NO_ERROR;
}
/* Find the name of the youngest shelf.
*/
static svn_error_t *
name_of_youngest(const char **name_p,
const char *local_abspath,
svn_client_ctx_t *ctx,
apr_pool_t *result_pool,
apr_pool_t *scratch_pool)
{
apr_array_header_t *list;
const svn_sort__item_t *youngest_item;
SVN_ERR(list_sorted_by_date(&list,
local_abspath, ctx, scratch_pool));
if (list->nelts == 0)
return svn_error_create(SVN_ERR_CL_INSUFFICIENT_ARGS, NULL,
_("No shelves found"));
youngest_item = &APR_ARRAY_IDX(list, list->nelts - 1, svn_sort__item_t);
*name_p = apr_pstrdup(result_pool, youngest_item->key);
return SVN_NO_ERROR;
}
struct status_baton
{
/* These fields correspond to the ones in the
svn_cl__print_status() interface. */
const char *target_abspath;
const char *target_path;
svn_boolean_t quiet; /* don't display statuses while shelving them */
int num_paths_shelved;
int num_paths_not_shelved;
svn_client_ctx_t *ctx;
};
/* A status callback function for printing STATUS for PATH. */
static svn_error_t *
print_status(void *baton,
const char *path,
const svn_client_status_t *status,
apr_pool_t *scratch_pool)
{
struct status_baton *sb = baton;
unsigned int conflicts;
return svn_cl__print_status(sb->target_abspath, sb->target_path,
path, status,
TRUE /*suppress_externals_placeholders*/,
FALSE /*detailed*/,
FALSE /*show_last_committed*/,
TRUE /*skip_unrecognized*/,
FALSE /*repos_locks*/,
&conflicts, &conflicts, &conflicts,
sb->ctx,
scratch_pool);
}
/* A callback function for shelved paths. */
static svn_error_t *
was_shelved(void *baton,
const char *path,
const svn_client_status_t *status,
apr_pool_t *scratch_pool)
{
struct status_baton *sb = baton;
if (!sb->quiet)
{
SVN_ERR(print_status(baton, path, status, scratch_pool));
}
++sb->num_paths_shelved;
return SVN_NO_ERROR;
}
/* A callback function for not-shelved paths. */
static svn_error_t *
was_not_shelved(void *baton,
const char *path,
const svn_client_status_t *status,
apr_pool_t *scratch_pool)
{
struct status_baton *sb = baton;
SVN_ERR(print_status(baton, path, status, scratch_pool));
SVN_ERR(svn_cmdline_printf(scratch_pool, " > not shelved\n"));
++sb->num_paths_not_shelved;
return SVN_NO_ERROR;
}
/** Shelve/save a new version of changes.
*
* Shelve in shelf @a name the local modifications found by @a paths,
* @a depth, @a changelists. Revert the shelved changes from the WC
* unless @a keep_local is true.
*
* If no local modifications are found, throw an error.
*
* If @a dry_run is true, don't actually do it.
*
* Report in @a *new_version_p the new version number (or, with dry run,
* what it would be).
*/
static svn_error_t *
shelve(int *new_version_p,
const char *name,
const apr_array_header_t *paths,
svn_depth_t depth,
const apr_array_header_t *changelists,
apr_hash_t *revprop_table,
svn_boolean_t keep_local,
svn_boolean_t dry_run,
svn_boolean_t quiet,
const char *local_abspath,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
svn_client__shelf_t *shelf;
svn_client__shelf_version_t *previous_version;
svn_client__shelf_version_t *new_version;
struct status_baton sb;
SVN_ERR(svn_client__shelf_open_or_create(&shelf,
name, local_abspath,
ctx, scratch_pool));
SVN_ERR(svn_client__shelf_get_newest_version(&previous_version, shelf,
scratch_pool, scratch_pool));
if (! quiet)
{
SVN_ERR(svn_cmdline_printf(scratch_pool, keep_local
? _("--- Save a new version of '%s' in WC root '%s'\n")
: _("--- Shelve '%s' in WC root '%s'\n"),
shelf->name, shelf->wc_root_abspath));
SVN_ERR(stats(shelf, shelf->max_version, previous_version, apr_time_now(),
TRUE /*with_logmsg*/, scratch_pool));
}
sb.target_abspath = shelf->wc_root_abspath;
sb.target_path = "";
sb.quiet = quiet;
sb.num_paths_shelved = 0;
sb.num_paths_not_shelved = 0;
sb.ctx = ctx;
if (! quiet)
SVN_ERR(svn_cmdline_printf(scratch_pool,
keep_local ? _("--- Saving...\n")
: _("--- Shelving...\n")));
SVN_ERR(svn_client__shelf_save_new_version3(&new_version, shelf,
paths, depth, changelists,
was_shelved, &sb,
was_not_shelved, &sb,
scratch_pool));
if (sb.num_paths_not_shelved > 0)
{
SVN_ERR(svn_client__shelf_delete_newer_versions(shelf, previous_version,
scratch_pool));
SVN_ERR(svn_client__shelf_close(shelf, scratch_pool));
return svn_error_createf(SVN_ERR_ILLEGAL_TARGET, NULL,
Q_("%d path could not be shelved",
"%d paths could not be shelved",
sb.num_paths_not_shelved),
sb.num_paths_not_shelved);
}
if (sb.num_paths_shelved == 0
|| ! new_version)
{
SVN_ERR(svn_client__shelf_close(shelf, scratch_pool));
return svn_error_createf(SVN_ERR_ILLEGAL_TARGET, NULL,
keep_local ? _("No local modifications could be saved")
: _("No local modifications could be shelved"));
}
/* Un-apply the changes, if required. */
if (!keep_local)
{
SVN_ERR(svn_client__shelf_unapply(new_version,
dry_run, scratch_pool));
}
/* Fetch the log message and any other revprops */
if (ctx->log_msg_func3)
{
const char *tmp_file;
apr_array_header_t *commit_items
= apr_array_make(scratch_pool, 1, sizeof(void *));
const char *message = "";
SVN_ERR(ctx->log_msg_func3(&message, &tmp_file, commit_items,
ctx->log_msg_baton3, scratch_pool));
/* Abort the shelving if the log message callback requested so. */
if (! message)
return SVN_NO_ERROR;
if (message && !dry_run)
{
svn_string_t *propval = svn_string_create(message, scratch_pool);
if (! revprop_table)
revprop_table = apr_hash_make(scratch_pool);
svn_hash_sets(revprop_table, SVN_PROP_REVISION_LOG, propval);
}
}
SVN_ERR(svn_client__shelf_revprop_set_all(shelf, revprop_table, scratch_pool));
if (new_version_p)
*new_version_p = shelf->max_version;
if (dry_run)
{
SVN_ERR(svn_client__shelf_delete_newer_versions(shelf, previous_version,
scratch_pool));
}
SVN_ERR(svn_client__shelf_close(shelf, scratch_pool));
return SVN_NO_ERROR;
}
/* Return the single character representation of STATUS.
* (Similar to subversion/svn/status.c:generate_status_code()
* and subversion/tests/libsvn_client/client-test.c:status_to_char().) */
static char
status_to_char(enum svn_wc_status_kind status)
{
switch (status)
{
case svn_wc_status_none: return '.';
case svn_wc_status_unversioned: return '?';
case svn_wc_status_normal: return ' ';
case svn_wc_status_added: return 'A';
case svn_wc_status_missing: return '!';
case svn_wc_status_deleted: return 'D';
case svn_wc_status_replaced: return 'R';
case svn_wc_status_modified: return 'M';
case svn_wc_status_merged: return 'G';
case svn_wc_status_conflicted: return 'C';
case svn_wc_status_ignored: return 'I';
case svn_wc_status_obstructed: return '~';
case svn_wc_status_external: return 'X';
case svn_wc_status_incomplete: return ':';
default: return '*';
}
}
/* Throw an error if any path affected by SHELF_VERSION gives a conflict
* when applied (as a dry-run) to the WC. */
static svn_error_t *
test_apply(svn_client__shelf_version_t *shelf_version,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
apr_hash_t *paths;
apr_hash_index_t *hi;
SVN_ERR(svn_client__shelf_paths_changed(&paths, shelf_version,
scratch_pool, scratch_pool));
for (hi = apr_hash_first(scratch_pool, paths); hi; hi = apr_hash_next(hi))
{
const char *path = apr_hash_this_key(hi);
svn_boolean_t conflict;
SVN_ERR(svn_client__shelf_test_apply_file(&conflict, shelf_version, path,
scratch_pool));
if (conflict)
{
char *to_wc_abspath
= svn_dirent_join(shelf_version->shelf->wc_root_abspath, path,
scratch_pool);
svn_wc_status3_t *status;
SVN_ERR(svn_wc_status3(&status, ctx->wc_ctx, to_wc_abspath,
scratch_pool, scratch_pool));
return svn_error_createf(SVN_ERR_ILLEGAL_TARGET, NULL,
_("Shelved path '%s' already has "
"status '%c' in the working copy"),
path, status_to_char(status->node_status));
}
}
return SVN_NO_ERROR;
}
/** Restore/unshelve a given or newest version of changes.
*
* Restore local modifications from shelf @a name version @a arg,
* or the newest version is @a arg is null.
*
* If @a dry_run is true, don't actually do it.
*
* Error if any path would have a conflict, unless @a force_if_conflict.
*/
static svn_error_t *
shelf_restore(const char *name,
const char *arg,
svn_boolean_t dry_run,
svn_boolean_t quiet,
svn_boolean_t force_if_conflict,
const char *local_abspath,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
int version, old_version;
apr_time_t time_now = apr_time_now();
svn_client__shelf_t *shelf;
svn_client__shelf_version_t *shelf_version;
SVN_ERR(svn_client__shelf_open_existing(&shelf, name, local_abspath,
ctx, scratch_pool));
old_version = shelf->max_version;
if (arg)
{
SVN_ERR(svn_cstring_atoi(&version, arg));
SVN_ERR(svn_client__shelf_version_open(&shelf_version,
shelf, version,
scratch_pool, scratch_pool));
}
else
{
version = shelf->max_version;
SVN_ERR(get_newest_version_existing(&shelf_version, shelf,
scratch_pool, scratch_pool));
}
if (! quiet)
{
SVN_ERR(svn_cmdline_printf(scratch_pool,
_("--- Unshelve '%s' in WC root '%s'\n"),
shelf->name, shelf->wc_root_abspath));
SVN_ERR(stats(shelf, version, shelf_version, time_now,
TRUE /*with_logmsg*/, scratch_pool));
}
if (! force_if_conflict)
{
SVN_ERR_W(test_apply(shelf_version, ctx, scratch_pool),
_("Cannot unshelve/restore, as at least one shelved "
"path would conflict with a local modification "
"or other status in the working copy"));
}
SVN_ERR(svn_client__shelf_apply(shelf_version,
dry_run, scratch_pool));
if (! dry_run)
{
SVN_ERR(svn_client__shelf_delete_newer_versions(shelf, shelf_version,
scratch_pool));
}
if (!quiet)
{
if (version < old_version)
SVN_ERR(svn_cmdline_printf(scratch_pool,
Q_("restored '%s' version %d and deleted %d newer version\n",
"restored '%s' version %d and deleted %d newer versions\n",
old_version - version),
name, version, old_version - version));
else
SVN_ERR(svn_cmdline_printf(scratch_pool,
_("restored '%s' version %d (the newest version)\n"),
name, version));
}
SVN_ERR(svn_client__shelf_close(shelf, scratch_pool));
return SVN_NO_ERROR;
}
static svn_error_t *
shelf_diff(const char *name,
const char *arg,
const char *local_abspath,
svn_boolean_t summarize,
svn_depth_t depth,
svn_boolean_t ignore_ancestry,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
svn_client__shelf_t *shelf;
svn_client__shelf_version_t *shelf_version;
svn_stream_t *stream, *errstream;
svn_diff_tree_processor_t *diff_processor;
SVN_ERR(svn_client__shelf_open_existing(&shelf, name, local_abspath,
ctx, scratch_pool));
if (arg)
{
int version;
SVN_ERR(svn_cstring_atoi(&version, arg));
SVN_ERR(svn_client__shelf_version_open(&shelf_version,
shelf, version,
scratch_pool, scratch_pool));
}
else
{
SVN_ERR(get_newest_version_existing(&shelf_version, shelf,
scratch_pool, scratch_pool));
}
SVN_ERR(svn_stream_for_stdout(&stream, scratch_pool));
errstream = svn_stream_empty(scratch_pool);
if (summarize)
{
svn_client_diff_summarize_func_t func;
void *baton;
SVN_ERR(svn_cl__get_diff_summary_writer(&func, &baton,
FALSE /*xml*/,
FALSE /*ignore_properties*/,
"" /*anchor/prefix*/,
scratch_pool, scratch_pool));
SVN_ERR(svn_client__get_diff_summarize_callbacks(&diff_processor,
func, baton,
scratch_pool,
scratch_pool));
}
else
{
SVN_ERR(svn_client__get_diff_writer_svn(
&diff_processor,
NULL /*anchor*/,
"", "", /*orig_path_1, orig_path_2,*/
NULL /*options*/,
"" /*relative_to_dir*/,
FALSE /*no_diff_added*/,
FALSE /*no_diff_deleted*/,
FALSE /*show_copies_as_adds*/,
FALSE /*ignore_content_type*/,
FALSE /*ignore_properties*/,
FALSE /*properties_only*/,
TRUE /*pretty_print_mergeinfo*/,
svn_cmdline_output_encoding(scratch_pool),
stream, errstream,
ctx, scratch_pool));
}
SVN_ERR(svn_client__shelf_diff(shelf_version, "",
depth, ignore_ancestry,
diff_processor, scratch_pool));
SVN_ERR(svn_stream_close(stream));
SVN_ERR(svn_client__shelf_close(shelf, scratch_pool));
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
static svn_error_t *
shelf_drop(const char *name,
const char *local_abspath,
svn_boolean_t dry_run,
svn_boolean_t quiet,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
SVN_ERR(svn_client__shelf_delete(name, local_abspath, dry_run,
ctx, scratch_pool));
if (! quiet)
SVN_ERR(svn_cmdline_printf(scratch_pool,
_("deleted '%s'\n"),
name));
return SVN_NO_ERROR;
}
/* */
static svn_error_t *
shelf_shelve(int *new_version,
const char *name,
apr_array_header_t *targets,
svn_depth_t depth,
apr_array_header_t *changelists,
apr_hash_t *revprop_table,
svn_boolean_t keep_local,
svn_boolean_t dry_run,
svn_boolean_t quiet,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
const char *local_abspath;
if (depth == svn_depth_unknown)
depth = svn_depth_infinity;
SVN_ERR(svn_cl__check_targets_are_local_paths(targets));
SVN_ERR(svn_cl__eat_peg_revisions(&targets, targets, scratch_pool));
svn_opt_push_implicit_dot_target(targets, scratch_pool);
/* ### TODO: check all paths are in same WC; for now use first path */
SVN_ERR(svn_dirent_get_absolute(&local_abspath,
APR_ARRAY_IDX(targets, 0, char *),
scratch_pool));
SVN_ERR(shelve(new_version, name,
targets, depth, changelists,
revprop_table,
keep_local, dry_run, quiet,
local_abspath, ctx, scratch_pool));
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_save(apr_getopt_t *os,
void *baton,
apr_pool_t *pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
opt_state->keep_local = TRUE;
SVN_ERR(svn_cl__shelf_shelve(os, baton, pool));
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_shelve(apr_getopt_t *os,
void *baton,
apr_pool_t *pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx;
const char *name;
apr_array_header_t *targets;
if (opt_state->quiet)
ctx->notify_func2 = NULL; /* Easy out: avoid unneeded work */
SVN_ERR(get_next_argument(&name, os, pool, pool));
/* Parse the remaining arguments as paths. */
SVN_ERR(svn_cl__args_to_target_array_print_reserved(&targets, os,
opt_state->targets,
ctx, FALSE, pool));
{
int new_version;
svn_error_t *err;
if (ctx->log_msg_func3)
SVN_ERR(svn_cl__make_log_msg_baton(&ctx->log_msg_baton3,
opt_state, NULL, ctx->config,
pool));
err = shelf_shelve(&new_version, name,
targets, opt_state->depth, opt_state->changelists,
opt_state->revprop_table,
opt_state->keep_local, opt_state->dry_run,
opt_state->quiet, ctx, pool);
if (ctx->log_msg_func3)
SVN_ERR(svn_cl__cleanup_log_msg(ctx->log_msg_baton3,
err, pool));
else
SVN_ERR(err);
if (! opt_state->quiet)
{
if (opt_state->keep_local)
SVN_ERR(svn_cmdline_printf(pool,
_("saved '%s' version %d\n"),
name, new_version));
else
SVN_ERR(svn_cmdline_printf(pool,
_("shelved '%s' version %d\n"),
name, new_version));
}
}
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_unshelve(apr_getopt_t *os,
void *baton,
apr_pool_t *scratch_pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx;
const char *local_abspath;
const char *name;
const char *arg = NULL;
SVN_ERR(svn_dirent_get_absolute(&local_abspath, "", scratch_pool));
if (os->ind < os->argc)
{
SVN_ERR(get_next_argument(&name, os, scratch_pool, scratch_pool));
}
else
{
SVN_ERR(name_of_youngest(&name,
local_abspath, ctx, scratch_pool, scratch_pool));
SVN_ERR(svn_cmdline_printf(scratch_pool,
_("unshelving the youngest shelf, '%s'\n"),
name));
}
/* Which checkpoint number? */
if (os->ind < os->argc)
SVN_ERR(get_next_argument(&arg, os, scratch_pool, scratch_pool));
if (os->ind < os->argc)
return svn_error_create(SVN_ERR_CL_ARG_PARSING_ERROR, NULL,
_("Too many arguments"));
if (opt_state->quiet)
ctx->notify_func2 = NULL; /* Easy out: avoid unneeded work */
SVN_ERR(shelf_restore(name, arg,
opt_state->dry_run, opt_state->quiet,
opt_state->force /*force_already_modified*/,
local_abspath, ctx, scratch_pool));
if (opt_state->drop)
{
SVN_ERR(shelf_drop(name, local_abspath,
opt_state->dry_run, opt_state->quiet,
ctx, scratch_pool));
}
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_list(apr_getopt_t *os,
void *baton,
apr_pool_t *pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx;
apr_array_header_t *targets = NULL;
apr_pool_t *iterpool = svn_pool_create(pool);
int i;
SVN_ERR(svn_cl__args_to_target_array_print_reserved(&targets, os,
opt_state->targets,
ctx, FALSE, pool));
/* Add "." if user passed 0 arguments */
svn_opt_push_implicit_dot_target(targets, pool);
for (i = 0; i < targets->nelts; ++i)
{
const char *local_abspath;
const char *target = APR_ARRAY_IDX(targets, i, const char *);
svn_pool_clear(iterpool);
SVN_ERR(svn_dirent_get_absolute(&local_abspath, target, iterpool));
SVN_ERR(shelves_list(local_abspath,
opt_state->quiet,
ctx, iterpool));
}
svn_pool_destroy(iterpool);
return SVN_NO_ERROR;
}
/* "svn shelf-list-by-paths [PATH...]"
*
* TARGET_RELPATHS are all within the same WC, relative to WC_ROOT_ABSPATH.
*/
static svn_error_t *
shelf_list_by_paths(apr_array_header_t *target_relpaths,
const char *wc_root_abspath,
svn_client_ctx_t *ctx,
apr_pool_t *scratch_pool)
{
apr_array_header_t *shelves;
apr_hash_t *paths_to_shelf_name = apr_hash_make(scratch_pool);
apr_array_header_t *array;
int i;
SVN_ERR(list_sorted_by_date(&shelves,
wc_root_abspath, ctx, scratch_pool));
/* Check paths are valid */
for (i = 0; i < target_relpaths->nelts; i++)
{
char *target_relpath = APR_ARRAY_IDX(target_relpaths, i, char *);
if (svn_path_is_url(target_relpath))
return svn_error_createf(SVN_ERR_ILLEGAL_TARGET, NULL,
_("'%s' is not a local path"), target_relpath);
SVN_ERR_ASSERT(svn_relpath_is_canonical(target_relpath));
}
/* Find the most recent shelf for each affected path */
for (i = 0; i < shelves->nelts; i++)
{
svn_sort__item_t *item = &APR_ARRAY_IDX(shelves, i, svn_sort__item_t);
const char *name = item->key;
svn_client__shelf_t *shelf;
svn_client__shelf_version_t *shelf_version;
apr_hash_t *shelf_paths;
int j;
SVN_ERR(svn_client__shelf_open_existing(&shelf,
name, wc_root_abspath,
ctx, scratch_pool));
SVN_ERR(svn_client__shelf_get_newest_version(&shelf_version, shelf,
scratch_pool, scratch_pool));
if (!shelf_version)
continue;
SVN_ERR(svn_client__shelf_paths_changed(&shelf_paths,
shelf_version,
scratch_pool, scratch_pool));
for (j = 0; j < target_relpaths->nelts; j++)
{
char *target_relpath = APR_ARRAY_IDX(target_relpaths, j, char *);
apr_hash_index_t *hi;
for (hi = apr_hash_first(scratch_pool, shelf_paths);
hi; hi = apr_hash_next(hi))
{
const char *shelf_path = apr_hash_this_key(hi);
if (svn_relpath_skip_ancestor(target_relpath, shelf_path))
{
if (! svn_hash_gets(paths_to_shelf_name, shelf_path))
{
svn_hash_sets(paths_to_shelf_name, shelf_path, shelf->name);
}
}
}
}
}
/* Print the results. */
array = svn_sort__hash(paths_to_shelf_name,
svn_sort_compare_items_as_paths,
scratch_pool);
for (i = 0; i < array->nelts; i++)
{
svn_sort__item_t *item = &APR_ARRAY_IDX(array, i, svn_sort__item_t);
const char *path = item->key;
const char *name = item->value;
SVN_ERR(svn_cmdline_printf(scratch_pool, "%-20.20s %s\n",
name,
svn_dirent_local_style(path, scratch_pool)));
}
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_list_by_paths(apr_getopt_t *os,
void *baton,
apr_pool_t *pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx;
const char *wc_root_abspath;
apr_array_header_t *targets;
/* Parse the remaining arguments as paths. */
SVN_ERR(targets_relative_to_a_wc(&wc_root_abspath, &targets,
os, opt_state->targets,
ctx, pool, pool));
SVN_ERR(shelf_list_by_paths(targets, wc_root_abspath, ctx, pool));
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_diff(apr_getopt_t *os,
void *baton,
apr_pool_t *pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx;
const char *local_abspath;
const char *name;
const char *arg = NULL;
SVN_ERR(svn_dirent_get_absolute(&local_abspath, "", pool));
SVN_ERR(get_next_argument(&name, os, pool, pool));
/* Which checkpoint number? */
if (os->ind < os->argc)
SVN_ERR(get_next_argument(&arg, os, pool, pool));
if (os->ind < os->argc)
return svn_error_create(SVN_ERR_CL_ARG_PARSING_ERROR, NULL,
_("Too many arguments"));
SVN_ERR(shelf_diff(name, arg, local_abspath,
opt_state->diff.summarize,
opt_state->depth, opt_state->ignore_ancestry,
ctx, pool));
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_drop(apr_getopt_t *os,
void *baton,
apr_pool_t *pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx;
const char *name;
apr_array_header_t *targets = NULL;
apr_pool_t *iterpool = svn_pool_create(pool);
int i;
SVN_ERR(get_next_argument(&name, os, pool, pool));
SVN_ERR(svn_cl__args_to_target_array_print_reserved(&targets, os,
opt_state->targets,
ctx, FALSE, pool));
svn_opt_push_implicit_dot_target(targets, pool);
for (i = 0; i < targets->nelts; ++i)
{
const char *local_abspath;
const char *target = APR_ARRAY_IDX(targets, i, const char *);
svn_pool_clear(iterpool);
SVN_ERR(svn_dirent_get_absolute(&local_abspath, target, iterpool));
SVN_ERR(shelf_drop(name, local_abspath,
opt_state->dry_run, opt_state->quiet,
ctx, iterpool));
}
svn_pool_destroy(iterpool);
return SVN_NO_ERROR;
}
/* This implements the `svn_opt_subcommand_t' interface. */
svn_error_t *
svn_cl__shelf_log(apr_getopt_t *os,
void *baton,
apr_pool_t *pool)
{
svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state;
svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx;
const char *name;
apr_array_header_t *targets = NULL;
apr_pool_t *iterpool = svn_pool_create(pool);
int i;
SVN_ERR(get_next_argument(&name, os, pool, pool));
SVN_ERR(svn_cl__args_to_target_array_print_reserved(&targets, os,
opt_state->targets,
ctx, FALSE, pool));
svn_opt_push_implicit_dot_target(targets, pool);
for (i = 0; i < targets->nelts; ++i)
{
const char *local_abspath;
const char *target = APR_ARRAY_IDX(targets, i, const char *);
svn_pool_clear(iterpool);
SVN_ERR(svn_dirent_get_absolute(&local_abspath, target, iterpool));
SVN_ERR(shelf_log(name, local_abspath, ctx, iterpool));
}
svn_pool_destroy(iterpool);
return SVN_NO_ERROR;
}
| 34.454545 | 97 | 0.583401 |
63d1828c035fde813a9542d61c8ebad8c70c6147 | 382 | h | C | QiuShengKe-ios/QiuShengKe-ios/Common/QiuMiCommonWebViewController/WKCookieSyncManager.h | bjbjbjbj/qiushengke_ios | 1703edc3c70818fe7e0ca613666971e2d627ee56 | [
"Apache-2.0"
] | null | null | null | QiuShengKe-ios/QiuShengKe-ios/Common/QiuMiCommonWebViewController/WKCookieSyncManager.h | bjbjbjbj/qiushengke_ios | 1703edc3c70818fe7e0ca613666971e2d627ee56 | [
"Apache-2.0"
] | null | null | null | QiuShengKe-ios/QiuShengKe-ios/Common/QiuMiCommonWebViewController/WKCookieSyncManager.h | bjbjbjbj/qiushengke_ios | 1703edc3c70818fe7e0ca613666971e2d627ee56 | [
"Apache-2.0"
] | null | null | null | //
// WKCookieSyncManager.h
// shoes
//
// Created by 奉强 on 16/4/5.
// Copyright © 2016年 saygogo. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
@interface WKCookieSyncManager : NSObject
@property (nonatomic, strong) WKProcessPool *processPool;
- (void)setCookie;
- (void)cleanCookies;
+ (instancetype)sharedWKCookieSyncManager;
@end
| 16.608696 | 57 | 0.727749 |
63dea69dac8b369212672511584e70dbbfc8fdf7 | 1,649 | h | C | src/mongo/bson/mutable/document-inl.h | harishd10/mongodb | 69dd944e2e7cac2a3f56c99f2a20d45651b8db24 | [
"Apache-2.0"
] | 24 | 2015-10-15T00:03:57.000Z | 2021-04-25T18:21:31.000Z | src/mongo/bson/mutable/document-inl.h | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | 1 | 2015-06-02T12:19:19.000Z | 2015-06-02T12:19:19.000Z | src/mongo/bson/mutable/document-inl.h | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | 3 | 2017-07-26T11:17:11.000Z | 2021-11-30T00:11:32.000Z | /* Copyright 2013 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace mongo {
namespace mutablebson {
inline int Document::compareWith(const Document& other, bool considerFieldName) const {
// We cheat and use Element::compareWithElement since we know that 'other' is a
// Document and has a 'hidden' fieldname that is always indentical across all Document
// instances.
return root().compareWithElement(other.root(), considerFieldName);
}
inline int Document::compareWithBSONObj(const BSONObj& other, bool considerFieldName) const {
return root().compareWithBSONObj(other, considerFieldName);
}
inline void Document::writeTo(BSONObjBuilder* builder) const {
return root().writeTo(builder);
}
inline BSONObj Document::getObject() const {
BSONObjBuilder builder;
writeTo(&builder);
return builder.obj();
}
inline Element Document::root() {
return _root;
}
inline ConstElement Document::root() const {
return _root;
}
} // namespace mutablebson
} // namespace mongo
| 31.711538 | 97 | 0.697999 |
7632604dcc1b1983e1239c2848149f3b6d5520e0 | 1,513 | c | C | assets/images/SawBlade/Binary/SawBlade.c | VUEngine/VUEngine-Platformer-Demo | 90b249ba9a8c281a455b9919eef462d8076d111f | [
"MIT"
] | 2 | 2021-01-09T19:24:07.000Z | 2021-09-02T04:31:52.000Z | assets/images/SawBlade/Binary/SawBlade.c | VUEngine/VUEngine-Platformer-Demo | 90b249ba9a8c281a455b9919eef462d8076d111f | [
"MIT"
] | null | null | null | assets/images/SawBlade/Binary/SawBlade.c | VUEngine/VUEngine-Platformer-Demo | 90b249ba9a8c281a455b9919eef462d8076d111f | [
"MIT"
] | null | null | null |
//{{BLOCK(SawBlade)
//======================================================================
//
// SawBlade, 24x48@2,
// + 18 tiles not compressed
// + regular map (flat), not compressed, 3x6
// Total size: 304 + 36 = 340
//
// Exported by Cearn's GBA Image Transmogrifier, v0.8.6
// ( http://www.coranac.com/projects/#grit )
//
//======================================================================
const unsigned int SawBladeTiles[76] __attribute__((aligned(4)))=
{
0x00000000,0xDF404500,0x7FF4FFD0,0xA7D09FF4,
0x5FFD0554,0xFFFF5FFD,0x5AA9F557,0xAAAAAAAA,0x00000000,0x007D0014,0x07FF01FF,0x01F607FD,
0x69FDABD4,0xAAFD6AFD,0xAAFDAAFD,0xABD0ABD4,0x5AA9AAAA,0x96A556A5,0xAAAAAAAA,0xAAAAAAAA,
0x1FDA05FA,0x1FEA1FEA,0x1FEA1FEA,0x01FA05FA,0xBFF4AFF4,0xDF40FFD0,0x00004500,0x00000000,
0xAAAAAAAA,0xFFFFFAAB,0x1FFD5FFD,0x00000554,0x07FF07FE,0x007D01FF,0x00000014,0x00000000,
0xD4004000,0xFD00FD00,0x7DD0F440,0xA7FD9FF4,0xF5575001,0xFFFFFFFF,0x5AA9F557,0xAAAAAAAA,
0x00050000,0x001F001F,0x01DF0047,0x1FF607FD,0x69F4ABFD,0xAAF46AF4,0xAAF4AAF4,0xABFDABFD,
0x5AA9AAAA,0x96A556A5,0xAAAAAAAA,0xAAAAAAAA,0x07DA1FFA,0x07EA07EA,0x07EA07EA,0x1FFA1FFA,
0xBDD0AFF4,0xFD00F440,0xD400FD00,0x00004000,0xAAAAAAAA,0xFFFFFAAB,0xF557FFFF,0x00005001,
0x01DF07FE,0x001F0047,0x0005001F,0x00000000,
};
const unsigned short SawBladeMap[18] __attribute__((aligned(4)))=
{
0x0000,0x0001,0x0002,0x0003,0x0004,0x0005,0x0006,0x0007,
0x0008,0x0009,0x000a,0x000b,0x000c,0x000d,0x000e,0x000f,
0x0010,0x0011,
};
//}}BLOCK(SawBlade) | 38.794872 | 89 | 0.733642 |
9dd45bc903e5448d52b5ca1b7f0a6632a0c52dfd | 1,052 | h | C | Mutex.h | bgroff/tcp-light | 7f722c46233d0f7d3f7a16bd04410b98463e553c | [
"MIT"
] | 1 | 2019-04-16T03:38:06.000Z | 2019-04-16T03:38:06.000Z | Mutex.h | bgroff/tcp-light | 7f722c46233d0f7d3f7a16bd04410b98463e553c | [
"MIT"
] | null | null | null | Mutex.h | bgroff/tcp-light | 7f722c46233d0f7d3f7a16bd04410b98463e553c | [
"MIT"
] | null | null | null | /*
* File: Mutex.h
* Class: ICS 451
* Project #: 3
* Team Members: Bryce Groff, Brandon Grant, Emiliano Miranda
* Author: Bryce Groff
* Created Date: 04-19-09
* Desc: Represents a Lock.
*/
#ifndef _MUTEX_H_
#define _MUTEX_H_
#include <pthread.h>
#include <inttypes.h>
#include <time.h>
/*! \class Mutex
\brief Wrapper around pthread locks.
Mutex gives a wrapper around the pthread mutual exclusion mechanism.
*/
class Mutex {
public:
Mutex();
Mutex(int type);
~Mutex();
int Lock(); //!< Locks this lock.
int TryLock(); //!< Tries to lock this lock. If 0 is returned, then the lock is required; otherwise, an error number is returned.
int Unlock(); //!< Unlocks this lock.
int TimedWait(timespec &); //!< Waits for timespec amount of time then timesout
int Wait(); //!< Waits until signaled
int Signal(); //!< Signals the condition variable to continue.
private:
pthread_mutex_t mLock;
pthread_cond_t mCond;
pthread_mutexattr_t mAttr;
};
#endif
| 25.658537 | 135 | 0.64924 |
6fe6439f3ed8f2c70891afb6c164ead5aa0fd892 | 2,966 | h | C | src/array.h | Giridharsalana/gdstk | 3f60be2439922eba919350d5f566fa5e98a4acd6 | [
"BSL-1.0"
] | 1 | 2021-04-12T17:05:45.000Z | 2021-04-12T17:05:45.000Z | src/array.h | Giridharsalana/gdstk | 3f60be2439922eba919350d5f566fa5e98a4acd6 | [
"BSL-1.0"
] | null | null | null | src/array.h | Giridharsalana/gdstk | 3f60be2439922eba919350d5f566fa5e98a4acd6 | [
"BSL-1.0"
] | null | null | null | /*
Copyright 2020-2020 Lucas Heitzmann Gabrielli.
This file is part of gdstk, distributed under the terms of the
Boost Software License - Version 1.0. See the accompanying
LICENSE file or <http://www.boost.org/LICENSE_1_0.txt>
*/
#define _USE_MATH_DEFINES
#ifndef __ARRAY_H__
#define __ARRAY_H__
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "vec.h"
namespace gdstk {
template <class T>
struct Array {
int64_t capacity; // allocated capacity
int64_t size; // number of slots used
T* items; // slots
T& operator[](int64_t idx) { return items[idx]; }
const T& operator[](int64_t idx) const { return items[idx]; }
void print(bool all) const {
const int64_t n = 6;
printf("Array <%p>, size %" PRId64 "/%" PRId64 "\n", this, size, capacity);
if (all) {
for (int64_t i = 0; i < size; i += n) {
for (int64_t j = 0; j < n && i + j < size; j++) {
if (j > 0) printf(" ");
printf("<%p>", items[i + j]);
}
printf("\n");
}
}
}
void clear() {
if (items) free(items);
items = NULL;
capacity = 0;
size = 0;
}
int64_t index(const T item) const {
T* it = items;
for (int64_t j = 0; j < size; j++)
if (*(it++) == item) return j;
return -1;
}
void append(T item) {
if (size == capacity) {
capacity += capacity > 0 ? capacity : 4;
items = (T*)realloc(items, sizeof(T) * capacity);
}
items[size++] = item;
}
void remove_unordered(int64_t index) { items[index] = items[--size]; }
void remove(int64_t index) {
memmove(items + index, items + index + 1, sizeof(T) * ((--size) - index));
}
void ensure_slots(int64_t free_slots) {
if (capacity < size + free_slots) {
capacity = size + free_slots;
items = (T*)realloc(items, sizeof(T) * capacity);
}
}
void extend(const Array<T>& src) {
ensure_slots(src.size);
memcpy(items + size, src.items, sizeof(T) * src.size);
size += src.size;
}
void copy_from(const Array<T>& src) {
capacity = src.capacity;
size = src.size;
items = (T*)malloc(sizeof(T) * capacity);
memcpy(items, src.items, sizeof(T) * src.size);
}
};
template <>
inline void Array<Vec2>::print(bool all) const {
const int64_t n = 6;
printf("Array <%p>, size %" PRId64 "/%" PRId64 "\n", this, size, capacity);
if (all) {
for (int64_t i = 0; i < size; i += n) {
for (int64_t j = 0; j < n && i + j < size; j++) {
if (j > 0) printf(" ");
printf("(%lg, %lg)", items[i + j].x, items[i + j].y);
}
printf("\n");
}
}
}
} // namespace gdstk
#endif
| 26.247788 | 83 | 0.516183 |
e48cf4d1901e9ac82a2beef6713f3bf7d8a17f59 | 1,171 | h | C | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Input.PointerLeftArgs.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Input.PointerLeftArgs.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Input.PointerLeftArgs.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | // This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.9.0/Input/PointerEvents.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Input.PointerEventArgs.h>
#include <Fuse.Scripting.IScriptEvent.h>
namespace g{namespace Fuse{namespace Input{struct PointerEventData;}}}
namespace g{namespace Fuse{namespace Input{struct PointerLeftArgs;}}}
namespace g{namespace Fuse{struct Visual;}}
namespace g{
namespace Fuse{
namespace Input{
// public sealed class PointerLeftArgs :94
// {
::g::Fuse::VisualEventArgs_type* PointerLeftArgs_typeof();
void PointerLeftArgs__ctor_3_fn(PointerLeftArgs* __this, ::g::Fuse::Input::PointerEventData* data, ::g::Fuse::Visual* visual);
void PointerLeftArgs__New3_fn(::g::Fuse::Input::PointerEventData* data, ::g::Fuse::Visual* visual, PointerLeftArgs** __retval);
struct PointerLeftArgs : ::g::Fuse::Input::PointerEventArgs
{
void ctor_3(::g::Fuse::Input::PointerEventData* data, ::g::Fuse::Visual* visual);
static PointerLeftArgs* New3(::g::Fuse::Input::PointerEventData* data, ::g::Fuse::Visual* visual);
};
// }
}}} // ::g::Fuse::Input
| 40.37931 | 128 | 0.752348 |
f20cb4db678ccb1a17c4c30fe3af6eadcf61e8aa | 4,416 | c | C | Archive/nrf5_gcc_mesh/mesh/core/src/event.c | aberke/city-science-bike-swarm | 797e803014fc0c3878016309a62460a736140958 | [
"MIT"
] | 15 | 2019-02-25T20:25:29.000Z | 2021-02-27T17:57:38.000Z | nrf5_mesh/mesh/core/src/event.c | aberke/city-science-bike-swarm | 797e803014fc0c3878016309a62460a736140958 | [
"MIT"
] | 3 | 2020-02-21T22:35:38.000Z | 2020-10-05T02:25:30.000Z | nrf5_mesh/mesh/core/src/event.c | aberke/city-science-bike-swarm | 797e803014fc0c3878016309a62460a736140958 | [
"MIT"
] | 5 | 2019-06-29T21:03:57.000Z | 2021-06-15T06:16:20.000Z | /* Copyright (c) 2010 - 2020, Nordic Semiconductor ASA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, 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 Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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 <nrf_error.h>
#include "event.h"
#include "list.h"
#include "utils.h"
typedef enum
{
EVENT_HANDLER_IDLE,
EVENT_HANDLER_PROCEEDING,
EVENT_HANDLER_CLEANING_REQUIRED,
} event_handler_state_t;
/** Linked list of event handlers */
static list_node_t * mp_evt_handlers_head;
static event_handler_state_t m_event_handler_state = EVENT_HANDLER_IDLE;
static void event_list_clean(void)
{
list_node_t * p_item = mp_evt_handlers_head;
while (p_item != NULL)
{
nrf_mesh_evt_handler_t * p_handler = PARENT_BY_FIELD_GET(nrf_mesh_evt_handler_t,
node,
p_item);
list_node_t * p_next = p_item->p_next;
if (p_handler->is_removed)
{
(void) list_remove(&mp_evt_handlers_head, p_item);
}
p_item = p_next;
}
}
void event_handle(const nrf_mesh_evt_t * p_evt)
{
NRF_MESH_ASSERT(p_evt != NULL);
if (mp_evt_handlers_head != NULL)
{
m_event_handler_state = EVENT_HANDLER_PROCEEDING;
LIST_FOREACH(p_node, mp_evt_handlers_head)
{
nrf_mesh_evt_handler_t * p_handler = PARENT_BY_FIELD_GET(nrf_mesh_evt_handler_t,
node,
p_node);
if (!p_handler->is_removed)
{
p_handler->evt_cb(p_evt);
}
}
if (EVENT_HANDLER_CLEANING_REQUIRED == m_event_handler_state)
{
event_list_clean();
}
m_event_handler_state = EVENT_HANDLER_IDLE;
}
}
void event_handler_add(nrf_mesh_evt_handler_t * p_handler_params)
{
NRF_MESH_ASSERT(p_handler_params != NULL);
p_handler_params->is_removed = false;
list_add(&mp_evt_handlers_head, &p_handler_params->node);
}
void event_handler_remove(nrf_mesh_evt_handler_t * p_handler_params)
{
NRF_MESH_ASSERT(p_handler_params != NULL);
if (EVENT_HANDLER_PROCEEDING == m_event_handler_state || EVENT_HANDLER_CLEANING_REQUIRED == m_event_handler_state)
{
m_event_handler_state = EVENT_HANDLER_CLEANING_REQUIRED;
p_handler_params->is_removed = true;
}
else
{
(void) list_remove(&mp_evt_handlers_head, &p_handler_params->node);
}
}
| 37.423729 | 118 | 0.682518 |
53f760378e3959b657e19693260665e048b85f46 | 3,399 | h | C | include/xen/interface/features.h | Sunrisepeak/Linux2.6-Reading | c25102a494a37f9f30a27ca2cd4a1a412bffc80f | [
"MIT"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | include/xen/interface/features.h | Sunrisepeak/Linux2.6-Reading | c25102a494a37f9f30a27ca2cd4a1a412bffc80f | [
"MIT"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | include/xen/interface/features.h | Sunrisepeak/Linux2.6-Reading | c25102a494a37f9f30a27ca2cd4a1a412bffc80f | [
"MIT"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /* SPDX-License-Identifier: MIT */
/******************************************************************************
* features.h
*
* Feature flags, reported by XENVER_get_features.
*
* Copyright (c) 2006, Keir Fraser <keir@xensource.com>
*/
#ifndef __XEN_PUBLIC_FEATURES_H__
#define __XEN_PUBLIC_FEATURES_H__
/*
* If set, the guest does not need to write-protect its pagetables, and can
* update them via direct writes.
*/
#define XENFEAT_writable_page_tables 0
/*
* If set, the guest does not need to write-protect its segment descriptor
* tables, and can update them via direct writes.
*/
#define XENFEAT_writable_descriptor_tables 1
/*
* If set, translation between the guest's 'pseudo-physical' address space
* and the host's machine address space are handled by the hypervisor. In this
* mode the guest does not need to perform phys-to/from-machine translations
* when performing page table operations.
*/
#define XENFEAT_auto_translated_physmap 2
/* If set, the guest is running in supervisor mode (e.g., x86 ring 0). */
#define XENFEAT_supervisor_mode_kernel 3
/*
* If set, the guest does not need to allocate x86 PAE page directories
* below 4GB. This flag is usually implied by auto_translated_physmap.
*/
#define XENFEAT_pae_pgdir_above_4gb 4
/* x86: Does this Xen host support the MMU_PT_UPDATE_PRESERVE_AD hypercall? */
#define XENFEAT_mmu_pt_update_preserve_ad 5
/* x86: Does this Xen host support the MMU_{CLEAR,COPY}_PAGE hypercall? */
#define XENFEAT_highmem_assist 6
/*
* If set, GNTTABOP_map_grant_ref honors flags to be placed into guest kernel
* available pte bits.
*/
#define XENFEAT_gnttab_map_avail_bits 7
/* x86: Does this Xen host support the HVM callback vector type? */
#define XENFEAT_hvm_callback_vector 8
/* x86: pvclock algorithm is safe to use on HVM */
#define XENFEAT_hvm_safe_pvclock 9
/* x86: pirq can be used by HVM guests */
#define XENFEAT_hvm_pirqs 10
/* operation as Dom0 is supported */
#define XENFEAT_dom0 11
/* Xen also maps grant references at pfn = mfn.
* This feature flag is deprecated and should not be used.
#define XENFEAT_grant_map_identity 12
*/
/* Guest can use XENMEMF_vnode to specify virtual node for memory op. */
#define XENFEAT_memory_op_vnode_supported 13
/* arm: Hypervisor supports ARM SMC calling convention. */
#define XENFEAT_ARM_SMCCC_supported 14
/*
* x86/PVH: If set, ACPI RSDP can be placed at any address. Otherwise RSDP
* must be located in lower 1MB, as required by ACPI Specification for IA-PC
* systems.
* This feature flag is only consulted if XEN_ELFNOTE_GUEST_OS contains
* the "linux" string.
*/
#define XENFEAT_linux_rsdp_unrestricted 15
/*
* A direct-mapped (or 1:1 mapped) domain is a domain for which its
* local pages have gfn == mfn. If a domain is direct-mapped,
* XENFEAT_direct_mapped is set; otherwise XENFEAT_not_direct_mapped
* is set.
*
* If neither flag is set (e.g. older Xen releases) the assumptions are:
* - not auto_translated domains (x86 only) are always direct-mapped
* - on x86, auto_translated domains are not direct-mapped
* - on ARM, Dom0 is direct-mapped, DomUs are not
*/
#define XENFEAT_not_direct_mapped 16
#define XENFEAT_direct_mapped 17
#define XENFEAT_NR_SUBMAPS 1
#endif /* __XEN_PUBLIC_FEATURES_H__ */
| 33 | 79 | 0.717858 |
991fbac99c0b8f285038072e36a279315dbc3964 | 4,141 | c | C | jni/guacd/libguac/client-handlers.c | maqiangddb/AndroidVncServer | 3bd4414ff4a84cd7407493364078dc4d77d4e5ad | [
"MIT"
] | 2 | 2016-05-26T06:54:21.000Z | 2021-05-09T18:05:50.000Z | jni/guacd/libguac/client-handlers.c | maqiangddb/AndroidVncServer | 3bd4414ff4a84cd7407493364078dc4d77d4e5ad | [
"MIT"
] | null | null | null | jni/guacd/libguac/client-handlers.c | maqiangddb/AndroidVncServer | 3bd4414ff4a84cd7407493364078dc4d77d4e5ad | [
"MIT"
] | 1 | 2019-03-16T08:46:46.000Z | 2019-03-16T08:46:46.000Z |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is libguac.
*
* The Initial Developer of the Original Code is
* Michael Jumper.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdlib.h>
#include <stdio.h>
#include "client.h"
#include "guacamole/protocol.h"
#include "client-handlers.h"
/* Guacamole instruction handler map */
__guac_instruction_handler_mapping __guac_instruction_handler_map[] = {
{"sync", __guac_handle_sync},
{"mouse", __guac_handle_mouse},
{"key", __guac_handle_key},
{"clipboard", __guac_handle_clipboard},
{"disconnect", __guac_handle_disconnect},
{"size", __guac_handle_size},
{NULL, NULL}
};
int64_t __guac_parse_int(const char* str) {
int sign = 1;
int64_t num = 0;
for (; *str != '\0'; str++) {
if (*str == '-')
sign = -sign;
else
num = num * 10 + (*str - '0');
}
return num * sign;
}
/* Guacamole instruction handlers */
int __guac_handle_sync(guac_client* client, guac_instruction* instruction) {
guac_timestamp timestamp = __guac_parse_int(instruction->argv[0]);
/* Error if timestamp is in future */
if (timestamp > client->last_sent_timestamp)
return -1;
client->last_received_timestamp = timestamp;
return 0;
}
int __guac_handle_mouse(guac_client* client, guac_instruction* instruction) {
if (client->mouse_handler)
return client->mouse_handler(
client,
atoi(instruction->argv[0]), /* x */
atoi(instruction->argv[1]), /* y */
atoi(instruction->argv[2]) /* mask */
);
return 0;
}
int __guac_handle_key(guac_client* client, guac_instruction* instruction) {
if (client->key_handler)
return client->key_handler(
client,
atoi(instruction->argv[0]), /* keysym */
atoi(instruction->argv[1]) /* pressed */
);
return 0;
}
int __guac_handle_clipboard(guac_client* client, guac_instruction* instruction) {
if (client->clipboard_handler)
return client->clipboard_handler(
client,
instruction->argv[0] /* data */
);
return 0;
}
int __guac_handle_size(guac_client* client, guac_instruction* instruction) {
if (client->size_handler)
return client->size_handler(
client,
atoi(instruction->argv[0]), /* width */
atoi(instruction->argv[1]) /* height */
);
return 0;
}
int __guac_handle_disconnect(guac_client* client, guac_instruction* instruction) {
/* Return error code to force disconnect */
return -1;
}
| 30.902985 | 82 | 0.659503 |
3ea0f633016859e8838fc66160bf55c80d454e2d | 4,168 | h | C | thirdparty/qt_linux/x86/include/QtCore/qconfig.h | jhupo/qt-components | e5797879f63d4fb544695d3abefb2a26767e86c5 | [
"MIT"
] | null | null | null | thirdparty/qt_linux/x86/include/QtCore/qconfig.h | jhupo/qt-components | e5797879f63d4fb544695d3abefb2a26767e86c5 | [
"MIT"
] | null | null | null | thirdparty/qt_linux/x86/include/QtCore/qconfig.h | jhupo/qt-components | e5797879f63d4fb544695d3abefb2a26767e86c5 | [
"MIT"
] | null | null | null | /* Everything */
/* Compile time features */
/* Qt was configured for a static build */
#if !defined(QT_SHARED) && !defined(QT_STATIC)
# define QT_STATIC
#endif
#define QT_LARGEFILE_SUPPORT 64
#define QT_POINTER_SIZE 4
#define QT_REDUCE_RELOCATIONS
// Compiler sub-arch support
#define QT_COMPILER_SUPPORTS_SSE2
#define QT_COMPILER_SUPPORTS_SSE3
#define QT_COMPILER_SUPPORTS_SSSE3
#define QT_COMPILER_SUPPORTS_SSE4_1
#define QT_COMPILER_SUPPORTS_SSE4_2
#define QT_COMPILER_SUPPORTS_AVX
#ifndef QT_BOOTSTRAPPED
#if defined(QT_BUILTIN_GIF_READER) && defined(QT_NO_BUILTIN_GIF_READER)
# undef QT_BUILTIN_GIF_READER
#elif !defined(QT_BUILTIN_GIF_READER) && !defined(QT_NO_BUILTIN_GIF_READER)
# define QT_BUILTIN_GIF_READER 1
#endif
#if defined(QT_NO_ALSA) && defined(QT_ALSA)
# undef QT_NO_ALSA
#elif !defined(QT_NO_ALSA) && !defined(QT_ALSA)
# define QT_NO_ALSA
#endif
#if defined(QT_NO_CONCURRENT) && defined(QT_CONCURRENT)
# undef QT_NO_CONCURRENT
#elif !defined(QT_NO_CONCURRENT) && !defined(QT_CONCURRENT)
# define QT_NO_CONCURRENT
#endif
#if defined(QT_NO_CUPS) && defined(QT_CUPS)
# undef QT_NO_CUPS
#elif !defined(QT_NO_CUPS) && !defined(QT_CUPS)
# define QT_NO_CUPS
#endif
#if defined(QT_NO_EGL) && defined(QT_EGL)
# undef QT_NO_EGL
#elif !defined(QT_NO_EGL) && !defined(QT_EGL)
# define QT_NO_EGL
#endif
#if defined(QT_NO_EGLFS) && defined(QT_EGLFS)
# undef QT_NO_EGLFS
#elif !defined(QT_NO_EGLFS) && !defined(QT_EGLFS)
# define QT_NO_EGLFS
#endif
#if defined(QT_NO_EGL_X11) && defined(QT_EGL_X11)
# undef QT_NO_EGL_X11
#elif !defined(QT_NO_EGL_X11) && !defined(QT_EGL_X11)
# define QT_NO_EGL_X11
#endif
#if defined(QT_NO_HARFBUZZ) && defined(QT_HARFBUZZ)
# undef QT_NO_HARFBUZZ
#elif !defined(QT_NO_HARFBUZZ) && !defined(QT_HARFBUZZ)
# define QT_NO_HARFBUZZ
#endif
#if defined(QT_NO_OPENGL) && defined(QT_OPENGL)
# undef QT_NO_OPENGL
#elif !defined(QT_NO_OPENGL) && !defined(QT_OPENGL)
# define QT_NO_OPENGL
#endif
#if defined(QT_NO_OPENSSL) && defined(QT_OPENSSL)
# undef QT_NO_OPENSSL
#elif !defined(QT_NO_OPENSSL) && !defined(QT_OPENSSL)
# define QT_NO_OPENSSL
#endif
#if defined(QT_NO_OPENVG) && defined(QT_OPENVG)
# undef QT_NO_OPENVG
#elif !defined(QT_NO_OPENVG) && !defined(QT_OPENVG)
# define QT_NO_OPENVG
#endif
#if defined(QT_NO_PRINTSUPPORT) && defined(QT_PRINTSUPPORT)
# undef QT_NO_PRINTSUPPORT
#elif !defined(QT_NO_PRINTSUPPORT) && !defined(QT_PRINTSUPPORT)
# define QT_NO_PRINTSUPPORT
#endif
#if defined(QT_NO_SSL) && defined(QT_SSL)
# undef QT_NO_SSL
#elif !defined(QT_NO_SSL) && !defined(QT_SSL)
# define QT_NO_SSL
#endif
#if defined(QT_NO_TABLET) && defined(QT_TABLET)
# undef QT_NO_TABLET
#elif !defined(QT_NO_TABLET) && !defined(QT_TABLET)
# define QT_NO_TABLET
#endif
#if defined(QT_NO_XINPUT) && defined(QT_XINPUT)
# undef QT_NO_XINPUT
#elif !defined(QT_NO_XINPUT) && !defined(QT_XINPUT)
# define QT_NO_XINPUT
#endif
#if defined(QT_QML_NO_DEBUGGER) && defined(QT_NO_QML_NO_DEBUGGER)
# undef QT_QML_NO_DEBUGGER
#elif !defined(QT_QML_NO_DEBUGGER) && !defined(QT_NO_QML_NO_DEBUGGER)
# define QT_QML_NO_DEBUGGER
#endif
#if defined(QT_RUNTIME_XCURSOR) && defined(QT_NO_RUNTIME_XCURSOR)
# undef QT_RUNTIME_XCURSOR
#elif !defined(QT_RUNTIME_XCURSOR) && !defined(QT_NO_RUNTIME_XCURSOR)
# define QT_RUNTIME_XCURSOR
#endif
#if defined(QT_RUNTIME_XFIXES) && defined(QT_NO_RUNTIME_XFIXES)
# undef QT_RUNTIME_XFIXES
#elif !defined(QT_RUNTIME_XFIXES) && !defined(QT_NO_RUNTIME_XFIXES)
# define QT_RUNTIME_XFIXES
#endif
#if defined(QT_RUNTIME_XINERAMA) && defined(QT_NO_RUNTIME_XINERAMA)
# undef QT_RUNTIME_XINERAMA
#elif !defined(QT_RUNTIME_XINERAMA) && !defined(QT_NO_RUNTIME_XINERAMA)
# define QT_RUNTIME_XINERAMA
#endif
#if defined(QT_RUNTIME_XRANDR) && defined(QT_NO_RUNTIME_XRANDR)
# undef QT_RUNTIME_XRANDR
#elif !defined(QT_RUNTIME_XRANDR) && !defined(QT_NO_RUNTIME_XRANDR)
# define QT_RUNTIME_XRANDR
#endif
#if defined(QT_USE_MATH_H_FLOATS) && defined(QT_NO_USE_MATH_H_FLOATS)
# undef QT_USE_MATH_H_FLOATS
#elif !defined(QT_USE_MATH_H_FLOATS) && !defined(QT_NO_USE_MATH_H_FLOATS)
# define QT_USE_MATH_H_FLOATS
#endif
#endif // QT_BOOTSTRAPPED
#define QT_VISIBILITY_AVAILABLE
#define QT_QPA_DEFAULT_PLATFORM_NAME "xcb"
| 27.24183 | 75 | 0.797505 |
e315eaf55720cd068cc1c354138e4305ebe9819d | 1,221 | h | C | ControlCenter/SBCCButtonLikeSectionSplitView.h | DanyL/CCLoader | ca535884d19e6013c981bf798ca2501ea9ffef24 | [
"MIT"
] | 1 | 2015-02-17T16:55:25.000Z | 2015-02-17T16:55:25.000Z | ControlCenter/SBCCButtonLikeSectionSplitView.h | DanyL/CCLoader | ca535884d19e6013c981bf798ca2501ea9ffef24 | [
"MIT"
] | null | null | null | ControlCenter/SBCCButtonLikeSectionSplitView.h | DanyL/CCLoader | ca535884d19e6013c981bf798ca2501ea9ffef24 | [
"MIT"
] | null | null | null | /*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "SBControlCenterSectionView.h"
@class SBCCButtonLikeSectionView, SBControlCenterSeparatorView;
@interface SBCCButtonLikeSectionSplitView : SBControlCenterSectionView
{
SBControlCenterSeparatorView *_separatorView;
double _separatorWidth;
_Bool _leftHidden;
_Bool _rightHidden;
SBCCButtonLikeSectionView *_leftSection;
SBCCButtonLikeSectionView *_rightSection;
}
@property(nonatomic) SBCCButtonLikeSectionView *rightSection; // @synthesize rightSection=_rightSection;
@property(nonatomic) SBCCButtonLikeSectionView *leftSection; // @synthesize leftSection=_leftSection;
- (void)layoutSubviews;
- (struct CGRect)_separatorFrame;
- (struct CGRect)_frameForSectionSlot:(int)arg1;
- (id)_viewForSectionSlot:(int)arg1;
- (void)_updateLabelParameters;
- (void)_updateSeparatorVisibility;
- (void)setRightSectionHidden:(_Bool)arg1 animated:(_Bool)arg2;
- (void)setLeftSectionHidden:(_Bool)arg1 animated:(_Bool)arg2;
- (void)_relayoutAnimated:(_Bool)arg1;
- (_Bool)_useLandscapeBehavior;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;
@end
| 32.131579 | 104 | 0.784603 |
6a47fbf947ce816d6f47dd150ff8d6008a5bb1b1 | 3,817 | h | C | external/parallelstl/include/pstl/internal/iterator_impl.h | ZabalaMariano/PISA | 344063799847e89f2f4bd7d75d606ccb95620d30 | [
"Apache-2.0"
] | null | null | null | external/parallelstl/include/pstl/internal/iterator_impl.h | ZabalaMariano/PISA | 344063799847e89f2f4bd7d75d606ccb95620d30 | [
"Apache-2.0"
] | null | null | null | external/parallelstl/include/pstl/internal/iterator_impl.h | ZabalaMariano/PISA | 344063799847e89f2f4bd7d75d606ccb95620d30 | [
"Apache-2.0"
] | 1 | 2021-02-27T11:46:50.000Z | 2021-02-27T11:46:50.000Z | // -*- C++ -*-
//===-- iterator_impl.h ---------------------------------------------------===//
//
// Copyright (C) 2017-2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// This file incorporates work covered by the following copyright and permission
// notice:
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
//
//===----------------------------------------------------------------------===//
#ifndef _PSTL_iterator_impl_H
#define _PSTL_iterator_impl_H
#include <iterator>
#include <tuple>
#if _PSTL_CPP14_INTEGER_SEQUENCE_PRESENT
# include <utility>
#endif
#include "pstl_config.h"
namespace pstl
{
namespace __internal
{
#if _PSTL_CPP14_INTEGER_SEQUENCE_PRESENT
using std::index_sequence;
using std::make_index_sequence;
#else
template <std::size_t... S>
class index_sequence
{
};
template <std::size_t N, std::size_t... S>
struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...>
{
};
template <std::size_t... S>
struct make_index_sequence_impl<0, S...>
{
using type = index_sequence<S...>;
};
template <std::size_t N>
using make_index_sequence = typename pstl::__internal::make_index_sequence_impl<N>::type;
#endif /* _PSTL_CPP14_INTEGER_SEQUENCE_PRESENT */
template <size_t N>
struct zip_forward_iterator_util
{
template <typename TupleType>
static void
increment(TupleType& it)
{
++std::get<N - 1>(it);
zip_forward_iterator_util<N - 1>::increment(it);
}
};
template <>
struct zip_forward_iterator_util<0>
{
template <typename TupleType>
static void
increment(TupleType&){};
};
template <typename TupleReturnType>
struct make_references
{
template <typename TupleType, std::size_t... Is>
TupleReturnType
operator()(const TupleType& t, index_sequence<Is...>)
{
return std::tie(*std::get<Is>(t)...);
}
};
//zip_iterator version for forward iterator
//== and != comparison is performed only on the first element of the tuple
template <typename... Types>
class zip_forward_iterator
{
static const std::size_t num_types = sizeof...(Types);
typedef typename std::tuple<Types...> it_types;
public:
typedef typename std::make_signed<std::size_t>::type difference_type;
typedef std::tuple<typename std::iterator_traits<Types>::value_type...> value_type;
typedef std::tuple<typename std::iterator_traits<Types>::reference...> reference;
typedef std::tuple<typename std::iterator_traits<Types>::pointer...> pointer;
typedef std::forward_iterator_tag iterator_category;
zip_forward_iterator() : my_it() {}
explicit zip_forward_iterator(Types... args) : my_it(std::make_tuple(args...)) {}
zip_forward_iterator(const zip_forward_iterator& input) : my_it(input.my_it) {}
zip_forward_iterator&
operator=(const zip_forward_iterator& input)
{
my_it = input.my_it;
return *this;
}
reference operator*() const { return make_references<reference>()(my_it, make_index_sequence<num_types>()); }
zip_forward_iterator&
operator++()
{
zip_forward_iterator_util<num_types>::increment(my_it);
return *this;
}
zip_forward_iterator
operator++(int)
{
zip_forward_iterator it(*this);
++(*this);
return it;
}
bool
operator==(const zip_forward_iterator& it) const
{
return std::get<0>(my_it) == std::get<0>(it.my_it);
}
bool
operator!=(const zip_forward_iterator& it) const
{
return !(*this == it);
}
it_types
base() const
{
return my_it;
}
private:
it_types my_it;
};
} // namespace __internal
} // namespace pstl
#endif /* _PSTL_iterator_impl_H */
| 24.158228 | 113 | 0.659418 |
1d421e79313f934cd2268975f087beb940ad753a | 679 | h | C | pubg/PrivateHeaders/HsLocalConversationLoaderInfo.h | cara-ksa-so4/PUBC | 1065b983d7bb1c4ad2104c2c4943487c7f17fa44 | [
"MIT"
] | 14 | 2019-07-23T20:33:14.000Z | 2022-03-09T23:29:36.000Z | fc/PrivateHeaders/HsLocalConversationLoaderInfo.h | lechium/FControl | 1203a3d6345b5ce9c738d238e0e7075e27c4d21c | [
"MIT"
] | 5 | 2019-07-22T03:59:20.000Z | 2020-03-02T14:50:48.000Z | fc/PrivateHeaders/HsLocalConversationLoaderInfo.h | lechium/FControl | 1203a3d6345b5ce9c738d238e0e7075e27c4d21c | [
"MIT"
] | 8 | 2019-07-23T20:35:34.000Z | 2022-03-03T05:51:30.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class HsConversationDM;
@interface HsLocalConversationLoaderInfo : NSObject
{
HsConversationDM *_conversation; // 8 = 0x8
unsigned long long _messageCount; // 16 = 0x10
}
@property unsigned long long messageCount; // @synthesize messageCount=_messageCount;
@property(retain) HsConversationDM *conversation; // @synthesize conversation=_conversation;
- (void).cxx_destruct; // IMP=0x000000010142641c
- (id)initWithConversation:(id)arg1 messageCount:(unsigned long long)arg2; // IMP=0x0000000101426350
@end
| 28.291667 | 100 | 0.742268 |
8a962fd0e958b2694e8fad63b15c215cdbd736b1 | 4,202 | c | C | pico22/binex/100-basic-file-exploit-DONE/program-redacted.c | htpa-tsa/picogym | 6263c0baabd80360178051ac3e37c9cc3ed5897d | [
"MIT"
] | 3 | 2022-03-06T18:22:32.000Z | 2022-03-10T02:44:46.000Z | Binary Exploitation/basic-file-exploit/program-redacted.c | KathleenX7/PicoCTF-2022-Writeup | 6ac233456245335e9ce53ccc2bb4c6c71270c73a | [
"CC0-1.0"
] | null | null | null | Binary Exploitation/basic-file-exploit/program-redacted.c | KathleenX7/PicoCTF-2022-Writeup | 6ac233456245335e9ce53ccc2bb4c6c71270c73a | [
"CC0-1.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#define WAIT 60
static const char* flag = "[REDACTED]";
static char data[10][100];
static int input_lengths[10];
static int inputs = 0;
int tgetinput(char *input, unsigned int l)
{
fd_set input_set;
struct timeval timeout;
int ready_for_reading = 0;
int read_bytes = 0;
if( l <= 0 )
{
printf("'l' for tgetinput must be greater than 0\n");
return -2;
}
/* Empty the FD Set */
FD_ZERO(&input_set );
/* Listen to the input descriptor */
FD_SET(STDIN_FILENO, &input_set);
/* Waiting for some seconds */
timeout.tv_sec = WAIT; // WAIT seconds
timeout.tv_usec = 0; // 0 milliseconds
/* Listening for input stream for any activity */
ready_for_reading = select(1, &input_set, NULL, NULL, &timeout);
/* Here, first parameter is number of FDs in the set,
* second is our FD set for reading,
* third is the FD set in which any write activity needs to updated,
* which is not required in this case.
* Fourth is timeout
*/
if (ready_for_reading == -1) {
/* Some error has occured in input */
printf("Unable to read your input\n");
return -1;
}
if (ready_for_reading) {
read_bytes = read(0, input, l-1);
if(input[read_bytes-1]=='\n'){
--read_bytes;
input[read_bytes]='\0';
}
if(read_bytes==0){
printf("No data given.\n");
return -4;
} else {
return 0;
}
} else {
printf("Timed out waiting for user input. Press Ctrl-C to disconnect\n");
return -3;
}
return 0;
}
static void data_write() {
char input[100];
char len[4];
long length;
int r;
printf("Please enter your data:\n");
r = tgetinput(input, 100);
// Timeout on user input
if(r == -3)
{
printf("Goodbye!\n");
exit(0);
}
while (true) {
printf("Please enter the length of your data:\n");
r = tgetinput(len, 4);
// Timeout on user input
if(r == -3)
{
printf("Goodbye!\n");
exit(0);
}
if ((length = strtol(len, NULL, 10)) == 0) {
puts("Please put in a valid length");
} else {
break;
}
}
if (inputs > 10) {
inputs = 0;
}
strcpy(data[inputs], input);
input_lengths[inputs] = length;
printf("Your entry number is: %d\n", inputs + 1);
inputs++;
}
static void data_read() {
char entry[4];
long entry_number;
char output[100];
int r;
memset(output, '\0', 100);
printf("Please enter the entry number of your data:\n");
r = tgetinput(entry, 4);
// Timeout on user input
if(r == -3)
{
printf("Goodbye!\n");
exit(0);
}
if ((entry_number = strtol(entry, NULL, 10)) == 0) {
puts(flag);
fseek(stdin, 0, SEEK_END);
exit(0);
}
entry_number--;
strncpy(output, data[entry_number], input_lengths[entry_number]);
puts(output);
}
int main(int argc, char** argv) {
char input[3] = {'\0'};
long command;
int r;
puts("Hi, welcome to my echo chamber!");
puts("Type '1' to enter a phrase into our database");
puts("Type '2' to echo a phrase in our database");
puts("Type '3' to exit the program");
while (true) {
r = tgetinput(input, 3);
// Timeout on user input
if(r == -3)
{
printf("Goodbye!\n");
exit(0);
}
if ((command = strtol(input, NULL, 10)) == 0) {
puts("Please put in a valid number");
} else if (command == 1) {
data_write();
puts("Write successful, would you like to do anything else?");
} else if (command == 2) {
if (inputs == 0) {
puts("No data yet");
continue;
}
data_read();
puts("Read successful, would you like to do anything else?");
} else if (command == 3) {
return 0;
} else {
puts("Please type either 1, 2 or 3");
puts("Maybe breaking boundaries elsewhere will be helpful");
}
}
return 0;
}
| 21.438776 | 81 | 0.561637 |
ad0e2f514417f091d1acafaf27b1646fba25252c | 8,490 | c | C | drivers/serial/mps/cyclades/z/cyzports/util.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/serial/mps/cyclades/z/cyzports/util.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/serial/mps/cyclades/z/cyzports/util.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /** FILE: util.c *********** Module Header ********************************
*
* Ports applet utility library routines. This file contains string,
* cursor, SendWinIniChange() routines.
*
* History:
* 15:30 on Thur 25 Apr 1991 -by- Steve Cathcart [stevecat]
* Took base code from Win 3.1 source
* 10:30 on Tues 04 Feb 1992 -by- Steve Cathcart [stevecat]
* Updated code to latest Win 3.1 sources
* 15:30 on Thur 03 May 1994 -by- Steve Cathcart [stevecat]
* Increased MyMessageBox buffers, Restart dialog changes
* 17:00 on Mon 18 Sep 1995 -by- Steve Cathcart [stevecat]
* Changes for product update - SUR release NT v4.0
* Nov 1997 -by- Doron Holan [stevecat]
* Removed obsolete cpl code
*
* Copyright (C) 1990-1995 Microsoft Corporation
*
*************************************************************************/
/* Notes -
Global Functions:
U T I L I T Y
BackslashTerm () - add backslash char to path
ErrMemDlg () - display Memory Error message box
MyAtoi () - To convert from Unicode to ANSI string before calling atoi
myatoi () - local implementation of atoi for Unicode strings
MyItoa () - To convert from ANSI to Unicode string after calling itoa
MyMessageBox () - display message to user, with parameters
MyUltoa () - To convert from Unicode to ANSI string before calling ultoa
SendWinIniChange () - broadcast system change message via USER
strscan () - Find a string within another string
StripBlanks () - Strip leading and trailing blanks from a string
Local Functions:
*/
//==========================================================================
// Include files
//==========================================================================
// C Runtime
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
// Application specific
#include "cyzports.h"
#define INT_SIZE_LENGTH 20
#define LONG_SIZE_LENGTH 40
LPTSTR
BackslashTerm(LPTSTR pszPath)
{
LPTSTR pszEnd;
pszEnd = pszPath + lstrlen(pszPath);
//
// Get the end of the source directory
//
switch(*CharPrev(pszPath, pszEnd)) {
case TEXT('\\'):
case TEXT(':'):
break;
default:
*pszEnd++ = TEXT('\\');
*pszEnd = TEXT('\0');
}
return pszEnd;
}
void
ErrMemDlg(HWND hParent)
{
MessageBox(hParent, g_szErrMem, g_szPortsApplet,
MB_OK | MB_ICONHAND | MB_SYSTEMMODAL );
}
///////////////////////////////////////////////////////////////////////////////
//
// MyAtoi
//
// Desc: To convert from Unicode to ANSI string before
// calling CRT atoi and atol functions.
//
///////////////////////////////////////////////////////////////////////////////
int
MyAtoi(LPTSTR string)
{
CHAR szAnsi[ INT_SIZE_LENGTH ];
BOOL fDefCharUsed;
#ifdef UNICODE
WideCharToMultiByte(CP_ACP, 0, string, INT_SIZE_LENGTH,
szAnsi, INT_SIZE_LENGTH, NULL, &fDefCharUsed);
return atoi(szAnsi);
#else
return atoi(string);
#endif
}
int
myatoi(LPTSTR pszInt)
{
int retval;
TCHAR cSave;
for (retval = 0; *pszInt; ++pszInt) {
if ((cSave = (TCHAR) (*pszInt - TEXT('0'))) > (TCHAR) 9)
break;
retval = (int) (retval * 10 + (int) cSave);
}
return (retval);
}
///////////////////////////////////////////////////////////////////////////////
//
// MyItoa
//
// Desc: To convert from ANSI to Unicode string after calling
// CRT itoa function.
//
///////////////////////////////////////////////////////////////////////////////
LPTSTR
MyItoa(INT value, LPTSTR string, INT radix)
{
CHAR szAnsi[INT_SIZE_LENGTH];
#ifdef UNICODE
_itoa(value, szAnsi, radix);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szAnsi, -1,
string, INT_SIZE_LENGTH );
#else
_itoa(value, string, radix);
#endif
return (string);
} // end of MyItoa()
LPTSTR
MyUltoa(unsigned long value,
LPTSTR string,
INT radix)
{
CHAR szAnsi[ LONG_SIZE_LENGTH ];
#ifdef UNICODE
_ultoa(value, szAnsi, radix);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szAnsi, -1,
string, LONG_SIZE_LENGTH );
#else
_ultoa(value, string, radix);
#endif
return( string );
} // end of MyUltoa()
int
MyMessageBox(HWND hWnd,
DWORD wText,
DWORD wCaption,
DWORD wType,
...)
{
TCHAR szText[4 * PATHMAX],
szCaption[2 * PATHMAX];
int ival;
va_list parg;
va_start(parg, wType);
if (wText == INITS)
goto NoMem;
if (!LoadString(g_hInst, wText, szCaption, CharSizeOf(szCaption)))
goto NoMem;
wvsprintf(szText, szCaption, parg);
if (!LoadString(g_hInst, wCaption, szCaption, CharSizeOf(szCaption)))
goto NoMem;
if ((ival = MessageBox(hWnd, szText, szCaption, wType)) == 0)
goto NoMem;
va_end(parg);
return ival;
NoMem:
va_end(parg);
ErrMemDlg(hWnd);
return 0;
}
void
SendWinIniChange(LPTSTR lpSection)
{
// NOTE: We have (are) gone through several iterations of which USER
// api is the correct one to use. The main problem for the Control
// Panel is to avoid being HUNG if another app (top-level window)
// is HUNG. Another problem is that we pass a pointer to a message
// string in our address space. SendMessage will 'thunk' this properly
// for each window, but PostMessage and SendNotifyMessage will not.
// That finally brings us to try to use SendMessageTimeout(). 9/21/92
//
// Try SendNotifyMessage in build 260 or later - kills earlier builds
// SendNotifyMessage ((HWND)-1, WM_WININICHANGE, 0L, (LONG)lpSection);
// PostMessage ((HWND)-1, WM_WININICHANGE, 0L, (LONG)lpSection);
// [stevecat] 4/4/92
//
// SendMessage ((HWND)-1, WM_WININICHANGE, 0L, (LPARAM)lpSection);
//
// NOTE: The final parameter (LPDWORD lpdwResult) must be NULL
SendMessageTimeout((HWND)-1,
WM_WININICHANGE,
0L,
(WPARAM) lpSection,
SMTO_ABORTIFHUNG,
1000,
NULL);
}
LPTSTR
strscan(LPTSTR pszString,
LPTSTR pszTarget)
{
LPTSTR psz;
if (psz = _tcsstr( pszString, pszTarget))
return (psz);
else
return (pszString + lstrlen(pszString));
}
///////////////////////////////////////////////////////////////////////////////
//
// StripBlanks()
//
// Strips leading and trailing blanks from a string.
// Alters the memory where the string sits.
//
///////////////////////////////////////////////////////////////////////////////
void
StripBlanks(LPTSTR pszString)
{
LPTSTR pszPosn;
//
// strip leading blanks
//
pszPosn = pszString;
while (*pszPosn == TEXT(' '))
pszPosn++;
if (pszPosn != pszString)
lstrcpy(pszString, pszPosn);
//
// strip trailing blanks
//
if ((pszPosn = pszString + lstrlen(pszString)) != pszString) {
pszPosn = CharPrev(pszString, pszPosn);
while (*pszPosn == TEXT(' '))
pszPosn = CharPrev(pszString, pszPosn);
pszPosn = CharNext(pszPosn);
*pszPosn = TEXT('\0');
}
}
BOOL ReadRegistryByte(HKEY hKey,
PTCHAR valueName,
PBYTE regData)
{
DWORD regDataType = 0;
DWORD regDataSize = 0;
regDataSize = sizeof(*regData);
if ((ERROR_SUCCESS != RegQueryValueEx(hKey,
valueName,
NULL,
®DataType,
regData,
®DataSize))
|| (regDataSize != sizeof(BYTE))
|| (regDataType != REG_BINARY))
{
//
// Read was unsuccessful or not a binary value, regData is not set
//
return FALSE;
}
//
// Read was a success, regData contains the value read in
//
return TRUE;
}
| 24.824561 | 81 | 0.519552 |
8de74cf4d859d9706e976dbe470bc5d0f1a2409d | 139 | h | C | IoT-Clients/SCRAPS_ATMEGA/full_verified/verifast/examples/crypto_ccs/bin/stdlib/math.h | sss-wue/scraps | 8558e1ff1a8461956e0f0454e4873054f53fdded | [
"Apache-2.0"
] | null | null | null | IoT-Clients/SCRAPS_ATMEGA/full_verified/verifast/examples/crypto_ccs/bin/stdlib/math.h | sss-wue/scraps | 8558e1ff1a8461956e0f0454e4873054f53fdded | [
"Apache-2.0"
] | 1 | 2022-03-23T15:58:56.000Z | 2022-03-23T17:25:28.000Z | IoT-Clients/SCRAPS_ATMEGA/full_verified/verifast/examples/crypto_ccs/bin/stdlib/math.h | sss-wue/scraps | 8558e1ff1a8461956e0f0454e4873054f53fdded | [
"Apache-2.0"
] | null | null | null | #ifndef MATH_H
#define MATH_H
#include "vf__floating_point.h"
double fabs(double x);
//@ requires true;
//@ ensures true;
#endif | 13.9 | 31 | 0.683453 |
e1fa5f078f07b70fc041b68c624154b40ffcf8e0 | 2,845 | h | C | security/include/rt_sec_types.h | an4967/RT-OCF | d65a99947d1cfc3e71492dbca54c54a141060516 | [
"Apache-2.0"
] | null | null | null | security/include/rt_sec_types.h | an4967/RT-OCF | d65a99947d1cfc3e71492dbca54c54a141060516 | [
"Apache-2.0"
] | null | null | null | security/include/rt_sec_types.h | an4967/RT-OCF | d65a99947d1cfc3e71492dbca54c54a141060516 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
*
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#ifndef __IOTIVITY_RT_SEC_TYPES_H
#define __IOTIVITY_RT_SEC_TYPES_H
// doxm
#define OCF_DOXM_HREF "/oic/sec/doxm"
#define OCF_DOXM_RT "oic.r.doxm"
#define OCF_DOXM_OXMS "oxms"
#define OCF_DOXM_OXMSEL "oxmsel"
#define OCF_DOXM_SCT "sct"
#define OCF_DOXM_OWNED "owned"
#define OCF_DOXM_DEVICEUUID "deviceuuid"
#define OCF_DOXM_DEVOWNERUUID "devowneruuid"
//cred
#define OCF_CRED_HREF "/oic/sec/cred"
#define OCF_CRED_RT "oic.r.cred"
#define OCF_CREDS_NAME "creds"
#define OCF_CREDID_NAME "credid"
#define OCF_SUBJECTUUID_NAME "subjectuuid"
#define OCF_CREDTYPE_NAME "credtype"
#define OCF_CREDUSAGE_NAME "credusage"
#define OCF_PERIOD_NAME "period"
#define OCF_PUBLICDATA_NAME "publicdata"
#define OCF_OPTIONALDATA_NAME "optionaldata"
#define OCF_PRIVATEDATA_NAME "privatedata"
#define OCF_ENCODING_NAME "encoding"
#define OCF_KEY_DATA_NAME "data"
#define OCF_REVSTAT_NAME "revstat"
//acl2
#define OCF_ACL2_HREF "/oic/sec/acl2"
#define OCF_ACL2_RT "oic.r.acl2"
#define OCF_ACL_LIST "aclist2"
#define OCF_ACL_ID "aceid"
#define OCF_ACL_SUBJECT "subject"
#define OCF_ACL_UUID "uuid"
#define OCF_ACL_CONNTYPE "conntype"
#define OCF_ACL_RESOURCES "resources"
#define OCF_ACL_HREF "href"
#define OCF_ACL_PERMISSION "permission"
#define OCF_ACL_AUTH_CRYPT "auth-crypt"
#define OCF_ACL_ANON_CLEAR "anon-clear"
#define OCF_ACL_WILDCARD_NAME "wc"
#define OCF_ACL_WILDCARD_DISCOVERIABLE "+"
#define OCF_ACL_WILDCARD_NON_DISCOVERIABLE "-"
#define OCF_PERMISSION_CREATE (1 << 0)
#define OCF_PERMISSION_READ (1 << 1)
#define OCF_PERMISSION_WRITE (1 << 2)
#define OCF_PERMISSION_DELETE (1 << 3)
#define OCF_PERMISSION_NOTIFY (1 << 4)
//pstat
#define OCF_PSTAT_HREF "/oic/sec/pstat"
#define OCF_PSTAT_RT "oic.r.pstat"
#define OCF_PSTAT_DOS "dos"
#define OCF_PSTAT_STATE "s"
#define OCF_PSTAT_PENDING "p"
#define OCF_PSTAT_ISOP "isop"
#define OCF_PSTAT_CM "cm"
#define OCF_PSTAT_TM "tm"
#define OCF_PSTAT_OM "om"
#define OCF_PSTAT_SM "sm"
//security resource common
#define OCF_ROWNERUUID_NAME "rowneruuid"
#define OCF_WILDCARD_ALL "*"
#define OCF_WILDCARD_LEN (1)
#endif
| 32.329545 | 78 | 0.744112 |
c050fa02e795ed5995adfe2244dc6d9655524f9c | 2,949 | h | C | hxalignmicrotubules/HxMovingLeastSquaresSpatialGraphWarp.h | zibamira/microtubulestitching | 8322b71701e33fde0400715cd5b4e855779e4eda | [
"RSA-MD"
] | 2 | 2015-07-15T15:32:24.000Z | 2017-06-25T07:41:48.000Z | hxalignmicrotubules/HxMovingLeastSquaresSpatialGraphWarp.h | zibamira/microtubulestitching | 8322b71701e33fde0400715cd5b4e855779e4eda | [
"RSA-MD"
] | null | null | null | hxalignmicrotubules/HxMovingLeastSquaresSpatialGraphWarp.h | zibamira/microtubulestitching | 8322b71701e33fde0400715cd5b4e855779e4eda | [
"RSA-MD"
] | null | null | null | #pragma once
#include <vector>
#include <hxcore/HxCompModule.h>
#include <hxcore/HxPortDoIt.h>
#include <hxcore/HxPortFloatSlider.h>
#include <hxcore/HxPortMultiMenu.h>
#include <hxfield/HxUniformVectorField3.h>
#include <mclib/McVec2.h>
#include <hxalignmicrotubules/api.h>
namespace mtalign {
class SliceSelector;
}
class SbMatrix;
class HxSpatialGraph;
class SpatialGraphSelection;
class MovingLeastSquares;
/// `HxMovingLeastSquaresSpatialGraphWarp` applies a moving least squares warp
/// based on the corresponding landmarks in the spatial graph attribute
/// "WarpPairs". Pairs can be added via the hotkey `CTRL-W` defined by the
/// microtubule align filament editor plugin (see
/// `QxMicrotubuleAlignSpatialGraphTool`).
/// `HxMovingLeastSquaresSpatialGraphWarp` is neither used in the supplementary
/// data package nor by one of our protocols in the spindle project.
class HXALIGNMICROTUBULES_API HxMovingLeastSquaresSpatialGraphWarp
: public HxCompModule {
HX_HEADER(HxMovingLeastSquaresSpatialGraphWarp);
public:
struct TransformationOrderInfo {
int upperSliceIdx;
int lowerSliceIdx;
std::vector<int> upperTransformSlices;
std::vector<int> lowerTransformSlices;
};
HxPortMultiMenu portMethod;
HxPortFloatSlider portAlpha;
HxPortDoIt portAction;
virtual void update();
virtual void compute();
static void prepareLandmarks(McDArray<McVec2d>& p1, McDArray<McVec2d>& p2,
const HxSpatialGraph* graph,
const int slice1Num, const int slice2Num);
static void warpPoint(const McVec3f& source, McVec3f& traget,
MovingLeastSquares& mlsInterpolator);
static void
getSameValueVertices(std::map<int, std::vector<int> >& sameValueVertices,
const HxSpatialGraph* graph,
const std::string& attributeName);
static void generateTransformsForSlicesSimple(
const HxSpatialGraph* spatialGraph, const int slice1Index,
const int slice2Index, MovingLeastSquares& lowerTransform,
MovingLeastSquares& upperTransform, int alpha);
static void applyDeformationToSlice(SpatialGraphSelection& slice,
HxSpatialGraph* spatialGraph,
MovingLeastSquares& deformation);
protected:
HxSpatialGraph* createOutputDataSet();
HxUniformVectorField3* createOutputVectorDataSet();
void generateOrderOfDeformationSimple(
const mtalign::SliceSelector& selectionHelper,
std::vector<TransformationOrderInfo>& orderOfDeformation);
static bool isValidPair(const std::vector<int>& vertexIndices,
const mtalign::SliceSelector& selectionHelper);
void applyDeformation(TransformationOrderInfo& transformation,
HxSpatialGraph* spatialGraph);
};
| 36.407407 | 79 | 0.702611 |
dbf5cfaf9837a99647dd424b9fd558e14e839433 | 625 | h | C | C++/OOP Game 2nd course/Stepik/Figures/Rhombus.h | po4yka/elementary-education-projects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | 1 | 2020-09-01T20:22:30.000Z | 2020-09-01T20:22:30.000Z | C++/OOP Game 2nd course/Stepik/Figures/Rhombus.h | po4yka/EducationProjects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | null | null | null | C++/OOP Game 2nd course/Stepik/Figures/Rhombus.h | po4yka/EducationProjects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | null | null | null | #ifndef STEPIC_RHOMBUS_H
#define STEPIC_RHOMBUS_H
#include "Shape.h"
class Rhombus final : public Shape {
private:
float sideLength{};
void calcCenter() override;
public:
~Rhombus() override = default;
Rhombus(ANSIColor::eCOLOR_CODE color, const std::vector<BasePoint> &vertex_);
// Geometry object interface realization
eFIGURE getType() const override;
std::string getDescription() const override;
// Main task functions
void move(std::vector<BasePoint> newVertex) override;
void rotate(float angle) override;
void scale(float factor) override;
};
#endif //STEPIC_RHOMBUS_H
| 25 | 81 | 0.7248 |
6dd7ffd49d1e518b383afa797f8aac15770172df | 8,941 | h | C | NeuralNets/layers/base/utils.h | phineasng/MLearn | 20ac852179029dac2e9e363acc6b21ad9ddfc8d3 | [
"MIT"
] | 2 | 2016-11-14T19:37:33.000Z | 2017-02-05T02:29:35.000Z | NeuralNets/layers/base/utils.h | phineasng/MLearn | 20ac852179029dac2e9e363acc6b21ad9ddfc8d3 | [
"MIT"
] | 12 | 2016-01-23T17:49:50.000Z | 2018-06-25T22:43:30.000Z | NeuralNets/layers/base/utils.h | phineasng/MLearn | 20ac852179029dac2e9e363acc6b21ad9ddfc8d3 | [
"MIT"
] | 1 | 2017-05-23T18:17:14.000Z | 2017-05-23T18:17:14.000Z | #ifndef LAYER_BASE_UTILS_MLEARN_H_FILE
#define LAYER_BASE_UTILS_MLEARN_H_FILE
// MLearn includes
#include <MLearn/Core>
// STL includes
#include <cmath>
#include <type_traits>
/*!
\def DEFINE_LAYER_NAME(name)
Define a dummy struct to be used as layer name
*/
#define DEFINE_LAYER_NAME(layer_name) struct layer_name { \
static constexpr char* get_name() { return #layer_name; } \
};
namespace MLearn{
namespace nn{
/*!
\enum Activation type
*/
enum class ActivationType{
SIGMOID,
RELU,
TANH,
ATAN,
LEAKY_RELU
};
/*!
\brief Activation parameters
*/
template <typename Scalar, ActivationType A>
struct ActivationParams{};
/*!
\brief Activation type traits
*/
template <ActivationType A>
struct ActivationTraits{
enum { n_parameters = 0 };
enum { efficient_derivative = false };
};
// dummy version of efficient derivative compute functions
#define DEFINE_DUMMY_COMPUTE_DERIVATIVE_ACTIVATED()\
template <typename Scalar>\
static inline Scalar compute_derivative_activated(const Scalar& f){ \
throw MLNotImplemented(); \
}
// dummy version of activation compute functions using parameters
#define DEFINE_DUMMY_COMPUTE_WITH_PARAMETERS_FUNCTION(ACTIVATION)\
template <typename Scalar>\
static inline Scalar compute(const Scalar& x, const ActivationParams<Scalar, ACTIVATION>& params){ \
return compute(x); \
}\
template <typename Scalar>\
static inline Scalar compute_derivative(const Scalar& x, const ActivationParams<Scalar, ACTIVATION>& params){ \
return compute_derivative(x); \
}\
template <typename Scalar>\
static inline Scalar compute_derivative_activated(const Scalar& f, const ActivationParams<Scalar, ACTIVATION>& params){ \
return compute_derivative_activated(f); \
}
#define DEFINE_DUMMY_COMPUTE_DERIVATIVE_ACTIVATED_WITH_PARAMETERS(ACTIVATION)\
template <typename Scalar>\
static inline Scalar compute_derivative_activated(const Scalar& f, const ActivationParams<Scalar, ACTIVATION>& params){ \
return compute_derivative_activated(f); \
}
/*!
\brief Activation functor - non-specialised
*/
template <ActivationType A>
struct Activation{
/*!
\brief Compute activation
*/
template <typename Scalar>
static inline Scalar compute(const Scalar& x){ throw MLNotImplemented(); }
/*!
\brief Compute derivative of activation
*/
template <typename Scalar>
static inline Scalar compute_derivative(const Scalar& x){ throw MLNotImplemented(); }
/*!
\brief Compute derivative of activation with given activated value
This is a more computationally efficient derivative computation in case the activated value is already available.
E.g. for the sigmoid function, if f is the activated value, then f' = f*(1-f)
*/
DEFINE_DUMMY_COMPUTE_DERIVATIVE_ACTIVATED();
DEFINE_DUMMY_COMPUTE_WITH_PARAMETERS_FUNCTION(A);
};
/*!
\brief SIGMOID specializations
*/
template <>
struct ActivationTraits<ActivationType::SIGMOID>{
enum { n_parameters = 0 };
enum { efficient_derivative = true };
};
template <>
struct Activation<ActivationType::SIGMOID>{
/*!
\brief Activation operator
*/
template <typename Scalar>
static inline Scalar compute(const Scalar& x){ return 1./(1. + std::exp(-x)); }
/*!
\brief Activation derivative operator
*/
template <typename Scalar>
static inline Scalar compute_derivative(const Scalar& x){
Scalar exp_x = std::exp(-x);
Scalar exp_xp1 = exp_x + 1.;
return exp_x/(exp_xp1*exp_xp1);
}
/*!
\brief Activation derivate operator - given activate value
*/
template <typename Scalar>
static inline Scalar compute_derivative_activated(const Scalar& f){
return f*(1. - f);
}
DEFINE_DUMMY_COMPUTE_WITH_PARAMETERS_FUNCTION(ActivationType::SIGMOID);
};
/*!
\brief RELU specializations
*/
template <>
struct Activation<ActivationType::RELU>{
/*!
\brief Activation operator
*/
template <typename Scalar>
static inline Scalar compute(const Scalar& x){ return std::max(0., x); }
/*!
\brief Activation derivative operator
*/
template <typename Scalar>
static inline Scalar compute_derivative(const Scalar& x){
if (x >= 0.){
return 1.;
}else{
return 0.;
}
}
DEFINE_DUMMY_COMPUTE_DERIVATIVE_ACTIVATED();
DEFINE_DUMMY_COMPUTE_WITH_PARAMETERS_FUNCTION(ActivationType::RELU);
};
/*!
\brief TANH specializations
*/
template <>
struct ActivationTraits<ActivationType::TANH>{
enum { n_parameters = 0 };
enum { efficient_derivative = true };
};
template <>
struct Activation<ActivationType::TANH>{
/*!
\brief Activation operator
*/
template <typename Scalar>
static inline Scalar compute(const Scalar& x){ return std::tanh(x); }
/*!
\brief Activation derivative operator
*/
template <typename Scalar>
static inline Scalar compute_derivative(const Scalar& x){
Scalar sech = 1.0/std::cosh(x);
return sech*sech;
}
/*!
\brief Activation derivate operator - given activate value
*/
template <typename Scalar>
static inline Scalar compute_derivative_activated(const Scalar& f){
return (1. - f*f);
}
DEFINE_DUMMY_COMPUTE_WITH_PARAMETERS_FUNCTION(ActivationType::TANH);
};
/*!
\brief ATAN specializations
*/
template <>
struct Activation<ActivationType::ATAN>{
/*!
\brief Activation operator
*/
template <typename Scalar>
static inline Scalar compute(const Scalar& x){ return std::atan(x); }
/*!
\brief Activation derivative operator
*/
template <typename Scalar>
static inline Scalar compute_derivative(const Scalar& x){
return 1./(x*x + 1.);
}
DEFINE_DUMMY_COMPUTE_DERIVATIVE_ACTIVATED();
DEFINE_DUMMY_COMPUTE_WITH_PARAMETERS_FUNCTION(ActivationType::ATAN);
};
/*!
\brief RELU specializations
If no parameters are provided, the classic RELU is computed
*/
template <>
struct ActivationTraits<ActivationType::LEAKY_RELU>{
enum { n_parameters = 1 };
enum { efficient_derivative = false };
};
template <typename Scalar>
struct ActivationParams<Scalar, ActivationType::LEAKY_RELU>{
Scalar a = 0.0;
};
template <>
struct Activation<ActivationType::LEAKY_RELU>{
/*!
\brief Activation operator
*/
template <typename Scalar>
static inline Scalar compute(const Scalar& x){ return Activation<ActivationType::RELU>::compute(x); }
/*!
\brief Activation derivative operator
*/
template <typename Scalar>
static inline Scalar compute_derivative(const Scalar& x){
return Activation<ActivationType::RELU>::compute_derivative(x);
}
template <typename Scalar>
static inline Scalar compute(const Scalar& x, const ActivationParams<Scalar, ActivationType::LEAKY_RELU>& params){
if (x < 0.){
return params.a*x;
}else{
return x;
}
}
template <typename Scalar>
static inline Scalar compute_derivative(const Scalar& x, const ActivationParams<Scalar, ActivationType::LEAKY_RELU>& params){
if (x < 0.){
return params.a;
}else{
return 1.;
}
}
DEFINE_DUMMY_COMPUTE_DERIVATIVE_ACTIVATED();
DEFINE_DUMMY_COMPUTE_DERIVATIVE_ACTIVATED_WITH_PARAMETERS(ActivationType::LEAKY_RELU);
};
/*!
\brief Helper class to select (at compile-time) which derivative to use
*/
namespace internal{
template <typename Scalar, ActivationType A>
struct ActivationDerivativeBaseWrapper{
ActivationParams<Scalar, A> _params;
/*!
\brief Constructor
*/
ActivationDerivativeBaseWrapper() = default;
/*!
\brief Parameters setter
*/
void set_params(const ActivationParams<Scalar, A>& in_params){
_params = in_params;
}
/*!
\brief Parameters getter
*/
const ActivationParams<Scalar, A>& get_params() const{
return _params;
}
};
template <typename Scalar, ActivationType A, bool efficient>
struct ActivationDerivativeInternalWrapper{};
/*!
\brief Version using activated values
\param x pre-activation values
\param f_x activated values
\param params parameters
*/
template <typename Scalar, ActivationType A>
struct ActivationDerivativeInternalWrapper<Scalar, A, true>: public ActivationDerivativeBaseWrapper<Scalar, A>{
using ActivationDerivativeBaseWrapper<Scalar, A>::ActivationDerivativeBaseWrapper;
using ActivationDerivativeBaseWrapper<Scalar, A>::set_params;
using ActivationDerivativeBaseWrapper<Scalar, A>::get_params;
inline Scalar operator()(const Scalar& x, const Scalar& f_x) const{
return Activation<A>::compute_derivative_activated(f_x, this->_params);
}
};
template <typename Scalar, ActivationType A>
struct ActivationDerivativeInternalWrapper<Scalar, A, false>: public ActivationDerivativeBaseWrapper<Scalar, A>{
using ActivationDerivativeBaseWrapper<Scalar, A>::ActivationDerivativeBaseWrapper;
using ActivationDerivativeBaseWrapper<Scalar, A>::set_params;
using ActivationDerivativeBaseWrapper<Scalar, A>::get_params;
inline Scalar operator()(const Scalar& x, const Scalar& f_x) const{
return Activation<A>::compute_derivative(x, this->_params);
}
};
}
template <typename Scalar, ActivationType A>
using ActivationDerivativeWrapper =
internal::ActivationDerivativeInternalWrapper<Scalar, A, ActivationTraits<A>::efficient_derivative>;
}}
#endif // LAYER_BASE_UTILS_MLEARN_H_FILE | 25.400568 | 127 | 0.756403 |
33f470523155bed79829a15dc4c7052eb698425d | 4,892 | h | C | compile/mclinker/include/mcld/Support/Path.h | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 75 | 2015-03-18T06:01:37.000Z | 2022-01-27T15:17:23.000Z | compile/mclinker/include/mcld/Support/Path.h | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 5 | 2015-07-08T07:47:25.000Z | 2018-10-08T12:12:04.000Z | compile/mclinker/include/mcld/Support/Path.h | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 28 | 2015-04-14T16:05:13.000Z | 2021-11-18T01:31:01.000Z | //===- Path.h -------------------------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This file declares the mcld::sys::fs::Path. It follows TR2/boost
// filesystem (v3), but modified to remove exception handling and the
// path class.
//===----------------------------------------------------------------------===//
#ifndef MCLD_SUPPORT_PATH_H_
#define MCLD_SUPPORT_PATH_H_
#include "mcld/Config/Config.h"
#include <llvm/Support/raw_ostream.h>
#include <iosfwd>
#include <functional>
#include <string>
#include <locale>
namespace mcld {
namespace sys {
namespace fs {
#if defined(MCLD_ON_WIN32)
const char preferred_separator = '/';
const char separator = '/';
#else
const char preferred_separator = '/';
const char separator = '/';
#endif
const char colon = ':';
const char dot = '.';
/** \class Path
* \brief Path provides an abstraction for the path to a file or directory in
* the operating system's filesystem.
*/
class Path {
public:
typedef char ValueType;
typedef std::string StringType;
public:
Path();
explicit Path(const ValueType* s);
explicit Path(const StringType& s);
Path(const Path& pCopy);
virtual ~Path();
// ----- assignments ----- //
template <class InputIterator>
Path& assign(InputIterator begin, InputIterator end);
Path& assign(const StringType& s);
Path& assign(const ValueType* s, unsigned int length);
// ----- appends ----- //
template <class InputIterator>
Path& append(InputIterator begin, InputIterator end);
Path& append(const Path& pPath);
Path& append(const StringType& pPath);
// ----- observers ----- //
bool empty() const;
bool isFromRoot() const;
bool isFromPWD() const;
const StringType& native() const { return m_PathName; }
StringType& native() { return m_PathName; }
const ValueType* c_str() const { return m_PathName.c_str(); }
// ----- decomposition ----- //
Path parent_path() const;
Path filename() const;
Path stem() const;
Path extension() const;
// ----- generic form observers ----- //
StringType generic_string() const;
bool canonicalize();
public:
StringType::size_type m_append_separator_if_needed();
void m_erase_redundant_separator(StringType::size_type sep_pos);
protected:
StringType m_PathName;
};
bool operator==(const Path& pLHS, const Path& pRHS);
bool operator!=(const Path& pLHS, const Path& pRHS);
Path operator+(const Path& pLHS, const Path& pRHS);
//===----------------------------------------------------------------------===//
// Non-member Functions
//===----------------------------------------------------------------------===//
bool exists(const Path& pPath);
bool is_directory(const Path& pPath);
template <class Char, class Traits>
inline std::basic_ostream<Char, Traits>& operator<<(
std::basic_ostream<Char, Traits>& pOS,
const Path& pPath) {
return pOS << pPath.native();
}
template <class Char, class Traits>
inline std::basic_istream<Char, Traits>& operator>>(
std::basic_istream<Char, Traits>& pOS,
Path& pPath) {
return pOS >> pPath.native();
}
inline llvm::raw_ostream& operator<<(llvm::raw_ostream& pOS,
const Path& pPath) {
return pOS << pPath.native();
}
//===----------------------------------------------------------------------===//
// class path member template implementation
//===----------------------------------------------------------------------===//
template <class InputIterator>
Path& Path::assign(InputIterator begin, InputIterator end) {
m_PathName.clear();
if (begin != end)
m_PathName.append<InputIterator>(begin, end);
return *this;
}
template <class InputIterator>
Path& Path::append(InputIterator begin, InputIterator end) {
if (begin == end)
return *this;
StringType::size_type sep_pos(m_append_separator_if_needed());
m_PathName.append<InputIterator>(begin, end);
if (sep_pos)
m_erase_redundant_separator(sep_pos);
return *this;
}
} // namespace fs
} // namespace sys
} // namespace mcld
//===----------------------------------------------------------------------===//
// STL compatible functions
//===----------------------------------------------------------------------===//
namespace std {
template <>
struct less<mcld::sys::fs::Path>
: public binary_function<mcld::sys::fs::Path, mcld::sys::fs::Path, bool> {
bool operator()(const mcld::sys::fs::Path& pX,
const mcld::sys::fs::Path& pY) const {
if (pX.generic_string().size() < pY.generic_string().size())
return true;
return (pX.generic_string() < pY.generic_string());
}
};
} // namespace std
#endif // MCLD_SUPPORT_PATH_H_
| 28.44186 | 80 | 0.582379 |
ef0806cf11fa4902298f6e9858d93702f978c43e | 8,487 | c | C | c/test/test_binsearch_file.c | tecnickcom/binsearch | 1ff439ed6c48be1b549dc6d1080b83761beea2b8 | [
"MIT"
] | 5 | 2017-12-29T12:56:21.000Z | 2020-10-13T21:39:29.000Z | c/test/test_binsearch_file.c | tecnickcom/binsearch | 1ff439ed6c48be1b549dc6d1080b83761beea2b8 | [
"MIT"
] | 11 | 2017-12-16T18:28:37.000Z | 2018-09-06T16:09:16.000Z | c/test/test_binsearch_file.c | tecnickcom/binsearch | 1ff439ed6c48be1b549dc6d1080b83761beea2b8 | [
"MIT"
] | 1 | 2018-01-02T17:48:10.000Z | 2018-01-02T17:48:10.000Z | // Nicola Asuni
#if __STDC_VERSION__ >= 199901L
#define _XOPEN_SOURCE 600
#else
#define _XOPEN_SOURCE 500
#endif
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <sys/mman.h>
#include "../src/binsearch/binsearch.h"
int test_mmap_binfile_error(const char* file)
{
mmfile_t mf = {0};
mmap_binfile(file, &mf);
if (mf.src != MAP_FAILED)
{
fprintf(stderr, "An mmap error was expected\n");
return 1;
}
return 0;
}
int test_munmap_binfile_error()
{
mmfile_t mf = {0};
int e = munmap_binfile(mf);
if (e == 0)
{
fprintf(stderr, "An mummap error was expected\n");
return 1;
}
return 0;
}
int test_map_file_arrow()
{
int errors = 0;
char *file = "test_data_arrow.bin"; // file containing test data
mmfile_t mf = {0};
mf.ncols = 2;
mf.ctbytes[0] = 4;
mf.ctbytes[1] = 8;
mmap_binfile(file, &mf);
if (mf.fd < 0)
{
fprintf(stderr, "%s can't open %s for reading\n", __func__, file);
return 1;
}
if (mf.size == 0)
{
fprintf(stderr, "%s fstat error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.src == MAP_FAILED)
{
fprintf(stderr, "%s mmap error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.size != 730)
{
fprintf(stderr, "%s mf.size : Expecting 730 bytes, got instead: %" PRIu64 "\n", __func__, mf.size);
errors++;
}
if (mf.doffset != 376)
{
fprintf(stderr, "%s mf.doffset : Expecting 376 bytes, got instead: %" PRIu64 "\n", __func__, mf.doffset);
errors++;
}
if (mf.dlength != 136)
{
fprintf(stderr, "%s mf.dlength : Expecting 136 bytes, got instead: %" PRIu64 "\n", __func__, mf.dlength);
errors++;
}
if (mf.nrows != 11)
{
fprintf(stderr, "%s mf.nrows : Expecting 11 items, got instead: %" PRIu64 "\n", __func__, mf.nrows);
errors++;
}
if (mf.ncols != 2)
{
fprintf(stderr, "%s mf.ncols : Expecting 2 items, got instead: %" PRIu8 "\n", __func__, mf.ncols);
errors++;
}
if (mf.index[0] != 376)
{
fprintf(stderr, "%s mf.index[0] : Expecting 376 bytes, got instead: %" PRIu64 "\n", __func__, mf.index[0]);
errors++;
}
if (mf.index[1] != 424)
{
fprintf(stderr, "%s mf.index[1] : Expecting 424 bytes, got instead: %" PRIu64 "\n", __func__, mf.index[1]);
errors++;
}
int e = munmap_binfile(mf);
if (e != 0)
{
fprintf(stderr, "%s Got %d error while unmapping the file\n", __func__, e);
errors++;
}
return errors;
}
int test_map_file_feather()
{
int errors = 0;
char *file = "test_data_feather.bin"; // file containing test data
mmfile_t mf = {0};
mf.ncols = 2;
mf.ctbytes[0] = 4;
mf.ctbytes[1] = 8;
mmap_binfile(file, &mf);
if (mf.fd < 0)
{
fprintf(stderr, "%s can't open %s for reading\n", __func__, file);
return 1;
}
if (mf.size == 0)
{
fprintf(stderr, "%s fstat error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.src == MAP_FAILED)
{
fprintf(stderr, "%s mmap error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.size != 384)
{
fprintf(stderr, "%s mf.size : Expecting 384 bytes, got instead: %" PRIu64 "\n", __func__, mf.size);
errors++;
}
if (mf.doffset != 8)
{
fprintf(stderr, "%s mf.doffset : Expecting 8 bytes, got instead: %" PRIu64 "\n", __func__, mf.doffset);
errors++;
}
if (mf.dlength != 136)
{
fprintf(stderr, "%s mf.dlength : Expecting 136 bytes, got instead: %" PRIu64 "\n", __func__, mf.dlength);
errors++;
}
if (mf.nrows != 11)
{
fprintf(stderr, "%s mf.nrows : Expecting 11 items, got instead: %" PRIu64 "\n", __func__, mf.nrows);
errors++;
}
if (mf.ncols != 2)
{
fprintf(stderr, "%s mf.ncols : Expecting 2 items, got instead: %" PRIu8 "\n", __func__, mf.ncols);
errors++;
}
if (mf.index[0] != 8)
{
fprintf(stderr, "%s mf.index[0] : Expecting 8 bytes, got instead: %" PRIu64 "\n", __func__, mf.index[0]);
errors++;
}
if (mf.index[1] != 56)
{
fprintf(stderr, "%s mf.index[1] : Expecting 56 bytes, got instead: %" PRIu64 "\n", __func__, mf.index[1]);
errors++;
}
int e = munmap_binfile(mf);
if (e != 0)
{
fprintf(stderr, "%s Got %d error while unmapping the file\n", __func__, e);
errors++;
}
return errors;
}
int test_map_file_binsrc()
{
int errors = 0;
char *file = "test_data_binsrc.bin"; // file containing test data
mmfile_t mf = {0};
mmap_binfile(file, &mf);
if (mf.fd < 0)
{
fprintf(stderr, "%s can't open %s for reading\n", __func__, file);
return 1;
}
if (mf.size == 0)
{
fprintf(stderr, "%s fstat error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.src == MAP_FAILED)
{
fprintf(stderr, "%s mmap error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.size != 176)
{
fprintf(stderr, "%s mf.size : Expecting 176 bytes, got instead: %" PRIu64 "\n", __func__, mf.size);
errors++;
}
if (mf.doffset != 40)
{
fprintf(stderr, "%s mf.doffset : Expecting 40 bytes, got instead: %" PRIu64 "\n", __func__, mf.doffset);
errors++;
}
if (mf.dlength != 136)
{
fprintf(stderr, "%s mf.dlength : Expecting 136 bytes, got instead: %" PRIu64 "\n", __func__, mf.dlength);
errors++;
}
if (mf.nrows != 11)
{
fprintf(stderr, "%s mf.nrows : Expecting 11 items, got instead: %" PRIu64 "\n", __func__, mf.nrows);
errors++;
}
if (mf.ncols != 2)
{
fprintf(stderr, "%s mf.ncols : Expecting 2 items, got instead: %" PRIu8 "\n", __func__, mf.ncols);
errors++;
}
if (mf.index[0] != 40)
{
fprintf(stderr, "%s mf.index[0] : Expecting 40 bytes, got instead: %" PRIu64 "\n", __func__, mf.index[0]);
errors++;
}
if (mf.index[1] != 88)
{
fprintf(stderr, "%s mf.index[1] : Expecting 88 bytes, got instead: %" PRIu64 "\n", __func__, mf.index[1]);
errors++;
}
int e = munmap_binfile(mf);
if (e != 0)
{
fprintf(stderr, "%s Got %d error while unmapping the file\n", __func__, e);
errors++;
}
return errors;
}
int test_map_file_col()
{
int errors = 0;
char *file = "test_data_col.bin"; // file containing test data
mmfile_t mf = {0};
mmap_binfile(file, &mf);
if (mf.fd < 0)
{
fprintf(stderr, "%s can't open %s for reading\n", __func__, file);
return 1;
}
if (mf.size == 0)
{
fprintf(stderr, "%s fstat error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.src == MAP_FAILED)
{
fprintf(stderr, "%s mmap error! [%s]\n", __func__, strerror(errno));
return 1;
}
if (mf.size != 3776)
{
fprintf(stderr, "%s mf.size : Expecting 3776 bytes, got instead: %" PRIu64 "\n", __func__, mf.size);
errors++;
}
if (mf.doffset != 0)
{
fprintf(stderr, "%s mf.doffset : Expecting 0 bytes, got instead: %" PRIu64 "\n", __func__, mf.doffset);
errors++;
}
if (mf.dlength != 3776)
{
fprintf(stderr, "%s mf.dlength : Expecting 3776 bytes, got instead: %" PRIu64 "\n", __func__, mf.dlength);
errors++;
}
if (mf.nrows != 0)
{
fprintf(stderr, "%s mf.nrows : Expecting 0 items, got instead: %" PRIu64 "\n", __func__, mf.nrows);
errors++;
}
if (mf.ncols != 0)
{
fprintf(stderr, "%s mf.ncols : Expecting 0 items, got instead: %" PRIu8 "\n", __func__, mf.ncols);
errors++;
}
int e = munmap_binfile(mf);
if (e != 0)
{
fprintf(stderr, "%s Got %d error while unmapping the file\n", __func__, e);
errors++;
}
return errors;
}
int main()
{
int errors = 0;
errors += test_mmap_binfile_error("ERROR");
errors += test_mmap_binfile_error("/dev/null");
errors += test_munmap_binfile_error();
errors += test_map_file_arrow();
errors += test_map_file_feather();
errors += test_map_file_binsrc();
errors += test_map_file_col();
return errors;
}
| 27.377419 | 115 | 0.543891 |
893f5ef230d6ce4918df71974a73f1bebd832d6c | 922 | h | C | net/grpc/gateway/frontend/frontend.h | Atrasoftware/grpc-web | 025b1d641b50b486bbae6921b5df4f9a515649a6 | [
"BSD-3-Clause"
] | null | null | null | net/grpc/gateway/frontend/frontend.h | Atrasoftware/grpc-web | 025b1d641b50b486bbae6921b5df4f9a515649a6 | [
"BSD-3-Clause"
] | null | null | null | net/grpc/gateway/frontend/frontend.h | Atrasoftware/grpc-web | 025b1d641b50b486bbae6921b5df4f9a515649a6 | [
"BSD-3-Clause"
] | null | null | null | #ifndef NET_GRPC_GATEWAY_FRONTEND_FRONTEND_H_
#define NET_GRPC_GATEWAY_FRONTEND_FRONTEND_H_
#include <memory>
#include "net/grpc/gateway/backend/backend.h"
#include "net/grpc/gateway/runtime/response.h"
namespace grpc {
namespace gateway {
class Frontend : public std::enable_shared_from_this<Frontend> {
public:
explicit Frontend(std::unique_ptr<Backend> backend);
virtual ~Frontend();
Frontend(const Frontend&) = delete;
Frontend& operator=(const Frontend&) = delete;
// Start the frontend proxy progress.
virtual void Start() = 0;
// Send response to client.
virtual void Send(std::unique_ptr<Response> response) = 0;
protected:
Backend* backend() { return backend_.get(); }
std::shared_ptr<Frontend> shared_ptr() { return shared_from_this(); }
private:
std::unique_ptr<Backend> backend_;
};
} // namespace gateway
} // namespace grpc
#endif // NET_GRPC_GATEWAY_FRONTEND_FRONTEND_H_
| 26.342857 | 71 | 0.748373 |
def465a36cfc9c37d40330cd51a8742540b8a32c | 1,883 | h | C | src/wtcommon/registrable.h | loganek/workertracker | b4e66f02e6a7cdf91e5f0a418cabbd23ac636f2e | [
"Beerware"
] | null | null | null | src/wtcommon/registrable.h | loganek/workertracker | b4e66f02e6a7cdf91e5f0a418cabbd23ac636f2e | [
"Beerware"
] | 1 | 2017-01-10T10:13:37.000Z | 2017-01-10T10:13:37.000Z | src/wtcommon/registrable.h | loganek/workertracker | b4e66f02e6a7cdf91e5f0a418cabbd23ac636f2e | [
"Beerware"
] | null | null | null | /*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <marcin.kolny@gmail.com> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Marcin Kolny
* ----------------------------------------------------------------------------
*/
#ifndef REGISTRABLE_H
#define REGISTRABLE_H
// Automatically create collection of instances of derived classes
// Blog post: http://www.cookandcommit.eu/2016/10/automatic-collection-of-instances-of.html
#include <memory>
#include <typeindex>
#include <unordered_map>
namespace WT {
template <typename Derived, typename Base>
struct RegistrarCollection
{
template<typename ...Args>
RegistrarCollection(Args&&... args)
{
Base::registry()[typeid(Derived)] =
std::make_shared<Derived>(std::forward<Args>(args)...);
}
};
template <typename Derived, typename Base>
struct RegistrarSingle
{
template<typename ...Args>
RegistrarSingle(Args&&... args)
{
Base::registry() =
std::make_shared<Derived>(std::forward<Args>(args)...);
}
};
template<typename T>
struct RegistrableCollection
{
typedef std::unordered_map<std::type_index, std::shared_ptr<T>> collection_t;
template<typename R>
using RegistrarCollection = RegistrarCollection<R, T>;
static collection_t & registry()
{
static collection_t collection;
return collection;
}
};
template<typename T>
struct RegistrableSingle
{
template<typename R>
using RegistrarSingle = RegistrarSingle<R, T>;
static std::shared_ptr<T> & registry()
{
static std::shared_ptr<T> value;
return value;
}
};
}
#endif // REGISTRABLE_H
| 25.794521 | 91 | 0.617631 |
b05946c9088c7f535ac22447906b5e7f312c9305 | 1,705 | h | C | singlenet-tflite-class/mbase64/base64Class.h | gjbang/graduation-design | deaaa11ed652ac0b8843a039f04665da67181566 | [
"Apache-2.0"
] | null | null | null | singlenet-tflite-class/mbase64/base64Class.h | gjbang/graduation-design | deaaa11ed652ac0b8843a039f04665da67181566 | [
"Apache-2.0"
] | null | null | null | singlenet-tflite-class/mbase64/base64Class.h | gjbang/graduation-design | deaaa11ed652ac0b8843a039f04665da67181566 | [
"Apache-2.0"
] | 1 | 2021-06-24T15:28:20.000Z | 2021-06-24T15:28:20.000Z | //
// Created by axv on 2021/6/11.
//
#ifndef SINGLENET_TFLITE_CLASS_BASE64CLASS_H
#define SINGLENET_TFLITE_CLASS_BASE64CLASS_H
#include <string>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <malloc.h>
#include <memory.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <assert.h>
typedef unsigned char uint8;
//typedef unsigned long uint32_t;
namespace gj{
//定义编码字典
static uint8 alphabet_map[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//定义解码字典
static uint8 reverse_map[] =
{
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255,
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255
};
class base64Class {
public:
uint8 * encoder(const uint8* text, uint32_t text_len);
uint8* decoder(const uint8 *code, uint32_t code_len);
std::string base64_encode(std::string filename);
void base64_decode(std::string filecode, std::string filename);
};
};
#endif //SINGLENET_TFLITE_CLASS_BASE64CLASS_H
| 33.431373 | 101 | 0.580059 |
fc32153f40df06e54552d38c2098ab8a75f564b9 | 128 | h | C | engine/FileIO/src/FileStatus.h | AbyteofteA/MiteVox | 32cbe2e42f05c68b4f545707ef6df28d73d9dd2a | [
"MIT"
] | null | null | null | engine/FileIO/src/FileStatus.h | AbyteofteA/MiteVox | 32cbe2e42f05c68b4f545707ef6df28d73d9dd2a | [
"MIT"
] | null | null | null | engine/FileIO/src/FileStatus.h | AbyteofteA/MiteVox | 32cbe2e42f05c68b4f545707ef6df28d73d9dd2a | [
"MIT"
] | null | null | null |
#ifndef FILESTATUS_H
#define FILESTATUS_H
namespace fileio
{
enum struct FileStatus { ERROR = -1, LOADING, READY };
}
#endif | 12.8 | 55 | 0.734375 |
fc761af810f6b01d47b92645a46aede0e5db52d1 | 1,088 | h | C | tests/test_canvas.h | datoviz/datoviz-distributed | eab904d47930b7253a420c1c44c1b99731cbe6bb | [
"MIT"
] | null | null | null | tests/test_canvas.h | datoviz/datoviz-distributed | eab904d47930b7253a420c1c44c1b99731cbe6bb | [
"MIT"
] | null | null | null | tests/test_canvas.h | datoviz/datoviz-distributed | eab904d47930b7253a420c1c44c1b99731cbe6bb | [
"MIT"
] | null | null | null | /*************************************************************************************************/
/* Tests */
/*************************************************************************************************/
#ifndef DVZ_HEADER_TEST_CANVAS
#define DVZ_HEADER_TEST_CANVAS
/*************************************************************************************************/
/* Includes */
/*************************************************************************************************/
#include "test.h"
#include "testing.h"
/*************************************************************************************************/
/* Input tests */
/*************************************************************************************************/
int test_canvas_1(TstSuite*);
int test_canvas_triangle(TstSuite*);
#endif
| 36.266667 | 99 | 0.152574 |
d399afe05e9d4c11ea1e30752875741bc994cd4e | 10,874 | h | C | sources/WizeCore/proto/include/proto_private.h | GRDF/OpenWize | db1f90b13115541929fd1823a00a9dc5179a41bf | [
"MIT"
] | null | null | null | sources/WizeCore/proto/include/proto_private.h | GRDF/OpenWize | db1f90b13115541929fd1823a00a9dc5179a41bf | [
"MIT"
] | 1 | 2022-02-11T13:06:37.000Z | 2022-02-11T13:06:37.000Z | sources/WizeCore/proto/include/proto_private.h | GRDF/OpenWize | db1f90b13115541929fd1823a00a9dc5179a41bf | [
"MIT"
] | null | null | null | /*!
* @file proto_private.h
* @brief This file define common structures, enum, ...
*
*****************************************************************************
* @Copyright 2019, GRDF, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of GRDF, Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
*****************************************************************************
*
* Revision history
* ----------------
* 1.0.0 : 2019/11/22[GBI]
* Initial version
*
*
*/
/*!
* @ingroup Sources
* @{
* @ingroup Wize
* @{
* @ingroup Protocol
* @{
*
*/
#ifndef _PROTO_PRIVATE_H_
#define _PROTO_PRIVATE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include "proto.h"
/******************************************************************************/
//! ID used before Wize was register
#define PRE_WIZE_PROTO_ID (0xB4)
//! Current Wize ID
#define STD_WIZE_PROTO_ID (0x20)
#if L6VERS == L6VER_WIZE_REV_0_0
#define WIZE_PROTO_ID PRE_WIZE_PROTO_ID
#else
#define WIZE_PROTO_ID STD_WIZE_PROTO_ID
#endif
#ifndef L6_DOWNLOAD_VER
#define L6_DOWNLOAD_VER 0x00
#endif
/******************************************************************************/
// L2 related
/*!
* @def LFIELD_POS
* @brief Length Field size in Link layer frame.
*/
#define LFIELD_SZ 1
/*!
* @def CFIELD_SZ
* @brief Command Field size in Link layer frame.
*/
#define CFIELD_SZ 1
/*!
* @def MFIELD_SZ
* @brief Manufacturer Field size in Link layer frame.
*/
#define MFIELD_SZ 2
/*!
* @def AFIELD_SZ
* @brief Device Field size in Link layer frame.
*/
#define AFIELD_SZ 6
/*!
* @def CLFIELD_SZ
* @brief Cl Field size in Link layer frame.
*/
#define CLFIELD_SZ 1
/*!
* @def L2DWNID_SZ
* @brief Download Id Field size in Link layer frame.
*/
#define L2DWNID_SZ 3
/*!
* @def DATA_PRI_MSK
* @brief This define the data priority mask
*/
#define DATA_PRI_MSK 0x10
/*!
* @def CRC_SZ
* @brief Cyclic Redundancy Check Field size in Link layer frame.
*/
#define CRC_SZ 2
/*!
* @def RSCODE_SZ
* @brief Reed-Solomon Field size in Link layer frame.
*/
#define RSCODE_SZ 32
/******************************************************************************/
// L6 related
/*!
* @def L6_CTRL_SZ
* @brief Control field size
*/
#define L6_CTRL_SZ 1
/*!
* @def L6_NETWID_SZ
* @brief Network Id field size
*/
#define L6_NETWID_SZ 1
/*!
* @def L6_CPT_SZ
* @brief Frame Counter field size
*/
#define L6_CPT_SZ 2
/*!
* @def L6_APP_SZ
* @brief Application Id field size
*/
#define L6_APP_SZ 1
/*!
* @def L6_DWN_VERS_SZ
* @brief Download version protocol field size
*/
#define L6_DWN_VERS_SZ 1
/*!
* @def L6_DWN_B_NUM_SZ
* @brief Download block number field size
*/
#define L6_DWN_B_NUM_SZ 3
/*!
* @def L6_HASH_KENC_SZ
* @brief Hash Kenc field size
*/
#define L6_HASH_KENC_SZ 4
/*!
* @def L6_TSTAMP_SZ
* @brief Time Stamp field size
*/
#define L6_TSTAMP_SZ 2
/*!
* @def L6_EPOCH_SZ
* @brief The EPOCH field size
*/
#define L6_EPOCH_SZ 4
/*!
* @def L6_TX_FREQ_OFFSET_SZ
* @brief The Transmission Frequency Offset field size
*/
#define L6_TX_FREQ_OFFSET_SZ 2
/*!
* @def L6_HASH_KMAC_SZ
* @brief Hash Kmac field size
*/
#define L6_HASH_KMAC_SZ 2
/*!
* @def L6_HASH_KLOG_SZ
* @brief Hash Klog field size
*/
#define L6_HASH_KLOG_SZ 4
//#define FRAME_SEND_MAX_SZ 229
#define FRAME_SEND_MAX_SZ \
(255 - ( \
/* 10 */ \
CFIELD_SZ + MFIELD_SZ + AFIELD_SZ + CLFIELD_SZ + \
/* 5 */ \
L6_CTRL_SZ + L6_NETWID_SZ + L6_CPT_SZ + L6_APP_SZ + \
/* 8 */ \
L6_HASH_KENC_SZ + L6_TSTAMP_SZ + L6_HASH_KMAC_SZ + \
/* 2 */ \
CRC_SZ))
/******************************************************************************/
/*!
* @brief This enum defines the link layer frame type .
*/
typedef enum {
INSTPONG = 0x06, /*!< PONG (CNF_IR). From Gateway to Device */
INSTPING = 0x46, /*!< PING (SND_IR). From Device to Gateway */
COMMAND = 0x43, /*!< COMMAND (SND_UD2). From Gateway to Device */
RESPONSE = 0x08, /*!< RESPONSE (RSP_UD). From Device to Gateway */
DATA = 0x44, /*!< DATA (SND_NR). From Device to Gateway */
DATA_PRIO = DATA | DATA_PRI_MSK, /*!< Priority DATA. From Device to Gateway */
}cfield_e;
/* L2 Layer fields */
/*!
* @brief This structure defines the link layer exchange header.
*/
typedef struct {
uint8_t Cfield; /*!< Frame type */
uint8_t Mfield[MFIELD_SZ]; /*!< Indication of the device MANUFACTURER */
uint8_t Afield[AFIELD_SZ]; /*!< Unique ID of the device */
uint8_t Cifield; /*!< Wize Protocol Id*/
}l2_exch_header_t;
/*!
* @brief This structure defines the link layer download header.
*/
typedef struct {
uint8_t L2DownId[L2DWNID_SZ]; /*!< Identification number of the software
download sequence */
}l2_down_header_t;
/*!
* @brief This structure defines the link layer exchange footer.
*/
typedef struct {
uint8_t Crc[CRC_SZ]; /*!< Message checksum */
}l2_exch_footer_t;
/*!
* @brief This structure defines the link layer download footer.
*/
typedef struct {
uint8_t Crc[CRC_SZ]; /*!< Message checksum */
uint8_t Rs[RSCODE_SZ]; /*!< Error correction block (Reed-Solomon RS(255,223) ) */
}l2_down_footer_t;
/* L6 Layer fields */
/*!
* @brief This structure defines the presentation layer exchange header.
*/
typedef struct {
union {
uint8_t L6Ctrl; /*!< Control field */
struct {
uint8_t KEYSEL:4; /*!< Current encryption and authentication key id */
uint8_t WTS:1; /*!< Reserved value, set to 1. */
uint8_t VERS:3; /*!< The LAN protocol Version */
}L6Ctrl_b;
};
#if L6VERS == L6VER_WIZE_REV_1_0 || L6VERS == L6VER_WIZE_REV_1_1
uint8_t L6NetwId; /*!< Network identifier */
#endif
uint8_t L6Cpt[L6_CPT_SZ]; /*!< Message incremental number */
#if L6VERS == L6VER_WIZE_REV_1_0 || L6VERS == L6VER_WIZE_REV_1_1
uint8_t L6App; /*!< The application layer Id. */
#endif
}l6_exch_header_t;
/*!
* @brief This structure defines the presentation layer download header.
*/
typedef struct {
uint8_t L6DownVer; /*!< Software download protocol version */
uint8_t L6DownBnum[L6_DWN_B_NUM_SZ]; /*!< Software sequence block number. */
}l6_down_header_t;
/*!
* @brief This structure defines the presentation layer exchange footer.
*/
typedef struct {
union {
uint8_t L6HashKenc[L6_HASH_KENC_SZ]; /*!< Authentication signature
of the transmitter of
the message between the
Head-End system and the
device. */
uint8_t Epoch[L6_EPOCH_SZ]; /*!< */
};
union {
uint8_t L6TStamp[L6_TSTAMP_SZ]; /*!< Time stamp of the
transmission time of
the message by the device
or the gateway.*/
uint8_t TxFreqOffset[L6_TX_FREQ_OFFSET_SZ]; /*!< */
};
uint8_t L6HKmac[L6_HASH_KMAC_SZ]; /*!< Authentication signature
of the transmitter of
the message between the
gateway and the device.*/
}l6_exch_footer_t;
/*!
* @brief This structure defines the presentation layer download footer.
*/
typedef struct {
uint8_t L6HashLog[L6_HASH_KLOG_SZ]; /*!< Authentication footprint of the
transmitter of the message between
the gateway and the device. */
}l6_down_footer_t;
/******************************************************************************/
/*!
* @brief This structure define the protocol configuration
*/
struct proto_config_s {
union {
uint8_t filterDisL2; /*!< L2 Reception Filter disable*/
struct
{
uint8_t Crc:1; /*!< Crc filter. 0: enable, 1: disable */
uint8_t AField:1; /*!< Afield filter. 0: enable, 1: disable */
uint8_t MField:1; /*!< MField filter. 0: enable, 1: disable */
uint8_t CiField:1; /*!< CiFiled filter. 0: enable, 1: disable */
uint8_t DownId:1; /*!< DownId filter. 0: enable, 1: disable */
} filterDisL2_b;
};
union {
uint8_t filterDisL6; /*!< L6 Reception Filter disable*/
struct
{
uint8_t App:1; /*!< L6App filter. 0: enable, 1: disable */
uint8_t HashKmac:1; /*!< HashKmac filter. 0: enable, 1: disable */
uint8_t HashKenc:1; /*!< HashKenc filter. 0: enable, 1: disable */
uint8_t NetId:1; /*!< L6NetId filter. 0: enable, 1: disable */
uint8_t Ciph:1; /*!< L7 un-cipher filter. 0: enable, 1: disable
If disable, it is assume that the caller
will un-cipher the L7. */
} filterDisL6_b;
};
uint8_t u8TransLenMax; /*!< Max Length to transmit */
uint8_t u8RecvLenMax; /*!< Max Length to received */
uint8_t u8NetId; /*!< Network Id */
uint8_t DwnId[3]; /*!< Download Sequence Number */
uint8_t AppInst; /*!< L6App used for Install layer */
uint8_t AppAdm; /*!< L6App used for Admin layer */
uint8_t AppData; /*!< L6App used for Data layer */
};
/*!
* @brief This structure define the protocol context
*/
struct proto_ctx_s
{
struct proto_config_s sProtoConfig; /*!< Protocol filter configuration*/
struct proto_stats_s sProtoStats; /*!< Protocol TX/RX statistics */
uint8_t *pBuffer; /*!< Pointer on input/output buffer*/
uint8_t u8Size; /*!< Frame Size to send or received */
uint8_t aDeviceManufID[MFIELD_SZ]; /*!< Device Manufacturer Id */
uint8_t aDeviceAddr[AFIELD_SZ]; /*!< Device Unique Id */
};
#ifdef __cplusplus
}
#endif
#endif /* _PROTO_PRIVATE_H_ */
/*! @} */
/*! @} */
/*! @} */
| 27.953728 | 82 | 0.58341 |
5fec339331aed29dec679bfd3670101ed330de7b | 21,822 | c | C | workers/snodb/snodb.c | seerline/sisdb | 9fc4172ebc8fd0a58c27ef0e0b3cbfa5f65f64f9 | [
"MIT"
] | 13 | 2018-12-14T01:30:25.000Z | 2022-02-18T06:36:36.000Z | workers/snodb/snodb.c | seerline/sisdb | 9fc4172ebc8fd0a58c27ef0e0b3cbfa5f65f64f9 | [
"MIT"
] | 2 | 2021-01-13T06:12:31.000Z | 2022-03-15T08:57:14.000Z | workers/snodb/snodb.c | seerline/sisdb | 9fc4172ebc8fd0a58c27ef0e0b3cbfa5f65f64f9 | [
"MIT"
] | 2 | 2021-02-04T03:04:29.000Z | 2022-02-28T13:20:29.000Z |
#include "sis_modules.h"
#include "worker.h"
#include "server.h"
#include "sis_method.h"
#include "sis_utils.h"
#include <snodb.h>
#include <sis_net.msg.h>
///////////////////////////////////////////////////
// *** s_sis_modules sis_modules_[dir name] *** //
///////////////////////////////////////////////////
// NULL 默认为读取
struct s_sis_method snodb_methods[] = {
// 网络结构体
{"init", cmd_snodb_init, SIS_METHOD_ACCESS_NONET, NULL}, //
{"set", cmd_snodb_set, SIS_METHOD_ACCESS_RDWR, NULL}, //
{"start", cmd_snodb_start, SIS_METHOD_ACCESS_RDWR, NULL}, // 开始发送数据
{"stop", cmd_snodb_stop, SIS_METHOD_ACCESS_RDWR, NULL}, // 数据流发布完成 此时不再接收数据
{"ipub", cmd_snodb_ipub, SIS_METHOD_ACCESS_NONET, NULL}, // 发布数据流 单条数据 kidx+sidx+data
{"pub", cmd_snodb_pub, SIS_METHOD_ACCESS_RDWR, NULL}, // 发布数据流 单条数据 key sdb data
{"zpub", cmd_snodb_zpub, SIS_METHOD_ACCESS_NONET, NULL}, // 发布数据流 只有完成的压缩数据块
{"sub", cmd_snodb_sub, SIS_METHOD_ACCESS_READ, NULL}, // 订阅数据流
{"unsub", cmd_snodb_unsub, SIS_METHOD_ACCESS_READ, NULL}, // 取消订阅数据流
{"get", cmd_snodb_get, SIS_METHOD_ACCESS_READ, NULL}, // 订阅数据流
{"clear", cmd_snodb_clear, SIS_METHOD_ACCESS_NONET, NULL}, // 清理数据流
// 磁盘工具
{"rlog", cmd_snodb_rlog, 0, NULL}, // 异常退出时加载磁盘数据
{"wlog", cmd_snodb_wlog, 0, NULL}, // 异常退出时加载磁盘数据
};
// 共享内存数据库
s_sis_modules sis_modules_snodb = {
snodb_init,
NULL,
snodb_working,
NULL,
snodb_uninit,
NULL,
NULL,
sizeof(snodb_methods) / sizeof(s_sis_method),
snodb_methods,
};
//////////////////////////////////////////////////////////////////
//------------------------snodb --------------------------------//
//////////////////////////////////////////////////////////////////
// snodb 必须先收到 init 再收到 start 顺序不能错
///////////////////////////////////////////////////////////////////////////
//------------------------s_snodb_cxt --------------------------------//
///////////////////////////////////////////////////////////////////////////
#define SNODB_DEBUG
// 转化的压缩包
#ifdef SNODB_DEBUG
static int64 _zipnums = 0;
// 收到的压缩包
static int64 _inzipnums = 0;
static int64 _innums = 0;
static size_t _insize = 0;
#endif
static int cb_input_reader(void *context_, s_sis_object *imem_)
{
s_snodb_cxt *context = (s_snodb_cxt *)context_;
if (!context->work_ziper || context->stoping == 1)
{
return -1;
}
if (context->status != SIS_SUB_STATUS_WORK)
{
// 必须有这个判断 否则正在初始化时 会收到 in==NULL的数据包
LOG(5)("snodb status. %d %d zip : %p imem : %p \n", context->status, context->work_date, context->work_ziper, imem_);
return false;
}
if (!imem_) // 为空表示无数据超时
{
// 数据超时就强制回调一次 只是为了尽快返回数据 不是要强制分段
sisdb_incr_zip_restart(context->work_ziper, 0);
}
else
{
s_sis_memory *memory = SIS_OBJ_MEMORY(imem_);
#ifdef SNODB_DEBUG
if ((_innums++) % 100000 == 0)
{
LOG(8)("recv innums = %d %zu %p\n", _innums, _insize, context->work_ziper);
}
_insize += sis_memory_get_size(memory);
#endif
int kidx = sis_memory_get_byte(memory, 4);
int sidx = sis_memory_get_byte(memory, 2);
sisdb_incr_zip_set(context->work_ziper, kidx, sidx, sis_memory(memory), sis_memory_get_size(memory));
}
return 0;
}
static int cb_wlog_reader(void *reader_, s_sis_object *obj_)
{
s_snodb_reader *reader = (s_snodb_reader *)reader_;
s_snodb_cxt *snodb = (s_snodb_cxt *)reader->father;
// 从第一个初始包开始存盘
s_sis_db_incrzip zmem;
zmem.data = (uint8 *)SIS_OBJ_GET_CHAR(obj_);
zmem.size = SIS_OBJ_GET_SIZE(obj_);
zmem.init = sis_incrzip_isinit(zmem.data, zmem.size);
#ifdef SNODB_DEBUG
if ((_zipnums++) % 100 == 0)
{
LOG(8)("wlog zipnums = %d %d %d %d\n", _zipnums, reader->isinit, zmem.init, snodb->wlog_init);
}
#endif
if (!reader->isinit)
{
if (!zmem.init)
{
// 去掉刚启动时的无效包
return 0;
}
reader->isinit = true;
}
// 无论是否有历史数据,都从新写一份keys和sdbs读取的时候也要更新dict表 以免数据混乱
if(snodb->wlog_init == 0)
{
snodb_wlog_start(snodb);
snodb_wlog_save(snodb, SICDB_FILE_SIGN_KEYS, snodb->work_keys, sis_sdslen(snodb->work_keys));
snodb_wlog_save(snodb, SICDB_FILE_SIGN_SDBS, snodb->work_sdbs, sis_sdslen(snodb->work_sdbs));
snodb->wlog_init = 1;
}
snodb_wlog_save(snodb, SICDB_FILE_SIGN_ZPUB, (char *)zmem.data, zmem.size);
return 0;
}
bool snodb_init(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_sis_json_node *node = (s_sis_json_node *)argv_;
s_snodb_cxt *context = SIS_MALLOC(s_snodb_cxt, context);
worker->context = context;
const char *workname = sis_json_get_str(node, "work-name");
if (workname)
{
context->work_name = sis_sdsnew(workname);
}
else
{
context->work_name = sis_sdsnew(node->key);
}
const char *workpath = sis_json_get_str(node, "work-path");
if (workpath)
{
context->work_path = sis_sdsnew(workpath);
}
else
{
context->work_path = sis_sdsnew("./");
}
context->work_date = sis_time_get_idate(0);
context->wait_msec = sis_json_get_int(node, "wait-msec", 30);
// context->save_time = sis_json_get_int(node, "save-time", 160000);
s_sis_json_node *catchnode = sis_json_cmp_child_node(node, "catch-size");
if (catchnode)
{
context->catch_size = sis_json_get_int(node,"catch-size", 0);
if (context->catch_size > 0)
{
context->catch_size *= 1024*1024;
}
}
else
{
context->catch_size = 1; // 不保留
}
context->outputs = sis_lock_list_create(context->catch_size);
context->map_keys = sis_map_list_create(sis_sdsfree_call);
context->map_sdbs = sis_map_list_create(sis_dynamic_db_destroy);
// 每个读者都自行压缩数据 并把压缩的数据回调出去
context->ago_reader_map = sis_map_kint_create();
context->ago_reader_map->type->vfree = snodb_reader_destroy;
context->cur_reader_map = sis_map_kint_create();
context->cur_reader_map->type->vfree = snodb_reader_destroy;
s_sis_json_node *wlognode = sis_json_cmp_child_node(node, "wlog");
if (wlognode)
{
// 表示需要加载wlog的数据
s_sis_worker *service = sis_worker_create(worker, wlognode);
if (service)
{
context->wlog_worker = service;
context->wlog_method = sis_worker_get_method(context->wlog_worker, "write");
}
}
s_sis_json_node *wfilenode = sis_json_cmp_child_node(node, "wfile");
if (wfilenode)
{
// 表示收到stop时需要从wlog中获取数据并转格式后存盘
s_sis_worker *service = sis_worker_create(worker, wfilenode);
if (service)
{
context->wfile_worker = service;
}
}
s_sis_json_node *rfilenode = sis_json_cmp_child_node(node, "rfile");
if (rfilenode)
{
context->rfile_config = sis_json_clone(rfilenode, 1);
s_sis_json_node *wpnode = sis_json_cmp_child_node(context->rfile_config, "work-path");
if (!wpnode)
{
sis_json_object_add_string(context->rfile_config, "work-path", context->work_path, sis_sdslen(context->work_path));
}
s_sis_json_node *wnnode = sis_json_cmp_child_node(context->rfile_config, "work-name");
if (!wnnode)
{
sis_json_object_add_string(context->rfile_config, "work-name", context->work_name, sis_sdslen(context->work_name));
}
}
if (context->wlog_worker)
{
// 先从目录中获取wlog中数据 并加载到内存中
// 0 表示加载当前目录下有的文件
LOG(5)("load wlog start.\n");
int isload = snodb_wlog_load(context);
LOG(5)("load wlog complete. %d\n", isload);
// 加载成功后 wlog 文件会被重写 以此来保证数据前后的一致性
// snodb_wlog_remove(context);
// 如何保证磁盘的code索引和重启后索引保持一致
// 传入数据时不能清理 keys 和 sdbs 才能不出错
// 然后启动一个读者 订阅 outputs 中数据 然后实时写盘
context->wlog_reader = snodb_reader_create();
context->wlog_reader->father = context;
context->wlog_reader->ishead = isload == SIS_METHOD_OK ? 0 : 1;
context->wlog_reader->isinit = 0;
context->wlog_init = 0;
// 已经有了log文件就从头订阅 否则从尾部订阅
context->wlog_reader->reader = sis_lock_reader_create(context->outputs,
context->wlog_reader->ishead ? SIS_UNLOCK_READER_HEAD : SIS_UNLOCK_READER_TAIL,
context->wlog_reader, cb_wlog_reader, NULL);
sis_lock_reader_open(context->wlog_reader->reader);
}
context->stoping = 0;
return true;
}
void snodb_uninit(void *worker_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
context->stoping = 1;
if (context->wlog_worker)
{
snodb_reader_destroy(context->wlog_reader);
snodb_wlog_stop(context);
sis_worker_destroy(context->wlog_worker);
context->wlog_worker = NULL;
}
if (context->wfile_worker)
{
sis_worker_destroy(context->wfile_worker);
context->wfile_worker = NULL;
}
if (context->rfile_config)
{
sis_json_delete_node(context->rfile_config);
context->rfile_config = NULL;
}
sis_sdsfree(context->work_keys);
sis_sdsfree(context->work_sdbs);
sis_map_list_destroy(context->map_keys);
sis_map_list_destroy(context->map_sdbs);
if (context->inputs)
{
sis_fast_queue_destroy(context->inputs);
}
sis_map_kint_destroy(context->ago_reader_map);
sis_map_kint_destroy(context->cur_reader_map);
sis_lock_list_destroy(context->outputs);
if (context->work_ziper)
{
// 如果有压缩组件 就停止
sisdb_incr_zip_stop(context->work_ziper);
sisdb_incr_destroy(context->work_ziper);
context->work_ziper = NULL;
}
sis_sdsfree(context->work_name);
sis_sdsfree(context->work_path);
sis_free(context);
}
void snodb_working(void *worker_)
{
// s_sis_worker *worker = (s_sis_worker *)worker_;
// s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
// // 必须保证log和wsno都存在才能转格式写盘
// if (context->wlog_worker && context->wfile_worker && context->save_time > 0 &&
// context->inited == true && context->stoped == false && context->wfile_save == 0)
// {
// int iminu = sis_time_get_itime(0);
// if (iminu > context->save_time)
// {
// snodb_wlog_stop(context);
// if (snodb_wlog_to_snos(context) == SIS_METHOD_OK)
// {
// // 等待数据存盘完毕
// SIS_WAIT_LONG(context->wfile_save == 0);
// // 存盘结束清理 wlog
// snodb_wlog_remove(context);
// }
// // 数据转错 就不删除
// context->stoped = true;
// }
// }
}
// 因为可能发到中间时也会调用该函数 init 时需要保证环境和最初的环境一致
int cmd_snodb_init(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_message *msg = (s_sis_message *)argv_;
context->cb_source = sis_message_get(msg, "cb_source");
context->cb_net_message = sis_message_get_method(msg, "cb_net_message");
return SIS_METHOD_OK;
}
int cmd_snodb_set(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_net_message *netmsg = (s_sis_net_message *)argv_;
if (!sis_strcasecmp(netmsg->key, "_keys_") && netmsg->switchs.has_ask)
{
sis_sdsfree(context->work_keys);
context->work_keys = sis_sdsdup(netmsg->ask);
}
if (!sis_strcasecmp(netmsg->key, "_sdbs_") && netmsg->ask)
{
sis_sdsfree(context->work_sdbs);
// 从外界过来的sdbs可能格式不对,需要转换
s_sis_json_handle *injson = sis_json_load(netmsg->ask, sis_sdslen(netmsg->ask));
if (!injson)
{
return SIS_METHOD_ERROR;
}
context->work_sdbs = sis_json_to_sds(injson->node, true);
sis_json_close(injson);
}
return SIS_METHOD_OK;
}
void _snodb_write_start(s_snodb_cxt *context, int workdate)
{
// 这里为了保证二次进入 必须对压缩参数初始化
if (context->inputs)
{
sis_fast_queue_clear(context->inputs);
}
context->near_object = NULL;
// 清理输出缓存中可能存在的数据
sis_lock_list_clear(context->outputs);
context->work_date = workdate;
// 如果是断线重连 没有经过 stop 需要特殊处理
// 初始化用户信息
s_sis_dict_entry *de;
s_sis_dict_iter *di = sis_dict_get_iter(context->cur_reader_map);
while ((de = sis_dict_next(di)) != NULL)
{
s_snodb_reader *reader = (s_snodb_reader *)sis_dict_getval(de);
reader->status = SIS_SUB_STATUS_INIT;
}
sis_dict_iter_free(di);
context->cur_readers = 0;
context->status = SIS_SUB_STATUS_INIT;
}
int cmd_snodb_start(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_net_message *netmsg = (s_sis_net_message *)argv_;
SIS_NET_SHOW_MSG("start", netmsg);
int workdate = netmsg->ask ? sis_atoll(netmsg->ask) : sis_time_get_idate(0);
_snodb_write_start(context, workdate);
LOG(5)("snodb init ok : %d %d\n", context->status, context->work_date);
// 初始化 wlog 开始新的一天 wlog 写入
if (context->wlog_reader && (context->wlog_date == 0 || context->wlog_date != workdate))
{
// log日期不同就重新生成文件
context->wlog_date = workdate;
context->wlog_reader->isinit = 0;
context->wlog_init = 0;
}
#ifdef SNODB_DEBUG
_zipnums = 0;
_inzipnums = 0; // 重新计数
#endif
return SIS_METHOD_OK;
}
int cmd_snodb_stop(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_net_message *netmsg = (s_sis_net_message *)argv_;
if (context->status == SIS_SUB_STATUS_STOP || context->status == SIS_SUB_STATUS_NONE)
{
return SIS_METHOD_ERROR;
}
if (context->inputs)
{
sis_fast_queue_clear(context->inputs);
}
if (context->work_ziper)
{
// 如果有压缩组件 就停止
sisdb_incr_zip_stop(context->work_ziper);
sisdb_incr_destroy(context->work_ziper);
context->work_ziper = NULL;
}
// 停止实时行情订阅
LOG(5)("snodb stop. wlog : %p readers : %d workdate : %d = %s\n",
context->wlog_worker,
sis_map_kint_getsize(context->cur_reader_map),
context->work_date, netmsg->ask);
s_sis_dict_entry *de;
s_sis_dict_iter *di = sis_dict_get_iter(context->cur_reader_map);
while ((de = sis_dict_next(di)) != NULL)
{
s_snodb_reader *reader = (s_snodb_reader *)sis_dict_getval(de);
if (reader->status != SIS_SUB_STATUS_STOP)
{
LOG(5)("snodb stop. cid : %d workdate : %d = %s\n",
reader->cid, context->work_date, netmsg->ask);
snodb_reader_realtime_stop(reader);
reader->status = SIS_SUB_STATUS_STOP;
}
}
sis_dict_iter_free(di);
context->cur_readers = 0;
// context->status = SIS_SUB_STATUS_STOP; // 停止表示当日数据已经落盘
// 停止写wlog文件
if (context->wlog_worker)
{
snodb_wlog_stop(context);
if (snodb_wlog_to_snos(context) == SIS_METHOD_OK)
{
// 等待数据存盘完毕
SIS_WAIT_LONG(context->wfile_save == 0);
// 存盘结束清理 wlog
snodb_wlog_remove(context);
}
}
return SIS_METHOD_OK;
}
int _snodb_write_incrzip(void *context_, char *imem_, size_t isize_)
{
s_snodb_cxt *context = (s_snodb_cxt *)context_;
#ifdef SNODB_DEBUG
if ((_inzipnums++) % 100 == 0)
{
LOG(8)("zpub nums = %d %d | status %d \n", _inzipnums, context->outputs->users->count, context->status);
}
#endif
if (context->stoping || !imem_ || isize_ < 1)
{
return -1;
}
// 直接写入
s_sis_memory *memory = sis_memory_create();
sis_memory_cat(memory, imem_, isize_);
s_sis_object *obj = sis_object_create(SIS_OBJECT_MEMORY, memory);
int isinit = sis_incrzip_isinit((uint8 *)imem_, isize_);
if (isinit == 1)
{
context->near_object = obj;
}
sis_lock_list_push(context->outputs, obj);
sis_object_destroy(obj);
return 0;
}
int _snodb_write_bytes(s_snodb_cxt *context, int kidx, int sidx, void *imem, size_t isize)
{
if (kidx < 0 || sidx < 0 || !imem || isize < 1)
{
return -1;
}
// 初始化 压缩
if (!context->work_ziper)
{
context->work_ziper = sisdb_incr_create();
sisdb_incr_set_keys(context->work_ziper, context->work_keys);
sisdb_incr_set_sdbs(context->work_ziper, context->work_sdbs);
sisdb_incr_zip_start(context->work_ziper, context, _snodb_write_incrzip);
}
if (!context->inputs)
{
context->inputs = sis_fast_queue_create(context, cb_input_reader, 30, context->wait_msec);
}
s_sis_memory *memory = sis_memory_create();
sis_memory_cat_byte(memory, kidx, 4);
sis_memory_cat_byte(memory, sidx, 2);
sis_memory_cat(memory, (char *)imem, isize);
s_sis_object *obj = sis_object_create(SIS_OBJECT_MEMORY, memory);
// printf("-- input -- kidx_= %d, sidx_= %d isize = %zu\n", kidx, sidx, isize);
sis_fast_queue_push(context->inputs, obj);
sis_object_destroy(obj);
return 1;
}
bool _snodb_write_init(s_snodb_cxt *context)
{
// 只有数据来了 才传递给下一级
if (context->status == SIS_SUB_STATUS_STOP || context->status == SIS_SUB_STATUS_NONE)
{
return false;
}
if (context->status == SIS_SUB_STATUS_INIT)
{
if (!context->work_keys || !context->work_sdbs)
{
return false;
}
sis_get_map_keys(context->work_keys, context->map_keys);
sis_get_map_sdbs(context->work_sdbs, context->map_sdbs);
context->status = SIS_SUB_STATUS_WORK;
}
int count = sis_map_kint_getsize(context->cur_reader_map);
if (count <= context->cur_readers)
{
return true;
}
LOG(5)("snodb start. %d readers : %d : %d\n", context->work_date, count, context->cur_readers);
s_sis_dict_entry *de;
s_sis_dict_iter *di = sis_dict_get_iter(context->cur_reader_map);
while ((de = sis_dict_next(di)) != NULL)
{
s_snodb_reader *reader = (s_snodb_reader *)sis_dict_getval(de);
LOG(5)("send sub start.[%d] %d %d %d\n", reader->cid, reader->status, context->work_date, context->cur_readers);
if (reader->status != SIS_SUB_STATUS_INIT)
{
continue;
}
snodb_reader_realtime_start(reader);
reader->status = SIS_SUB_STATUS_WORK;
context->cur_readers ++;
}
sis_dict_iter_free(di);
return true;
}
// #include "stk_struct.v0.h"
int cmd_snodb_ipub(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_db_bytes *in = (s_sis_db_bytes *)argv_;
if (!_snodb_write_init(context))
{
return SIS_METHOD_ERROR;
}
_snodb_write_bytes(context, in->kidx, in->sidx, in->data, in->size);
return SIS_METHOD_OK;
}
int cmd_snodb_pub(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_net_message *netmsg = (s_sis_net_message *)argv_;
if (!_snodb_write_init(context))
{
return SIS_METHOD_ERROR;
}
char kname[128];
char sname[128];
int cmds = sis_str_divide(netmsg->key, '.', kname, sname);
// printf("%s %s\n",__func__, netmsg->key ? netmsg->key : "nil");
s_sis_sds inmem = sis_net_get_argvs(netmsg, 0);
if (cmds == 2 && inmem)
{
int kidx = sis_map_list_get_index(context->map_keys, kname);
int sidx = sis_map_list_get_index(context->map_sdbs, sname);
_snodb_write_bytes(context, kidx, sidx, inmem, sis_sdslen(inmem));
}
return SIS_METHOD_OK;
}
// 从这里写入的数据为索引+二进制数据
int cmd_snodb_zpub(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
if (!_snodb_write_init(context))
{
return SIS_METHOD_ERROR;
}
s_sis_db_incrzip *zmem = (s_sis_db_incrzip *)argv_;
// printf("%s \n",__func__);
if (_snodb_write_incrzip(context, (char *)zmem->data, zmem->size) >= 0)
{
return SIS_METHOD_OK;
}
return SIS_METHOD_ERROR;
}
int cmd_snodb_sub(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_net_message *netmsg = (s_sis_net_message *)argv_;
// SIS_NET_SHOW_MSG("register sub === ", netmsg);
snodb_register_reader(context, netmsg);
return SIS_METHOD_OK;
}
int cmd_snodb_unsub(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_net_message *netmsg = (s_sis_net_message *)argv_;
snodb_remove_reader(context, netmsg->cid);
return SIS_METHOD_OK;
}
int cmd_snodb_get(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
s_sis_net_message *netmsg = (s_sis_net_message *)argv_;
// printf("%s %d\n",__func__, sis_strsub(netmsg->key, "*"));
if (sis_is_multiple_sub(netmsg->key, sis_sdslen(netmsg->key)))
{
// 不支持多键值获取
return SIS_METHOD_ERROR;
}
// 默认读取数据不压缩
return snodb_read(context, netmsg);
}
int cmd_snodb_clear(void *worker_, void *argv_)
{
// s_sis_worker *worker = (s_sis_worker *)worker_;
// s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
// s_sis_message *msg = (s_sis_message *)argv_;
// const char *mode = sis_message_get_str(msg, "mode");
// if (!sis_strcasecmp(mode, "reader"))
// {
// int cid = sis_message_get_int(msg, "cid");
// if (cid == -1)
// {
// sis_pointer_list_clear(context->cur_reader_map);
// }
// else
// {
// snodb_remove_reader(context, cid);
// }
// }
// if (!sis_strcasecmp(mode, "catch"))
// {
// context->near_object = NULL;
// sis_lock_list_clear(context->outputs);
// // 清理数据可能造成数据压缩的不连续 需要处理
// }
return SIS_METHOD_OK;
}
int cmd_snodb_wlog(void *worker_, void *argv_)
{
return SIS_METHOD_OK;
}
int cmd_snodb_rlog(void *worker_, void *argv_)
{
s_sis_worker *worker = (s_sis_worker *)worker_;
s_snodb_cxt *context = (s_snodb_cxt *)worker->context;
if(snodb_wlog_load(context))
{
return SIS_METHOD_OK;
}
return SIS_METHOD_ERROR;
}
| 30.953191 | 121 | 0.652186 |
75a7a0f5dae1ed84db34b636b037031bbb6f25e3 | 332 | h | C | DQM/SiStripCommon/interface/ExtractTObject.h | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | 1 | 2018-07-25T03:57:34.000Z | 2018-07-25T03:57:34.000Z | DQM/SiStripCommon/interface/ExtractTObject.h | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | 1 | 2019-04-12T08:01:26.000Z | 2019-04-12T08:01:26.000Z | DQM/SiStripCommon/interface/ExtractTObject.h | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | #ifndef DQM_SiStripCommon_ExtractTObject_H
#define DQM_SiStripCommon_ExtractTObject_H
#include "DQMServices/Core/interface/MonitorElement.h"
#include <string>
class MonitorElement;
/** */
template <class T>
class ExtractTObject {
public:
static T* extract(MonitorElement* me);
};
#endif // DQM_SiStripCommon_ExtractTObject_H
| 19.529412 | 54 | 0.801205 |
0dd2c25a1c182a964fe40c5f2d2608bea7a77880 | 3,383 | h | C | FreeRadius/freeradius-server-2.2.0/src/modules/rlm_eap/types/rlm_eap_tnc/tncs_connect.h | GeneralZero/CS-577-Final-Project | acf58976df3c0b6b605b8b50a3af7ce9c4d04beb | [
"MIT"
] | null | null | null | FreeRadius/freeradius-server-2.2.0/src/modules/rlm_eap/types/rlm_eap_tnc/tncs_connect.h | GeneralZero/CS-577-Final-Project | acf58976df3c0b6b605b8b50a3af7ce9c4d04beb | [
"MIT"
] | null | null | null | FreeRadius/freeradius-server-2.2.0/src/modules/rlm_eap/types/rlm_eap_tnc/tncs_connect.h | GeneralZero/CS-577-Final-Project | acf58976df3c0b6b605b8b50a3af7ce9c4d04beb | [
"MIT"
] | null | null | null | /*
* This software is Copyright (C) 2006,2007 FH Hannover
*
* Portions of this code unrelated to FreeRADIUS are available
* separately under a commercial license. If you require an
* implementation of EAP-TNC that is not under the GPLv2, please
* contact tnc@inform.fh-hannover.de for details.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#ifndef _TNCS_CONNECT_H_
#define _TNCS_CONNECT_H_
#include "tncs.h"
/*
* establishs the connection to the TNCCS without calling functionality.
* That means that the TNCS-shared-object is loaded and the function-pointer
* to "exchangeTNCCSMessages" is explored.
*
* return: -1 if connect failed, 0 if connect was successful
*/
int connectToTncs(char *pathToSO);
/*
* Accesspoint to the TNCS for sending and receiving TNCCS-Messages.
* -pathToSO: Path to TNCCS-Shared Object
* -connId: identifies the client which the passed message belongs to.
* -isAcknoledgement: 1 if acknoledgement received (then all following in-parameters unimportant
* -input: input-TNCCS-message received from the client with connId
* -inputLength: length of input-TNCCS-message
* -isFirst: 1 if first message in fragmentation else 0
* -moreFragments: are there more Fragments to come (yes: 1, no: 0)?
* -overallLength: length of all fragments together (only set if fragmentation)
* -output: answer-TNCCS-message from the TNCS to the client
* -outputLength: length of answer-TNCCS-message
* -answerIsFirst: returned answer is first in row
* -moreFragmentsFollow: more fragments after this answer
* -overallLengthOut: length of all fragments together (only set if fragmentation) as answer
*
* return: state of connection as result of the exchange
*/
TNC_ConnectionState exchangeTNCCSMessages(/*in*/ char *pathToSO,
/*in*/ TNC_ConnectionID connId,
/*in*/ int isAcknoledgement,
/*in*/ TNC_BufferReference input,
/*in*/ TNC_UInt32 inputLength,
/*in*/ int isFirst,
/*in*/ int moreFragments,
/*in*/ TNC_UInt32 overallLength,
/*out*/ TNC_BufferReference *output,
/*out*/ TNC_UInt32 *outputLength,
/*out*/ int *answerIsFirst,
/*out*/ int *moreFragmentsFollow,
/*out*/ TNC_UInt32 *overallLengthOut);
#endif //_TNCS_CONNECT_H_
| 47.647887 | 96 | 0.635531 |
0eb2fcf821b5ce9c654f8a51df95e9f7acc07eec | 16,682 | c | C | example/freertos/iot/lwm2m/iot_demo/objects/object_security.c | qiangg/embarc_osp | 1fb67015e8a77b3ab14ab4bd90fcf2479b36fb20 | [
"BSD-3-Clause"
] | 2 | 2018-05-11T08:54:18.000Z | 2021-07-09T07:19:54.000Z | example/freertos/iot/lwm2m/iot_demo/objects/object_security.c | fanghuaqi/embarc_osp | 1fb67015e8a77b3ab14ab4bd90fcf2479b36fb20 | [
"BSD-3-Clause"
] | null | null | null | example/freertos/iot/lwm2m/iot_demo/objects/object_security.c | fanghuaqi/embarc_osp | 1fb67015e8a77b3ab14ab4bd90fcf2479b36fb20 | [
"BSD-3-Clause"
] | 2 | 2018-05-10T09:44:09.000Z | 2018-05-10T10:12:08.000Z | /*******************************************************************************
*
* Copyright (c) 2013, 2014 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* The Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* David Navarro, Intel Corporation - initial API and implementation
* Bosch Software Innovations GmbH - Please refer to git log
* Pascal Rieux - Please refer to git log
*
*******************************************************************************/
/*
* Resources:
*
* Name | ID | Operations | Instances | Mandatory | Type | Range | Units |
* Server URI | 0 | | Single | Yes | String | | |
* Bootstrap Server | 1 | | Single | Yes | Boolean | | |
* Security Mode | 2 | | Single | Yes | Integer | 0-3 | |
* Public Key or ID | 3 | | Single | Yes | Opaque | | |
* Server Public Key or ID | 4 | | Single | Yes | Opaque | | |
* Secret Key | 5 | | Single | Yes | Opaque | | |
* SMS Security Mode | 6 | | Single | Yes | Integer | 0-255 | |
* SMS Binding Key Param. | 7 | | Single | Yes | Opaque | 6 B | |
* SMS Binding Secret Keys | 8 | | Single | Yes | Opaque | 32-48 B | |
* Server SMS Number | 9 | | Single | Yes | Integer | | |
* Short Server ID | 10 | | Single | No | Integer | 1-65535 | |
* Client Hold Off Time | 11 | | Single | Yes | Integer | | s |
*
*/
/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 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 Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*
--------------------------------------------- */
/*
* Here we implement a very basic LWM2M Security Object which only knows NoSec security mode.
*/
#include "liblwm2m.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "embARC_debug.h"
#define LWM2M_SECURITY_URI_ID 0
#define LWM2M_SECURITY_BOOTSTRAP_ID 1
#define LWM2M_SECURITY_SECURITY_ID 2
#define LWM2M_SECURITY_PUBLIC_KEY_ID 3
#define LWM2M_SECURITY_SERVER_PUBLIC_KEY_ID 4
#define LWM2M_SECURITY_SECRET_KEY_ID 5
#define LWM2M_SECURITY_SMS_SECURITY_ID 6
#define LWM2M_SECURITY_SMS_KEY_PARAM_ID 7
#define LWM2M_SECURITY_SMS_SECRET_KEY_ID 8
#define LWM2M_SECURITY_SMS_SERVER_NUMBER_ID 9
#define LWM2M_SECURITY_SHORT_SERVER_ID 10
#define LWM2M_SECURITY_HOLD_OFF_ID 11
typedef struct _security_instance_
{
struct _security_instance_ * next; // matches lwm2m_list_t::next
uint16_t instanceId; // matches lwm2m_list_t::id
char * uri;
bool isBootstrap;
uint16_t shortID;
uint32_t clientHoldOffTime;
} security_instance_t;
static uint8_t prv_get_value(lwm2m_tlv_t * tlvP, security_instance_t * instance_ptr)
{
// There are no multiple instance ressources
tlvP->type = LWM2M_TYPE_RESOURCE;
switch (tlvP->id) {
case LWM2M_SECURITY_URI_ID:
tlvP->value = (uint8_t*)instance_ptr->uri;
tlvP->length = strlen(instance_ptr->uri);
tlvP->flags = LWM2M_TLV_FLAG_STATIC_DATA;
tlvP->dataType = LWM2M_TYPE_STRING;
return COAP_205_CONTENT;
case LWM2M_SECURITY_BOOTSTRAP_ID:
lwm2m_tlv_encode_bool(instance_ptr->isBootstrap, tlvP);
if (0 != tlvP->length) return COAP_205_CONTENT;
else return COAP_500_INTERNAL_SERVER_ERROR;
case LWM2M_SECURITY_SECURITY_ID:
lwm2m_tlv_encode_int(LWM2M_SECURITY_MODE_NONE, tlvP);
if (0 != tlvP->length) return COAP_205_CONTENT;
else return COAP_500_INTERNAL_SERVER_ERROR;
case LWM2M_SECURITY_PUBLIC_KEY_ID:
// Here we return an opaque of 1 byte containing 0
tlvP->value = (uint8_t*)"";
tlvP->length = 1;
tlvP->flags = LWM2M_TLV_FLAG_STATIC_DATA;
tlvP->dataType = LWM2M_TYPE_OPAQUE;
return COAP_205_CONTENT;
case LWM2M_SECURITY_SERVER_PUBLIC_KEY_ID:
// Here we return an opaque of 1 byte containing 0
tlvP->value = (uint8_t*)"";
tlvP->length = 1;
tlvP->flags = LWM2M_TLV_FLAG_STATIC_DATA;
tlvP->dataType = LWM2M_TYPE_OPAQUE;
return COAP_205_CONTENT;
case LWM2M_SECURITY_SECRET_KEY_ID:
// Here we return an opaque of 1 byte containing 0
tlvP->value = (uint8_t*)"";
tlvP->length = 1;
tlvP->flags = LWM2M_TLV_FLAG_STATIC_DATA;
tlvP->dataType = LWM2M_TYPE_OPAQUE;
return COAP_205_CONTENT;
case LWM2M_SECURITY_SMS_SECURITY_ID:
lwm2m_tlv_encode_int(LWM2M_SECURITY_MODE_NONE, tlvP);
if (0 != tlvP->length) return COAP_205_CONTENT;
else return COAP_500_INTERNAL_SERVER_ERROR;
case LWM2M_SECURITY_SMS_KEY_PARAM_ID:
// Here we return an opaque of 6 bytes containing a buggy value
tlvP->value = (uint8_t*)"12345";
tlvP->length = 6;
tlvP->flags = LWM2M_TLV_FLAG_STATIC_DATA;
tlvP->dataType = LWM2M_TYPE_OPAQUE;
return COAP_205_CONTENT;
case LWM2M_SECURITY_SMS_SECRET_KEY_ID:
// Here we return an opaque of 32 bytes containing a buggy value
tlvP->value = (uint8_t*)"1234567890abcdefghijklmnopqrstu";
tlvP->length = 32;
tlvP->flags = LWM2M_TLV_FLAG_STATIC_DATA;
tlvP->dataType = LWM2M_TYPE_OPAQUE;
return COAP_205_CONTENT;
case LWM2M_SECURITY_SMS_SERVER_NUMBER_ID:
lwm2m_tlv_encode_int(0, tlvP);
if (0 != tlvP->length) return COAP_205_CONTENT;
else return COAP_500_INTERNAL_SERVER_ERROR;
case LWM2M_SECURITY_SHORT_SERVER_ID:
lwm2m_tlv_encode_int(instance_ptr->shortID, tlvP);
if (0 != tlvP->length) return COAP_205_CONTENT;
else return COAP_500_INTERNAL_SERVER_ERROR;
case LWM2M_SECURITY_HOLD_OFF_ID:
lwm2m_tlv_encode_int(instance_ptr->clientHoldOffTime, tlvP);
if (0 != tlvP->length) return COAP_205_CONTENT;
else return COAP_500_INTERNAL_SERVER_ERROR;
default:
return COAP_404_NOT_FOUND;
}
}
static uint8_t prv_security_read(uint16_t instanceId, int * numDataP, lwm2m_tlv_t ** dataArrayP,
lwm2m_object_t * objectP)
{
security_instance_t * instance_ptr;
uint8_t result;
int i;
instance_ptr = (security_instance_t *)lwm2m_list_find(objectP->instanceList, instanceId);
if (NULL == instance_ptr) return COAP_404_NOT_FOUND;
// is the server asking for the full instance ?
if (*numDataP == 0)
{
uint16_t resList[] = {LWM2M_SECURITY_URI_ID,
LWM2M_SECURITY_BOOTSTRAP_ID,
LWM2M_SECURITY_SECURITY_ID,
LWM2M_SECURITY_PUBLIC_KEY_ID,
LWM2M_SECURITY_SERVER_PUBLIC_KEY_ID,
LWM2M_SECURITY_SECRET_KEY_ID,
LWM2M_SECURITY_SMS_SECURITY_ID,
LWM2M_SECURITY_SMS_KEY_PARAM_ID,
LWM2M_SECURITY_SMS_SECRET_KEY_ID,
LWM2M_SECURITY_SMS_SERVER_NUMBER_ID,
LWM2M_SECURITY_SHORT_SERVER_ID,
LWM2M_SECURITY_HOLD_OFF_ID};
int nbRes = sizeof(resList)/sizeof(uint16_t);
*dataArrayP = lwm2m_tlv_new(nbRes);
if (*dataArrayP == NULL) return COAP_500_INTERNAL_SERVER_ERROR;
*numDataP = nbRes;
for (i = 0 ; i < nbRes ; i++) {
(*dataArrayP)[i].id = resList[i];
}
}
i = 0;
do {
result = prv_get_value((*dataArrayP) + i, instance_ptr);
i++;
} while (i < *numDataP && result == COAP_205_CONTENT);
return result;
}
#ifdef LWM2M_BOOTSTRAP
static uint8_t prv_security_write(uint16_t instanceId, int numData, lwm2m_tlv_t * dataArray,
lwm2m_object_t * objectP)
{
security_instance_t * instance_ptr;
int i;
uint8_t result = COAP_204_CHANGED;
if ((dataArray->flags & LWM2M_TLV_FLAG_BOOTSTRAPPING) == 0) return COAP_401_UNAUTHORIZED;
instance_ptr = (security_instance_t *)lwm2m_list_find(objectP->instanceList, instanceId);
if (NULL == instance_ptr) {
return COAP_404_NOT_FOUND;
}
i = 0;
do {
switch (dataArray[i].id) {
case LWM2M_SECURITY_URI_ID:
if (instance_ptr->uri != NULL) lwm2m_free(instance_ptr->uri);
instance_ptr->uri = (char *)lwm2m_malloc(dataArray[i].length + 1);
memset(instance_ptr->uri, 0, dataArray[i].length + 1);
if (instance_ptr->uri != NULL) {
strncpy(instance_ptr->uri, (char*)dataArray[i].value, dataArray[i].length);
result = COAP_204_CHANGED;
} else {
result = COAP_500_INTERNAL_SERVER_ERROR;
}
break;
case LWM2M_SECURITY_BOOTSTRAP_ID:
if (lwm2m_tlv_decode_bool(dataArray + i, &(instance_ptr->isBootstrap))) {
result = COAP_204_CHANGED;
} else {
result = COAP_400_BAD_REQUEST;
}
break;
case LWM2M_SECURITY_SECURITY_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_PUBLIC_KEY_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_SERVER_PUBLIC_KEY_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_SECRET_KEY_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_SMS_SECURITY_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_SMS_KEY_PARAM_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_SMS_SECRET_KEY_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_SMS_SERVER_NUMBER_ID:
// Let just ignore this
result = COAP_204_CHANGED;
break;
case LWM2M_SECURITY_SHORT_SERVER_ID:
int64_t value;
if (lwm2m_tlv_decode_int(dataArray + i, &value)) {
if (value >= 0 && value <= 0xFFFF) {
instance_ptr->shortID = value;
result = COAP_204_CHANGED;
} else {
result = COAP_406_NOT_ACCEPTABLE;
}
} else {
result = COAP_400_BAD_REQUEST;
}
break;
case LWM2M_SECURITY_HOLD_OFF_ID:
int64_t value;
if (lwm2m_tlv_decode_int(dataArray + i, &value)) {
if (value >= 0 && value <= 0xFFFF) {
instance_ptr->clientHoldOffTime = value;
result = COAP_204_CHANGED;
} else {
result = COAP_406_NOT_ACCEPTABLE;
}
} else {
result = COAP_400_BAD_REQUEST;
}
break;
default:
return COAP_404_NOT_FOUND;
}
i++;
} while (i < numData && result == COAP_204_CHANGED);
return result;
}
static uint8_t prv_security_delete(uint16_t id, lwm2m_object_t * objectP)
{
security_instance_t * instance_ptr;
objectP->instanceList = lwm2m_list_remove(objectP->instanceList, id, (lwm2m_list_t **)&instance_ptr);
if (NULL == instance_ptr) return COAP_404_NOT_FOUND;
if (NULL != instance_ptr->uri) {
lwm2m_free(instance_ptr->uri);
}
lwm2m_free(instance_ptr);
return COAP_202_DELETED;
}
static uint8_t prv_security_create(uint16_t instanceId, int numData, lwm2m_tlv_t * dataArray,
lwm2m_object_t * objectP)
{
security_instance_t * instance_ptr;
uint8_t result;
instance_ptr = (security_instance_t *)lwm2m_malloc(sizeof(security_instance_t));
if (NULL == instance_ptr) return COAP_500_INTERNAL_SERVER_ERROR;
memset(instance_ptr, 0, sizeof(security_instance_t));
instance_ptr->instanceId = instanceId;
objectP->instanceList = LWM2M_LIST_ADD(objectP->instanceList, instance_ptr);
result = prv_security_write(instanceId, numData, dataArray, objectP);
if (result != COAP_204_CHANGED) {
(void)prv_security_delete(instanceId, objectP);
} else {
result = COAP_201_CREATED;
}
return result;
}
#endif
static void prv_security_close(lwm2m_object_t * objectP)
{
while (objectP->instanceList != NULL) {
security_instance_t * securityInstance = (security_instance_t *)objectP->instanceList;
objectP->instanceList = objectP->instanceList->next;
if (NULL != securityInstance->uri) {
lwm2m_free(securityInstance->uri);
}
lwm2m_free(securityInstance);
}
}
void copy_security_object(lwm2m_object_t * objectDest, lwm2m_object_t * objectSrc)
{
memcpy(objectDest, objectSrc, sizeof(lwm2m_object_t));
objectDest->instanceList = NULL;
objectDest->userData = NULL;
security_instance_t * instanceSrc = (security_instance_t *)objectSrc->instanceList;
security_instance_t * previousInstanceDest = NULL;
while (instanceSrc != NULL) {
security_instance_t * instanceDest = (security_instance_t *)lwm2m_malloc(sizeof(security_instance_t));
if (NULL == instanceDest) {
return;
}
memcpy(instanceDest, instanceSrc, sizeof(security_instance_t));
instanceDest->uri = (char*)lwm2m_malloc(strlen(instanceSrc->uri) + 1);
strcpy(instanceDest->uri, instanceSrc->uri);
instanceSrc = (security_instance_t *)instanceSrc->next;
if (previousInstanceDest == NULL) {
objectDest->instanceList = (lwm2m_list_t *)instanceDest;
} else {
previousInstanceDest->next = instanceDest;
}
previousInstanceDest = instanceDest;
}
}
void display_security_object(lwm2m_object_t * object)
{
#ifdef WITH_LOGS
EMBARC_PRINTF(" /%u: Security object, instances:\r\n", object->objID);
security_instance_t * instance = (security_instance_t *)object->instanceList;
while (instance != NULL) {
EMBARC_PRINTF(" /%u/%u: instanceId: %u, uri: %s, isBootstrap: %s, shortId: %u, clientHoldOffTime: %u\r\n",
object->objID, instance->instanceId,
instance->instanceId, instance->uri, instance->isBootstrap ? "true" : "false",
instance->shortID, instance->clientHoldOffTime);
instance = (security_instance_t *)instance->next;
}
#endif
}
lwm2m_object_t * get_security_object(int serverId, const char* serverUri, bool isBootstrap)
{
lwm2m_object_t * obj;
obj = (lwm2m_object_t *)lwm2m_malloc(sizeof(lwm2m_object_t));
if (NULL != obj) {
security_instance_t * instance_ptr;
memset(obj, 0, sizeof(lwm2m_object_t));
obj->objID = 0;
// Manually create an hardcoded instance
instance_ptr = (security_instance_t *)lwm2m_malloc(sizeof(security_instance_t));
if (NULL == instance_ptr) {
lwm2m_free(obj);
return NULL;
}
memset(instance_ptr, 0, sizeof(security_instance_t));
instance_ptr->instanceId = 0;
instance_ptr->uri = (char*)lwm2m_malloc(strlen(serverUri)+1);
strcpy(instance_ptr->uri, serverUri);
instance_ptr->isBootstrap = isBootstrap;
instance_ptr->shortID = serverId;
instance_ptr->clientHoldOffTime = 10;
obj->instanceList = LWM2M_LIST_ADD(obj->instanceList, instance_ptr);
obj->readFunc = prv_security_read;
#ifdef LWM2M_BOOTSTRAP
obj->writeFunc = prv_security_write;
obj->createFunc = prv_security_create;
obj->deleteFunc = prv_security_delete;
#endif
obj->closeFunc = prv_security_close;
}
return obj;
}
char * get_server_uri(lwm2m_object_t * objectP, uint16_t secObjInstID)
{
security_instance_t * instance_ptr = (security_instance_t *)LWM2M_LIST_FIND(objectP->instanceList, secObjInstID);
if (NULL != instance_ptr) {
return lwm2m_strdup(instance_ptr->uri);
}
return NULL;
}
| 33.565392 | 114 | 0.689965 |
1d9a5a2a75615bf335106489c3b3ab2895681308 | 844 | h | C | Source/Singleton.h | bulmaxvad/QtSokoban | 71b915a6e551f0158b372ecd60f11378ffc7cc00 | [
"MIT"
] | 1 | 2020-07-15T04:06:20.000Z | 2020-07-15T04:06:20.000Z | Source/Singleton.h | bulmaxvad/QtSokoban | 71b915a6e551f0158b372ecd60f11378ffc7cc00 | [
"MIT"
] | null | null | null | Source/Singleton.h | bulmaxvad/QtSokoban | 71b915a6e551f0158b372ecd60f11378ffc7cc00 | [
"MIT"
] | 2 | 2019-05-07T21:26:55.000Z | 2019-06-12T18:57:57.000Z | #ifndef SIGLETON_H
#define SIGLETON_H
// This idea takes from https://stackoverflow.com/questions/1008019/c-singleton-design-pattern
template<class T>
class Singleton
{
public:
static T& get()
{
static T instance; // Guaranteed to be destroyed.
return instance;
}
//~ T& operator()() const { return Singleton<T>::get(); }
//~ private:
Singleton() // Constructor? (the {} brackets) are needed here.
{}
public:
Singleton(T const&) = delete;
void operator =(T const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
#endif // SIGLETON_H
| 25.575758 | 94 | 0.64218 |
33e36a347a657527ecd6de0a4020dc59c8657d69 | 256 | c | C | benchmarks/Angha_small/extr_ppatomfwctrl_pp_atomfwctrl_get_avfs_information/extr_ppatomfwctrl_pp_atomfwctrl_get_avfs_information.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | 2 | 2021-03-11T00:46:25.000Z | 2021-07-08T16:44:58.000Z | benchmarks/Angha_small/extr_ppatomfwctrl_pp_atomfwctrl_get_avfs_information/extr_ppatomfwctrl_pp_atomfwctrl_get_avfs_information.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | benchmarks/Angha_small/extr_ppatomfwctrl_pp_atomfwctrl_get_avfs_information/extr_ppatomfwctrl_pp_atomfwctrl_get_avfs_information.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | typedef a;
struct b {
void *c};
struct d {
int e;
int f};
struct b g;
void *g_0;
a h;
a i;
void j() {
k ();
h =
((struct d *)k)->e;
i =
((struct d *)k)->f;
if (h == 4 && i == 1)
g_0 = 0;
if (h == 4 && i )
l();
}
| 10.666667 | 25 | 0.375 |
d46d311e3323d2988270ad3a23b23b353ca0089b | 895 | h | C | test/e2e/test_master/skia/src/pathops/SkPathOpsCommon.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | 50 | 2018-01-12T14:32:26.000Z | 2022-03-30T10:36:30.000Z | test/e2e/test_master/skia/src/pathops/SkPathOpsCommon.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | 8 | 2021-02-18T14:52:08.000Z | 2022-03-09T08:51:39.000Z | test/e2e/test_master/skia/src/pathops/SkPathOpsCommon.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | 12 | 2019-04-02T11:51:47.000Z | 2022-03-07T11:07:39.000Z | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkPathOpsCommon_DEFINED
# define SkPathOpsCommon_DEFINED
# include "include/private/SkTDArray.h"
# include "src/pathops/SkOpAngle.h"
class SkOpCoincidence;
class SkOpContour;
class SkPathWriter;
const SkOpAngle* AngleWinding(SkOpSpanBase* start, SkOpSpanBase* end, int* windingPtr, bool* sortable);
SkOpSegment* FindChase(SkTDArray<SkOpSpanBase*>* chase, SkOpSpanBase** startPtr, SkOpSpanBase** endPtr);
SkOpSpan* FindSortableTop(SkOpContourHead*);
SkOpSpan* FindUndone(SkOpContourHead*);
bool FixWinding(SkPath* path);
bool SortContourList(SkOpContourHead**, bool evenOdd, bool oppEvenOdd);
bool HandleCoincidence(SkOpContourHead*, SkOpCoincidence*);
bool OpDebug(const SkPath& one, const SkPath& two, SkPathOp op, SkPath* result);
#endif
| 38.913043 | 104 | 0.788827 |
54d276f9cc118beb7463f9c47e48504e6988dd87 | 3,570 | h | C | software/libs/cartridge/cartridge.h | bzier/ENGAGE | 3d47a9ee20f02d83c2d032bd4b9567b32e43b61f | [
"MIT"
] | 64 | 2020-12-09T05:25:43.000Z | 2022-03-31T00:21:51.000Z | software/libs/cartridge/cartridge.h | bzier/ENGAGE | 3d47a9ee20f02d83c2d032bd4b9567b32e43b61f | [
"MIT"
] | 1 | 2020-12-04T16:56:58.000Z | 2020-12-08T20:08:13.000Z | software/libs/cartridge/cartridge.h | bzier/ENGAGE | 3d47a9ee20f02d83c2d032bd4b9567b32e43b61f | [
"MIT"
] | 6 | 2020-12-23T05:43:44.000Z | 2022-03-23T08:51:25.000Z | /*
* cartridge.h
*
* Created on: Jan 11, 2020
* Author: TU Delft Sustainable Systems Laboratory
* License: MIT License
*/
#ifndef LIBS_CARTRIDGE_CARTRIDGE_H_
#define LIBS_CARTRIDGE_CARTRIDGE_H_
#include "am_mcu_apollo.h"
#define SX150X_Address 0x20
// SZ1503 device address
#define SX150X_RegDataB 0x00
// RegDataB Data register for Bank B I/O[15:8]
#define SX150X_RegDataA 0x01
// RegDataA Data register for Bank A I/O[7:0]
#define SX150X_RegDirB 0x02
// RegDirB Direction register for Bank B I/O[15:8]
#define SX150X_RegDirA 0x03
// RegDirA Direction register for Bank A I/O[7:0]
#define SX150X_RegPullUpB 0x04
// RegPullUpB Pull-up register for Bank B I/O[15:8]
#define SX150X_RegPullUpA 0x05
// RegPullUpA Pull-up register for Bank A I/O[7:0]
#define SX150X_RegPullDownB 0x06
// RegPullDownB Pull-down register for Bank B I/O[15:8]
#define SX150X_RegPullDownA 0x07
// RegPullDownA Pull-down register for Bank A I/O[7:0]
#define SX150X_RegInterruptMaskB 0x08
// RegInterruptMaskB Interrupt mask register for Bank B I/O[15:8] 1111 1111
#define SX150X_RegInterruptMaskA 0x09
// RegInterruptMaskA Interrupt mask register for Bank A I/O[7:0] 1111 1111
#define SX150X_RegSenseHighB 0x0A
// RegSenseHighB Sense register for I/O[15:12]
#define SX150X_RegSenseHighA 0x0B
// RegSenseHighA Sense register for I/O[7:4]
#define SX150X_RegSenseLowB 0x0C
// RegSenseLowB Sense register for I/O[11:8]
#define SX150X_RegSenseLowA 0x0D
// RegSenseLowA Sense register for I/O[3:0]
#define SX150X_RegInterruptSourceB 0x0E
// RegInterruptSourceB Interrupt source register for Bank B I/O[15:8]
#define SX150X_RegInterruptSourceA 0x0F
// RegInterruptSourceA Interrupt source register for Bank A I/O[7:0]
#define SX150X_RegEventStatusB 0x10
// RegEventStatusB Event status register for Bank B I/O[15:8]
#define SX150X_RegEventStatusA 0x11
// RegEventStatusA Event status register for Bank A I/O[7:0]
#define SX150X_RegPLDModeB 0x20
// RegPLDModeB PLD mode register for Bank B I/O[15:8]
#define SX150X_RegPLDModeA 0x21
// RegPLDModeA PLD mode register for Bank A I/O[7:0]
#define SX150X_RegPLDTable0B 0x22
// RegPLDTable0B PLD truth table 0 for Bank B I/O[15:8]
#define SX150X_RegPLDTable0A 0x23
// RegPLDTable0A PLD truth table 0 for Bank A I/O[7:0]
#define SX150X_RegPLDTable1B 0x24
// RegPLDTable1B PLD truth table 1 for Bank B I/O[15:8]
#define SX150X_RegPLDTable1A 0x25
// RegPLDTable1A PLD truth table 1 for Bank A I/O[7:0]
#define SX150X_RegPLDTable2B 0x26
// RegPLDTable2B PLD truth table 2 for Bank B I/O[15:8]
#define SX150X_RegPLDTable2A 0x27
// RegPLDTable2A PLD truth table 2 for Bank A I/O[7:0]
#define SX150X_RegPLDTable3B 0x28
// RegPLDTable3B PLD truth table 3 for Bank B I/O[15:8]
#define SX150X_RegPLDTable3A 0x29
// RegPLDTable3A PLD truth table 3 for Bank A I/O[7:0]
#define SX150X_RegPLDTable4B 0x2A
// RegPLDTable4B PLD truth table 4 for Bank B I/O[15:8]
#define SX150X_RegPLDTable4A 0x2B
// RegPLDTable4A PLD truth table 4 for Bank A I/O[7:0]
#define SX150X_RegAdvanced 0xAD
// RegAdvanced Advanced settings register
typedef union {
struct {
uint8_t CartridgeCS : 1;
uint8_t CartridgeRDn : 1;
uint8_t CartridgeWRn : 1;
uint8_t CartridgeCLK : 1;
uint8_t CartridgeRSTn : 1;
uint8_t dummy : 3;
};
uint8_t asUint8_t;
} CartridgeControlSignals;
void cartridgeInterfaceConfig();
void cartridgeInterfaceWriteControl(CartridgeControlSignals state);
void cartridgeInterfaceWriteData(uint16_t address, uint8_t data);
void cartridgeInterfaceReadData(uint16_t address, uint8_t* data);
#endif /* LIBS_CARTRIDGE_CARTRIDGE_H_ */
| 36.428571 | 75 | 0.780952 |
883b547c628af437754025591f4540195c82f41f | 1,372 | h | C | include/filter/filter_algorithm.h | NeurotechLtd/dsp | 1ebcdc65f4eb1bee217084de25ab3f9f09f745fc | [
"MIT"
] | null | null | null | include/filter/filter_algorithm.h | NeurotechLtd/dsp | 1ebcdc65f4eb1bee217084de25ab3f9f09f745fc | [
"MIT"
] | null | null | null | include/filter/filter_algorithm.h | NeurotechLtd/dsp | 1ebcdc65f4eb1bee217084de25ab3f9f09f745fc | [
"MIT"
] | 1 | 2019-12-12T08:49:49.000Z | 2019-12-12T08:49:49.000Z | #ifndef FILTER_ALGORITHM_H
#define FILTER_ALGORITHM_H
namespace DSP {
template <typename PassbandType>
class ClassicFilterAlgorithm : private PassbandType{
protected:
template <typename T>
auto filter(const T &sample){
auto V0 = sample;
for (auto i = PassbandType::Order; i > 0; i--) {
V0 = V0 - this->Denominators[i] * this->V[i - 1];
}
auto Y = V0 * this->Numerators[0] + this->V[0] * this->Numerators[1];
for (auto i = PassbandType::Order; i > 1; i--) {
Y = Y + this->Numerators[i] * this->V[i - 1];
this->V[i - 1] = this->V[i - 2];
}
this->V[0] = V0;
return Y;
}
};
template <typename PassbandType>
class FilterSolutionAlgorithm : private PassbandType{
protected:
template <typename T>
T filter(T invar){
T sumden = 0.0, sumnum = 0.0;
for (auto i = decltype(PassbandType::Order){0}; i < PassbandType::Order; i++) {
sumden += this->V[i] * this->Denominators[i];
sumnum += this->V[i] * this->Numerators[i];
if (i < PassbandType::Order - 1) this->V[i] = this->V[i + 1];
}
this->V[PassbandType::Order - 1] = invar - sumden;
sumnum += this->V[PassbandType::Order - 1] * this->Numerators[PassbandType::Order];
return sumnum;
}
};
}
#endif // FILTER_ALGORITHM_H
| 30.488889 | 91 | 0.566327 |
fd420e49d97c8fa005c6ec718b8a862f5ff5f74e | 1,850 | c | C | libdtrace/dt_inttab.c | tjfontaine/dtrace-utils | 1bd5b3825ca0dd641694f795734b9bbbfd3f2ebb | [
"UPL-1.0"
] | 1 | 2021-06-12T05:38:52.000Z | 2021-06-12T05:38:52.000Z | libdtrace/dt_inttab.c | tjfontaine/dtrace-utils | 1bd5b3825ca0dd641694f795734b9bbbfd3f2ebb | [
"UPL-1.0"
] | null | null | null | libdtrace/dt_inttab.c | tjfontaine/dtrace-utils | 1bd5b3825ca0dd641694f795734b9bbbfd3f2ebb | [
"UPL-1.0"
] | null | null | null | /*
* Oracle Linux DTrace.
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include <assert.h>
#include <dt_inttab.h>
#include <dt_impl.h>
dt_inttab_t *
dt_inttab_create(dtrace_hdl_t *dtp)
{
uint_t len = _dtrace_intbuckets;
dt_inttab_t *ip;
assert((len & (len - 1)) == 0);
if ((ip = dt_zalloc(dtp, sizeof (dt_inttab_t))) == NULL ||
(ip->int_hash = dt_zalloc(dtp, sizeof (void *) * len)) == NULL) {
dt_free(dtp, ip);
return (NULL);
}
ip->int_hdl = dtp;
ip->int_hashlen = len;
return (ip);
}
void
dt_inttab_destroy(dt_inttab_t *ip)
{
dt_inthash_t *hp, *np;
for (hp = ip->int_head; hp != NULL; hp = np) {
np = hp->inh_next;
dt_free(ip->int_hdl, hp);
}
dt_free(ip->int_hdl, ip->int_hash);
dt_free(ip->int_hdl, ip);
}
int
dt_inttab_insert(dt_inttab_t *ip, uint64_t value, uint_t flags)
{
uint_t h = value & (ip->int_hashlen - 1);
dt_inthash_t *hp;
if (flags & DT_INT_SHARED) {
for (hp = ip->int_hash[h]; hp != NULL; hp = hp->inh_hash) {
if (hp->inh_value == value && hp->inh_flags == flags)
return (hp->inh_index);
}
}
if ((hp = dt_alloc(ip->int_hdl, sizeof (dt_inthash_t))) == NULL)
return (-1);
hp->inh_hash = ip->int_hash[h];
hp->inh_next = NULL;
hp->inh_value = value;
hp->inh_index = ip->int_index++;
hp->inh_flags = flags;
ip->int_hash[h] = hp;
ip->int_nelems++;
if (ip->int_head == NULL)
ip->int_head = hp;
else
ip->int_tail->inh_next = hp;
ip->int_tail = hp;
return (hp->inh_index);
}
uint_t
dt_inttab_size(const dt_inttab_t *ip)
{
return (ip->int_nelems);
}
void
dt_inttab_write(const dt_inttab_t *ip, uint64_t *dst)
{
const dt_inthash_t *hp;
for (hp = ip->int_head; hp != NULL; hp = hp->inh_next)
*dst++ = hp->inh_value;
}
| 19.473684 | 73 | 0.645405 |
1329d36d40d17d50d041015f574bda1957fcbcab | 5,002 | h | C | scopeprotocols/EyeDecoder2.h | randomplum/scopehal | ed0d009b036e43436925cc35c4092fd44146b9b4 | [
"BSD-3-Clause"
] | null | null | null | scopeprotocols/EyeDecoder2.h | randomplum/scopehal | ed0d009b036e43436925cc35c4092fd44146b9b4 | [
"BSD-3-Clause"
] | null | null | null | scopeprotocols/EyeDecoder2.h | randomplum/scopehal | ed0d009b036e43436925cc35c4092fd44146b9b4 | [
"BSD-3-Clause"
] | null | null | null | /***********************************************************************************************************************
* *
* ANTIKERNEL v0.1 *
* *
* Copyright (c) 2012-2020 Andrew D. Zonenberg *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD 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
@author Andrew D. Zonenberg
@brief Declaration of EyeDecoder2
*/
#include "../scopehal/ProtocolDecoder.h"
#include "../scopehal/CaptureChannel.h"
class EyeCapture2 : public CaptureChannelBase
{
public:
EyeCapture2(size_t width, size_t height);
virtual ~EyeCapture2();
float* GetData()
{ return m_outdata; }
int64_t* GetAccumData()
{ return m_accumdata; }
void Normalize();
protected:
size_t m_width;
size_t m_height;
float* m_outdata;
int64_t* m_accumdata;
public:
//Not really applicable for eye patterns, but...
virtual size_t GetDepth() const;
virtual int64_t GetEndTime() const;
virtual int64_t GetSampleStart(size_t i) const;
virtual int64_t GetSampleLen(size_t i) const;
virtual bool EqualityTest(size_t i, size_t j) const;
virtual bool SamplesAdjacent(size_t i, size_t j) const;
};
class EyeDecoder2 : public ProtocolDecoder
{
public:
EyeDecoder2(std::string color);
virtual void Refresh();
virtual ChannelRenderer* CreateRenderer();
virtual bool NeedsConfig();
virtual bool IsOverlay();
static std::string GetProtocolName();
virtual void SetDefaultName();
virtual bool ValidateChannel(size_t i, OscilloscopeChannel* channel);
virtual double GetVoltageRange();
int64_t GetUIWidth()
{ return m_uiWidth; }
void SetWidth(size_t width)
{
m_width = width;
SetData(NULL);
}
void SetHeight(size_t height)
{
m_height = height;
SetData(NULL);
}
size_t GetWidth()
{ return m_width; }
size_t GetHeight()
{ return m_height; }
PROTOCOL_DECODER_INITPROC(EyeDecoder2)
protected:
size_t m_width;
size_t m_height;
size_t m_uiWidth;
};
| 42.389831 | 120 | 0.47521 |
92ce45f065eb1a430556b02394e2c4131b941ca3 | 5,739 | h | C | src/Cpl/Html.h | ermig1979/Cpl | 2b3a39712327232c66927d2755c7c3342ab837f4 | [
"MIT"
] | 1 | 2022-02-14T07:54:46.000Z | 2022-02-14T07:54:46.000Z | src/Cpl/Html.h | ermig1979/Cpl | 2b3a39712327232c66927d2755c7c3342ab837f4 | [
"MIT"
] | null | null | null | src/Cpl/Html.h | ermig1979/Cpl | 2b3a39712327232c66927d2755c7c3342ab837f4 | [
"MIT"
] | null | null | null | /*
* Common Purpose Library (http://github.com/ermig1979/Cpl).
*
* Copyright (c) 2021-2022 Yermalayeu Ihar.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include "Cpl/Defs.h"
namespace Cpl
{
struct Html
{
struct Attribute
{
String name, value;
Attribute(const String& n = String(), const String& v = String())
: name(n)
, value(v)
{
}
};
typedef std::vector<Attribute> Attributes;
static Attributes Attr()
{
return Attributes();
}
static Attributes Attr(
const String& name0, const String& value0)
{
Attributes attrbutes;
attrbutes.push_back(Attribute(name0, value0));
return attrbutes;
}
static Attributes Attr(
const String& name0, const String& value0,
const String& name1, const String& value1)
{
Attributes attrbutes;
attrbutes.push_back(Attribute(name0, value0));
attrbutes.push_back(Attribute(name1, value1));
return attrbutes;
}
static Attributes Attr(
const String& name0, const String& value0,
const String& name1, const String& value1,
const String& name2, const String& value2)
{
Attributes attrbutes;
attrbutes.push_back(Attribute(name0, value0));
attrbutes.push_back(Attribute(name1, value1));
attrbutes.push_back(Attribute(name2, value2));
return attrbutes;
}
Html(std::ostream& stream, size_t indent = 0)
: _stream(stream)
, _indent(indent)
, _line(true)
{
}
void WriteIndent()
{
static const String INDENT = " ";
for (size_t i = 0; i < _indent; ++i)
_stream << INDENT;
}
void WriteAtribute(const Attribute& attribute)
{
_stream << " " << attribute.name << "=\"" << attribute.value << "\"";
}
void WriteBegin(const String& name, const Attributes& attributes, bool indent, bool line)
{
if (_line)
WriteIndent();
_stream << "<" << name;
for (size_t i = 0; i < attributes.size(); ++i)
WriteAtribute(attributes[i]);
_stream << ">";
if (line)
_stream << std::endl;
if (indent)
_indent++;
_line = line;
}
void WriteEnd(const String& name, bool indent, bool line)
{
if (indent)
{
_indent--;
if (_line)
WriteIndent();
}
_stream << "</" << name << ">";
if (line)
_stream << std::endl;
_line = line;
}
void WriteValue(const String& name, const Attributes& attributes, const String& value, bool line)
{
WriteBegin(name, attributes, false, false);
WriteWithShielding(value);
WriteEnd(name, false, line);
}
void WriteText(const String& text, bool indent, bool line, bool shielding = true)
{
if (indent && _line)
WriteIndent();
if (shielding)
WriteWithShielding(text);
else
_stream << text;
if (line)
_stream << std::endl;
_line = line;
}
size_t Indent() const
{
return _indent;
}
private:
std::ostream& _stream;
size_t _indent;
bool _line;
void WriteWithShielding(const String& text, char ignore = 0)
{
for (size_t i = 0; i < text.size(); ++i)
{
if (text[i] == ignore)
_stream << text[i];
else
{
switch (text[i])
{
case '<': _stream << "<"; break;
case '>': _stream << ">"; break;
case '\'': _stream << "'"; break;
case '"': _stream << """; break;
case '&': _stream << "&"; break;
default:
_stream << text[i];
}
}
}
}
};
}
| 31.532967 | 106 | 0.496254 |
1f3c6db9725ee7e66275a3c76ef5dc45a7030f89 | 707 | h | C | Assignment4/hashmap.h | we8809/Project-C | b661a17e0007466029af8e2102219cc8403a04e6 | [
"MIT"
] | null | null | null | Assignment4/hashmap.h | we8809/Project-C | b661a17e0007466029af8e2102219cc8403a04e6 | [
"MIT"
] | null | null | null | Assignment4/hashmap.h | we8809/Project-C | b661a17e0007466029af8e2102219cc8403a04e6 | [
"MIT"
] | null | null | null | #ifndef HASHMAP_H
#define HASHMAP_H
#include "node.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE (1)
#define FALSE (0)
typedef struct hashmap {
size_t (*hash_func)(const char* key);
node_t** plist;
size_t length;
} hashmap_t;
hashmap_t* init_hashmap_malloc(size_t length, size_t (*p_hash_func)(const char* key));
int add_key(hashmap_t* hashmap, const char* key, const int value);
int get_value(const hashmap_t* hashmap, const char* key);
int update_value(hashmap_t* hashmap, const char* key, int value);
int remove_key(hashmap_t* hashmap, const char* key);
void destroy(hashmap_t* hashmap);
void print_hashmap(hashmap_t* hashmap);
#endif /* HASHMAP_H */
| 24.37931 | 86 | 0.729844 |
deaa17f4e5a7699b00877253bc52d66b3d88480f | 2,328 | c | C | module/parseresponse.c | Neboer/ipgw_linux_c | 77df9c27e4608c7a97b4d0b87fbc93115a970729 | [
"MIT"
] | 3 | 2019-06-01T08:12:57.000Z | 2020-10-10T16:47:35.000Z | module/parseresponse.c | Neboer/mini_ipgw | 77df9c27e4608c7a97b4d0b87fbc93115a970729 | [
"MIT"
] | 3 | 2019-05-23T08:41:28.000Z | 2020-10-15T08:24:35.000Z | module/parseresponse.c | Neboer/mini_ipgw | 77df9c27e4608c7a97b4d0b87fbc93115a970729 | [
"MIT"
] | 1 | 2019-05-13T12:23:08.000Z | 2019-05-13T12:23:08.000Z | // parse the response of return data.
// E2531: User not found.(用户不存在)
// 您似乎未曾连接到网络...
// 注销失败:Password is error.
// 网络已断开
/* 通过sscanf比较指定位置是否有特定的字符串来判断响应类型。如果指定位置字符串与所有模式均不匹配,则说明返回值错误。
* 返回值错误的情况下,将启动自动纠错,尝试在返回全文中搜索每一种可能参与比较的字符串,
* 如果搜索成功,则返回结果,并且重写settings.json文件中关于搜索位置的选项。*/
#include "parseresponse.h"
#include "makerequest.h"
#include "settings.h"
#include <stdio.h>
#include <string.h>
struct compare_instant {
char *pattern, *user_not_found, *password_error, *already_online, *connected;
};
struct compare_instant makeCompareInstant() {
struct compare_instant instant;
instant.pattern = getSettingsObject(1, "match_pattern");
instant.user_not_found = getSettingsObject(2, "compare_string", "user not found");
instant.password_error = getSettingsObject(2, "compare_string", "password error");
instant.already_online = getSettingsObject(2, "compare_string", "already online");
instant.connected = getSettingsObject(2, "compare_string", "connected");
return instant;
}
int parseIpgwResult(requests req) {
if (req.type == IPGW_REQUEST_LOGIN) {
if (req.code == 503) return IPGW_SERVICE_UNAVAILABLE;
else if (req.code == 200) {
char errStr[10];
struct compare_instant instant = makeCompareInstant();
if (!instant.pattern) return -1;
sscanf(req.content, instant.pattern, errStr);// TODO: potential over-copy leak.
if (strcmp(errStr, instant.user_not_found) == 0) return IPGW_USER_NOT_FOUND;
if (strcmp(errStr, instant.password_error) == 0) return IPGW_PASSWORD_ERROR;
if (strcmp(errStr, instant.already_online) == 0) return IPGW_ALREADY_ONLINE;
if (strcmp(errStr, instant.connected) == 0) return IPGW_NETWORK_CONNECTED;
else {
fprintf(stderr, "parse ipgw response error!Error comparision string:\n%s\n", errStr);
return -1;
}
} else {
fprintf(stderr, "error get code %d\n", req.code);
return -2;
}
} else if (req.type == IPGW_REQUEST_LOGOUT) {
printf("%s\n", req.content);
if (strcmp(req.content, "网络已断开") == 0) {
return IPGW_NETWORK_DISCONNECTED;
}
return IPGW_NETWORK_DISCONNECTED_ERROR;
} else {
return -1;
}
}
| 39.457627 | 101 | 0.659794 |
93013198366fd9a7a45783fa2f45eedd0b646a5a | 817 | h | C | clients/c/generated/model/list_view.h | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/c/generated/model/list_view.h | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/c/generated/model/list_view.h | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | /*
* list_view.h
*
*
*/
#ifndef _list_view_H_
#define _list_view_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "../include/binary.h"
typedef struct list_view_t list_view_t;
#include "free_style_project.h"
typedef struct list_view_t {
char *_class; // string
char *description; // string
list_t *jobs; //nonprimitive container
char *name; // string
char *url; // string
} list_view_t;
list_view_t *list_view_create(
char *_class,
char *description,
list_t *jobs,
char *name,
char *url
);
void list_view_free(list_view_t *list_view);
list_view_t *list_view_parseFromJSON(cJSON *list_viewJSON);
cJSON *list_view_convertToJSON(list_view_t *list_view);
#endif /* _list_view_H_ */
| 17.382979 | 59 | 0.70257 |
87c52071817f64b5c4d1a75a389b9ed336327b15 | 1,105 | c | C | libpassgen/unicode.c | xfbs/passgen | cfcf49ec5a0f9222822037222e0baa223912ac12 | [
"MIT"
] | 3 | 2019-11-14T16:33:31.000Z | 2021-06-23T03:54:43.000Z | libpassgen/unicode.c | xfbs/passgen | cfcf49ec5a0f9222822037222e0baa223912ac12 | [
"MIT"
] | 2 | 2019-07-27T21:37:58.000Z | 2022-03-03T10:03:38.000Z | libpassgen/unicode.c | xfbs/passgen | cfcf49ec5a0f9222822037222e0baa223912ac12 | [
"MIT"
] | null | null | null | #include "passgen/unicode.h"
#include <string.h>
#include <utf8proc.h>
#define MIN_BUFLEN 8
struct unicode_iter unicode_iter(const char *data) {
return unicode_iter_sized(data, strlen(data));
}
struct unicode_iter unicode_iter_sized(const char *data, size_t length) {
struct unicode_iter iter = {
.data = data,
.length = length,
.pos = 0,
};
return iter;
}
struct unicode_iter_result unicode_iter_peek(const struct unicode_iter *iter) {
struct unicode_iter_result result;
if(iter->pos >= iter->length) {
result.ok = false;
result.error = 0;
result.codepoint = 0;
return result;
}
result.error = utf8proc_iterate(
(const utf8proc_uint8_t *) (iter->data) + iter->pos,
iter->length - iter->pos,
&result.codepoint);
if(result.error > 0) {
result.ok = true;
} else {
result.ok = false;
}
return result;
}
struct unicode_iter_result unicode_iter_next(struct unicode_iter *iter) {
struct unicode_iter_result result = unicode_iter_peek(iter);
if(result.ok) {
iter->pos += result.error;
}
return result;
}
| 20.462963 | 79 | 0.674208 |
c66ef4c4f5c9c512367daa972ebd32ad73d0bb5b | 210 | c | C | Section 12/fn9.c | PacktPublishing/Programming-in-C-The-Complete-Course | 2cfa857cfc17cb6104eea9a306aa01188a7b1f6f | [
"MIT"
] | 5 | 2020-05-22T09:17:56.000Z | 2021-11-14T14:18:48.000Z | Section 12/fn9.c | PacktPublishing/Programming-in-C-The-Complete-Course | 2cfa857cfc17cb6104eea9a306aa01188a7b1f6f | [
"MIT"
] | null | null | null | Section 12/fn9.c | PacktPublishing/Programming-in-C-The-Complete-Course | 2cfa857cfc17cb6104eea9a306aa01188a7b1f6f | [
"MIT"
] | 6 | 2020-02-21T15:11:08.000Z | 2022-02-09T16:25:03.000Z | /* A sample program that illustrates that local variables are given precedence */
#include <stdio.h>
int n=10 ; // global variable
int main()
{
int n=90 ; // local variable
printf("%d\n",n);
}
| 17.5 | 82 | 0.633333 |
f4421a87fb28f0dcf012e705136b25d3d93a1fb8 | 438 | h | C | lib/include/jsonrpc/net/IDispatcher.h | a-kuntz/JsonRPC | 8ff47c5414e1ca929b741ea2af5f704bbe6ae13f | [
"MIT"
] | 1 | 2021-11-10T01:17:57.000Z | 2021-11-10T01:17:57.000Z | lib/include/jsonrpc/net/IDispatcher.h | a-kuntz/JsonRPC | 8ff47c5414e1ca929b741ea2af5f704bbe6ae13f | [
"MIT"
] | null | null | null | lib/include/jsonrpc/net/IDispatcher.h | a-kuntz/JsonRPC | 8ff47c5414e1ca929b741ea2af5f704bbe6ae13f | [
"MIT"
] | null | null | null | #ifndef HEADER_5E86F08A_9564_11EA_AFCA_784F43782D09
#define HEADER_5E86F08A_9564_11EA_AFCA_784F43782D09
#include <jsonrpc/Config.h>
#include <string>
namespace jsonrpc
{
namespace net
{
struct IDispatcher
{
virtual std::string dispatch(const std::string& data) = 0;
virtual ~IDispatcher() = default;
};
} // namespace net
} // namespace jsonrpc
#endif // HEADER_5E86F08A_9564_11EA_AFCA_784F43782D09
| 19.043478 | 65 | 0.732877 |
7382dbcc9309d540f2ae2ddbfd471f867f15597d | 1,007 | h | C | PrivateFrameworks/PhotosUICore/PXSearchResultsSectionedDataSourceChangeObserver-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/PhotosUICore/PXSearchResultsSectionedDataSourceChangeObserver-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/PhotosUICore/PXSearchResultsSectionedDataSourceChangeObserver-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSIndexPath, NSIndexSet, PXSearchResultsSectionedDataSource, PXSearchResultsValue, PXSearchTopAssetsResult;
@protocol PXSearchResultsSectionedDataSourceChangeObserver <NSObject>
- (void)searchResultsDataSource:(PXSearchResultsSectionedDataSource *)arg1 didChangeThumbnailAssetsForSearchResult:(PXSearchTopAssetsResult *)arg2 atIndexes:(NSIndexSet *)arg3;
- (void)searchResultsDataSource:(PXSearchResultsSectionedDataSource *)arg1 didChangeThumbnailAssetsForSearchResult:(PXSearchTopAssetsResult *)arg2 topAssetsSectionExists:(BOOL)arg3;
- (void)searchResultsDataSource:(PXSearchResultsSectionedDataSource *)arg1 didFetchAssetsForSearchResult:(PXSearchResultsValue *)arg2 indexPath:(NSIndexPath *)arg3;
- (void)searchResultsDataSourceHasPendingChanges:(PXSearchResultsSectionedDataSource *)arg1 shouldMergePendingChanges:(BOOL)arg2;
@end
| 55.944444 | 181 | 0.836147 |
ad52829185a8d4be48b9954f0c5688b32fd001ac | 3,444 | h | C | Core/runtime/v8/object_wrap.h | InfiniteSynthesis/lynx-native | 022e277ee6767f5b668269a17b1679072cf7c3d6 | [
"MIT"
] | 677 | 2017-09-23T16:03:12.000Z | 2022-03-26T08:32:10.000Z | Core/runtime/v8/object_wrap.h | InfiniteSynthesis/lynx-native | 022e277ee6767f5b668269a17b1679072cf7c3d6 | [
"MIT"
] | 3 | 2018-06-11T02:04:02.000Z | 2020-04-24T09:26:05.000Z | Core/runtime/v8/object_wrap.h | InfiniteSynthesis/lynx-native | 022e277ee6767f5b668269a17b1679072cf7c3d6 | [
"MIT"
] | 92 | 2017-09-21T14:21:27.000Z | 2022-03-25T13:29:42.000Z | // Copyright 2017 The Lynx Authors. All rights reserved.
#ifndef LYNX_RUNTIME_V8_OBJECT_WRAP_H_
#define LYNX_RUNTIME_V8_OBJECT_WRAP_H_
#if USING_V8
#include "v8.h"
#include <assert.h>
#include "runtime/js/object_wrap.h"
#include "base/debug/memory_debug.h"
namespace jscore {
class V8Context;
class V8ObjectWrap : public ObjectWrap {
public:
V8ObjectWrap(V8Context* context, LynxObject* object, v8::Local<v8::Object> handle);
virtual ~V8ObjectWrap();
virtual void Update();
virtual void Protect() {
assert(!persistent().IsEmpty());
persistent().ClearWeak();
refs_++;
}
virtual void Unprotect() {
assert(!persistent().IsEmpty());
assert(!persistent().IsWeak());
assert(refs_ > 0);
if (--refs_ == 0)
MakeWeak();
}
virtual void RegisterMethodCallback(const std::string& method_name, JSMethodCallback callback);
virtual void OnJSObjectInitialize();
virtual void OnJSObjectFinalize();
template<class T>
static inline T *Unwrap(v8::Local<v8::Object> handle) {
assert(!handle.IsEmpty());
assert(handle->InternalFieldCount() > 0);
// Cast to ObjectWrap before casting to T. A direct cast from void
// to T won't work right when T has more than one base class.
void *ptr = handle->GetAlignedPointerFromInternalField(0);
ObjectWrap *wrap = static_cast<ObjectWrap *>(ptr);
return static_cast<T *>(wrap->lynx_object());
}
static inline void Wrap(V8Context* context, LynxObject* lynx_object, v8::Local<v8::Object> handle) {
lynx_new V8ObjectWrap(context, lynx_object, handle);
}
inline v8::Local <v8::Object> handle() {
return handle(v8::Isolate::GetCurrent());
}
inline v8::Local <v8::Object> handle(v8::Isolate *isolate) {
return v8::Local<v8::Object>::New(isolate, persistent());
}
inline v8::Persistent <v8::Object> &persistent() {
return handle_;
}
protected:
inline void Wrap(v8::Isolate* isolate, v8::Local<v8::Object> handle) {
assert(persistent().IsEmpty());
assert(handle->InternalFieldCount() > 0);
handle->SetAlignedPointerInInternalField(0, this);
// Special case: prototype of global also has internal field count as InstanceTemplate set
// and it may be used as this in get or set callback so a c++ point should be set to
// prevent crash.
if (handle->GetPrototype()->ToObject()->InternalFieldCount() > 0) {
handle->GetPrototype()->ToObject()->SetAlignedPointerInInternalField(0, this);
}
persistent().Reset(isolate, handle);
MakeWeak();
}
inline void MakeWeak(void) {
persistent().SetWeak(this,
WeakCallback,
v8::WeakCallbackType::kParameter);
persistent().MarkIndependent();
}
static void WeakCallback(
const v8::WeakCallbackInfo<V8ObjectWrap>& data) {
v8::Isolate *isolate = data.GetIsolate();
v8::HandleScope scope(isolate);
V8ObjectWrap *wrap = data.GetParameter();
assert(wrap->refs_ == 0);
assert(wrap->handle_.IsNearDeath());
wrap->handle_.Reset();
lynx_delete(wrap);
}
private:
v8::Persistent<v8::Object> handle_;
int refs_;
};
} // namespace jscore
#endif
#endif // LYNX_RUNTIME_V8_OBJECT_WRAP_H_
| 30.477876 | 104 | 0.634146 |
51e0f5df7b2eb71ea6c6e68aa53316f3c4dbffd1 | 379 | c | C | src/libc/uv/uv_ip4_addr.c | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 298 | 2015-03-04T13:36:51.000Z | 2021-12-19T05:11:58.000Z | src/libc/uv/uv_ip4_addr.c | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 31 | 2015-07-27T14:51:55.000Z | 2020-09-14T15:59:57.000Z | src/libc/uv/uv_ip4_addr.c | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 18 | 2016-03-27T13:49:22.000Z | 2021-09-21T19:02:04.000Z | // Copyright (c) 2017 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <sys/socket.h>
#include <netinet/in.h>
#include <uv.h>
int uv_ip4_addr(const char *ip, int port, struct sockaddr_in *addr) {
*addr = (struct sockaddr_in){
.sin_family = AF_INET,
.sin_port = htons(port),
};
return uv_inet_pton(AF_INET, ip, &addr->sin_addr);
}
| 21.055556 | 69 | 0.662269 |
f619d2ea6dc3d6747f5df32479bea27b909e35c1 | 11,232 | h | C | hashing/tmk/cpp/algo/tmkfv.h | Brown4017/Facebook-Image-Video-2019 | cbc64771035b41d714d69d45dc6ff03eb18e2674 | [
"BSD-3-Clause"
] | 1 | 2020-01-10T04:07:18.000Z | 2020-01-10T04:07:18.000Z | hashing/tmk/cpp/algo/tmkfv.h | Brown4017/Facebook-Image-Video-2019 | cbc64771035b41d714d69d45dc6ff03eb18e2674 | [
"BSD-3-Clause"
] | null | null | null | hashing/tmk/cpp/algo/tmkfv.h | Brown4017/Facebook-Image-Video-2019 | cbc64771035b41d714d69d45dc6ff03eb18e2674 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2004-present Facebook. All Rights Reserved.
// ================================================================
// Wrapper class for TMK feature-vectors. It includes methods for
// computing them on a streaming basis from frame-features, one frame-feature
// at a time, as well as methods for manipulating them when loaded from disk.
// ================================================================
// ================================================================
// TMK NORMALIZED SCORING:
//
// The level-1 score is the cosine similarity between two pure-average
// features. It is not TMK. It is a criterion we use to determine whether or
// not to compute the full TMK pair score. (It has been found that when the
// level-1 scores differ significantly, the level-2 scores will as well, so the
// expensive level-2 score can be skipped. On the other hand, if the level-1
// scores are close, the level-2 scores might not be.)
//
// The TMK pair score (a.k.a. level-2 score) is as follows:
//
// For single videos:
// * Have P periods (nominally four of them).
// * Have m fourier coefficents a_0 through a_{m-1} (nominally m=32).
// * Note that the dot product is bilinear on vectors u and v so if u and v
// are both scaled by sqrt(a_j) then their dot is scaled by a_j.
// * For each period accumulate m cosine features and m sine features.
// * Suppose there are N frame-features ("frame hashes").
// * L2-normalize these.
// * 0th cosine feature is sqrt(a_0) sum_{over frames} (frame feature)
// * 0th sine feature is always zero
// * jth cosine feature is sqrt(a_j) sum_{over frames} (frame feature
// times cos(2 pi j t T))
// where T is the period and t is the integer timestamp of the frame
// * jth sine feature is sqrt(a_j) sum_{over frames} (frame feature
// times sin(2 pi j t T))
// where T is the period and t is the integer timestamp of the frame
// * Once frame-features are all ingested then L2-normalize all the
// cosine/sine features and then scale by sqrt(a_j).
//
// To score a pair of videos:
// * For each period T iterate over all offsets 0 .. T-1
// * For a given period and offset compute (see Poullot or Baraldi paper)
// o delta = 2 pi offset / period
// o Let u_{c,j} and u_{s,j} be the jth cosine/sine feature for the 1st video
// o Let v_{c,j} and v_{s,j} be the jth cosine/sine feature for the 1st video
// o Recall these have norm a_j: each vector is scaled by sqrt(a_j) so norms
// are a_j.
// o K_delta = u_{c,0} . v_{c,0}
// + sum_{j=1}^{m-1} cos(j delta) * (u_{c,j} . v_{c,j} + u_{s,j} . v_{s,j})
// + sum_{j=1}^{m-1} sin(j delta) * (u_{s,j} . v_{c,j} - u_{c,j} . v_{s,j})
// * For a given period, the TMK score is the maximum of K_delta for all
// offsets.
// * The TMK score for the pair of videos is either the max or sum over all
// periods.
//
// All well and good but now we need to normalize these to get a score between
// 0 and 1.
//
// To get that, suppose we are scoring a video with itself. This means each
// feature u_{.,j} == v_{.,j} and best offset is delta = 0.
//
// Then for each period,
//
// K_delta = u_{c,0} . u_{c,0}
// + sum_{j=1}^{m-1} cos(j delta) * (u_{c,j} . u_{c,j} + u_{s,j} . u_{s,j})
// + sum_{j=1}^{m-1} sin(j delta) * (u_{s,j} . u_{c,j} - u_{c,j} . u_{s,j})
//
// Since u_{.,j} . u_{.,j} = a_j (normalization) this is
//
// K_delta = a_0
// + sum_{j=1}^{m-1} cos(j delta) * 2 a_j
// + sum_{j=1}^{m-1} sin(j delta) * 0
//
// = a_0 + 2 sum_{j=1}^{m-1} cos(j delta)
//
// and since delta = 0 at best offset for self-scoring
//
// K_0 = a_0 + 2 sum_{j=1}^{m-1} a_j
//
// In the code below, this sum
//
// a_0 + 2 sum_{j=1}^{m-1} a_j
//
// is called _pairScoreNormalizer.
// ================================================================
#ifndef TMKFV_H
#define TMKFV_H
#include <stdio.h>
#include <tmk/cpp/io/tmkio.h>
#include <memory>
#include <vector>
namespace facebook {
namespace tmk {
namespace algo {
// ----------------------------------------------------------------
// TMK ingests frame-features or hashes. They are accumulated as time-weighted
// sums index by fourier period, then by fourier coefficients.
// These are parameters for TMK frame-feature processing:
using Periods = std::vector<int>;
// These are parameters for TMK frame-feature processing:
using FourierCoefficients = std::vector<float>;
// These are input to TMK frame-feature processing, also used for TMK
// internal state:
using FrameFeature = std::vector<float>;
// TMK internal state: The cosine/sine-feature dimensions are
//
// (numPeriods x numFourierCoefficients x frameFeatureDimension).
//
// If either numPeriods or numFourierCoefficients (or both) is zero then
// only the pure-average "level-1" feature will be computed.
using FeaturesByFourierCoefficient = std::vector<FrameFeature>;
using FeaturesByPeriodsAndFourierCoefficients =
std::vector<FeaturesByFourierCoefficient>;
// TMK alignment. Length is number of periods. These are used for detailed
// TMK-alignment values (when desired).
using BestOffsets = std::vector<int>;
using ValuesAtBestOffsets = std::vector<float>;
const int TMK_DEFAULT_RESAMPLE_FPS = 15;
// ================================================================
class TMKFeatureVectors {
// ----------------------------------------------------------------
private:
facebook::tmk::io::TMKFramewiseAlgorithm _algorithm;
int _framesPerSecond; // provenance of the data
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Input coefficients
Periods _periods;
FourierCoefficients _fourierCoefficients;
int _frameFeatureDimension;
int _frameFeatureCount;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Output features
// This is guaranteed to be independent of any model-training parameters.
FrameFeature _pureAverageFeature;
// These ones may depend on model-training parameters.
// As noted above, the cosine/sine-feature dimensions are
//
// (numPeriods x numFourierCoefficients x frameFeatureDimension).
//
// This means:
// * Outer index is 0 to _periods.size() - 1 inclusive.
// * Middle index is 0 to _fourierCoefficients.size() - 1 inclusive.
// * Inner index is 0 to _frameFeatureDimension - 1 inclusive.
//
// This therefore means that cosine/sine-feature dimensions
// are (numPeriods x numFourierCoefficients x frameFeatureDimension).
FeaturesByPeriodsAndFourierCoefficients _cosFeatures;
FeaturesByPeriodsAndFourierCoefficients _sinFeatures;
// When we compute the TMK score of a hashed video with itself, we want 1.0.
// This number does that. The algebraic derivation is above.
float _pairScoreNormalizer;
// ----------------------------------------------------------------
public:
TMKFeatureVectors() {}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// For constructing before computing from frame features.
TMKFeatureVectors(
facebook::tmk::io::TMKFramewiseAlgorithm algorithm, // provenance
int framesPerSecond, // provenance
const Periods& periods,
const FourierCoefficients& fourierCoefficients,
int frameFeatureDimension);
// For constructing after computing from frame features, e.g. load from
// file. Since it is possible for the dimensions to be inconsistent, we make
// this private and provide access via a factory method.
private:
TMKFeatureVectors(
facebook::tmk::io::TMKFramewiseAlgorithm algorithm, // provenance
int framesPerSecond, // provenance
int frameFeatureCount, // informational
const Periods& periods,
const FourierCoefficients& fourierCoefficients,
const FrameFeature& pureAverageFeature,
const FeaturesByPeriodsAndFourierCoefficients& cosFeatures,
const FeaturesByPeriodsAndFourierCoefficients& sinFeatures);
public:
// See the above private constructor. This is used for reading precomputed
// results from storage.
static std::shared_ptr<TMKFeatureVectors> tryCreateFromPrecomputed(
facebook::tmk::io::TMKFramewiseAlgorithm algorithm,
int framesPerSecond,
int frameFeatureCount,
const Periods& periods,
const FourierCoefficients& fourierCoefficients,
const FrameFeature& pureAverageFeature,
const FeaturesByPeriodsAndFourierCoefficients& cosFeatures,
const FeaturesByPeriodsAndFourierCoefficients& sinFeatures);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Checks the two are computed using the same periods, same framewise hasher,
// etc.
static bool areCompatible(
const TMKFeatureVectors& fva,
const TMKFeatureVectors& fvb);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
static Periods makePoullotPeriods();
static FourierCoefficients makePoullotFourierCoefficients();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ingestFrameFeature(const FrameFeature& frameFeature, int frameNumber);
void finishFrameFeatureIngest();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool writeToOutputStream(FILE* fp, const char* programName) const;
bool writeToOutputFile(const char* fileName, const char* programName) const;
static std::shared_ptr<TMKFeatureVectors> readFromInputStream(
FILE* fp,
const char* programName);
static std::shared_ptr<TMKFeatureVectors> readFromInputFile(
const char* fileName,
const char* programName);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
facebook::tmk::io::TMKFramewiseAlgorithm getAlgorithm() const {
return _algorithm;
}
int getNumPeriods() const {
return _periods.size();
}
int getNumFourierCoefficients() const {
return _fourierCoefficients.size();
}
int getFrameFeatureDimension() const {
return _frameFeatureDimension;
}
int getFramesPerSecond() const {
return _framesPerSecond;
}
int getFrameFeatureCount() const {
return _frameFeatureCount;
}
Periods getPeriods() const {
return _periods;
}
FourierCoefficients getFourierCoefficients() const {
return _fourierCoefficients;
}
FrameFeature getPureAverageFeature() const {
return _pureAverageFeature;
}
FeaturesByPeriodsAndFourierCoefficients getCosFeatures() const {
return _cosFeatures;
}
FeaturesByPeriodsAndFourierCoefficients getSinFeatures() const {
return _sinFeatures;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void L2NormalizePureAverageFeature();
static void findPairOffsetsModuloPeriods(
const TMKFeatureVectors& fva,
const TMKFeatureVectors& fvb,
BestOffsets& bestOffsets,
ValuesAtBestOffsets& valuesAtBestOffsets,
bool printDetails);
static float computeLevel1Score(
const TMKFeatureVectors& fva,
const TMKFeatureVectors& fvb);
static float computeLevel2Score(
const TMKFeatureVectors& fva,
const TMKFeatureVectors& fvb);
static bool compare(
const TMKFeatureVectors& fva,
const TMKFeatureVectors& fvb,
float tolerance);
};
} // namespace algo
} // namespace tmk
} // namespace facebook
#endif // TMKFV_H
| 36.115756 | 79 | 0.641916 |
22301d03cd5e33c98b264787b3ad4a286f64e20d | 374 | h | C | AudioCall/UI/ACCallFailedViewController.h | voximplant/ios-sdk-objc-demo | 5bb5430a4017f4fe400ad6a594022c9052ffc1a5 | [
"MIT"
] | null | null | null | AudioCall/UI/ACCallFailedViewController.h | voximplant/ios-sdk-objc-demo | 5bb5430a4017f4fe400ad6a594022c9052ffc1a5 | [
"MIT"
] | 1 | 2020-05-20T10:10:09.000Z | 2020-05-20T11:44:18.000Z | AudioCall/UI/ACCallFailedViewController.h | voximplant/ios-sdk-objc-demo | 5bb5430a4017f4fe400ad6a594022c9052ffc1a5 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2011-2019, Zingaya, Inc. All rights reserved.
*/
#import <UIKit/UIKit.h>
#import "ACCallManager.h"
NS_ASSUME_NONNULL_BEGIN
@interface ACCallFailedViewController : UIViewController<ACCallManagerDelegate>
@property (strong, nonatomic) NSString *failingReason;
@property (strong, nonatomic) NSString *endpointDisplayName;
@end
NS_ASSUME_NONNULL_END
| 20.777778 | 79 | 0.78877 |
6182e2dc141a2b5150788d824f4e779255ce4858 | 667 | h | C | GoodDay/GoodDay/CityModel.h | mengxiangjian13/GoodWeather | 8e9a0fea635ba1c2374556269cd139d4886845d4 | [
"MIT"
] | null | null | null | GoodDay/GoodDay/CityModel.h | mengxiangjian13/GoodWeather | 8e9a0fea635ba1c2374556269cd139d4886845d4 | [
"MIT"
] | null | null | null | GoodDay/GoodDay/CityModel.h | mengxiangjian13/GoodWeather | 8e9a0fea635ba1c2374556269cd139d4886845d4 | [
"MIT"
] | null | null | null | //
// CityModel.h
// GoodDay
//
// Created by Xiangjian Meng on 14/12/17.
// Copyright (c) 2014年 cn.com.modernmedia. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CityModel : NSObject
@property (nonatomic,strong) NSString *backgroundImageName;
@property (nonatomic,strong) NSString *name; // city name
@property (nonatomic,strong) NSString *customName; // show name
@property (nonatomic,strong) NSNumber *lat; // latitude
@property (nonatomic,strong) NSNumber *lon; // longitude
@property (nonatomic,strong) NSString *identifier;
@property (nonatomic,strong) NSString *country;
@property (nonatomic,assign) BOOL isCurrentLocation;
@end
| 29 | 64 | 0.751124 |
959584da8835ec4dcc8ca86456fb6e4df79ec3c2 | 13,184 | c | C | orte/mca/odls/base/odls_base_open.c | DmitrySigaev/ompi-release | 762d64c08aeeba62c1950c7c2fb3c2915afcb044 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orte/mca/odls/base/odls_base_open.c | DmitrySigaev/ompi-release | 762d64c08aeeba62c1950c7c2fb3c2915afcb044 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orte/mca/odls/base/odls_base_open.c | DmitrySigaev/ompi-release | 762d64c08aeeba62c1950c7c2fb3c2915afcb044 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "orte_config.h"
#include "orte/constants.h"
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#if !ORTE_DISABLE_FULL_SUPPORT
#include "opal/mca/mca.h"
#include "opal/mca/base/base.h"
#include "opal/mca/base/mca_base_param.h"
#include "opal/mca/hwloc/base/base.h"
#include "opal/mca/paffinity/base/base.h"
#include "opal/mca/sysinfo/sysinfo.h"
#include "opal/util/output.h"
#include "opal/util/path.h"
#include "opal/util/argv.h"
#include "orte/mca/plm/plm_types.h"
#include "orte/mca/errmgr/errmgr.h"
#include "orte/util/name_fns.h"
#include "orte/runtime/orte_globals.h"
#include "orte/util/show_help.h"
#include "orte/util/parse_options.h"
#include "orte/mca/odls/base/odls_private.h"
#endif
#include "orte/mca/odls/base/base.h"
/*
* The following file was created by configure. It contains extern
* statements and the definition of an array of pointers to each
* component's public mca_base_component_t struct.
*/
#include "orte/mca/odls/base/static-components.h"
#if ORTE_DISABLE_FULL_SUPPORT
/* have to include a bogus function here so that
* the build system sees at least one function
* in the library
*/
int orte_odls_base_open(void)
{
return ORTE_SUCCESS;
}
#else
/*
* Instantiate globals
*/
orte_odls_base_module_t orte_odls = {0};
/* instance the child list object */
static void orte_odls_child_constructor(orte_odls_child_t *ptr)
{
ptr->name = NULL;
ptr->restarts = 0;
ptr->pid = 0;
ptr->app_idx = -1;
ptr->alive = false;
ptr->coll_recvd = false;
/* set the default state to "failed to start" so
* we can correctly report should something
* go wrong during launch
*/
ptr->state = ORTE_PROC_STATE_FAILED_TO_START;
ptr->exit_code = 0;
ptr->init_recvd = false;
ptr->fini_recvd = false;
ptr->rml_uri = NULL;
ptr->slot_list = NULL;
ptr->waitpid_recvd = false;
ptr->iof_complete = false;
ptr->do_not_barrier = false;
}
static void orte_odls_child_destructor(orte_odls_child_t *ptr)
{
if (NULL != ptr->name) free(ptr->name);
if (NULL != ptr->rml_uri) free(ptr->rml_uri);
if (NULL != ptr->slot_list) free(ptr->slot_list);
}
OBJ_CLASS_INSTANCE(orte_odls_child_t,
opal_list_item_t,
orte_odls_child_constructor,
orte_odls_child_destructor);
static void orte_odls_job_constructor(orte_odls_job_t *ptr)
{
ptr->jobid = ORTE_JOBID_INVALID;
ptr->state = ORTE_JOB_STATE_UNDEF;
ptr->launch_msg_processed = false;
ptr->apps = NULL;
ptr->num_apps = 0;
ptr->policy = 0;
ptr->cpus_per_rank = 1;
ptr->stride = 1;
ptr->controls = 0;
ptr->stdin_target = ORTE_VPID_INVALID;
ptr->total_slots_alloc = 0;
ptr->num_procs = 0;
ptr->num_local_procs = 0;
ptr->regexp = NULL;
ptr->pmap = NULL;
OBJ_CONSTRUCT(&ptr->collection_bucket, opal_buffer_t);
OBJ_CONSTRUCT(&ptr->local_collection, opal_buffer_t);
ptr->collective_type = ORTE_GRPCOMM_COLL_NONE;
ptr->num_contributors = 0;
ptr->num_participating = -1;
ptr->num_collected = 0;
}
static void orte_odls_job_destructor(orte_odls_job_t *ptr)
{
int32_t i;
if (NULL != ptr->apps) {
for (i=0; i < ptr->num_apps; i++) {
OBJ_RELEASE(ptr->apps[i]);
}
if (NULL != ptr->apps) {
free(ptr->apps);
}
}
if (NULL != ptr->regexp) {
free(ptr->regexp);
}
if (NULL != ptr->pmap && NULL != ptr->pmap->bytes) {
free(ptr->pmap->bytes);
free(ptr->pmap);
}
OBJ_DESTRUCT(&ptr->collection_bucket);
OBJ_DESTRUCT(&ptr->local_collection);
}
OBJ_CLASS_INSTANCE(orte_odls_job_t,
opal_list_item_t,
orte_odls_job_constructor,
orte_odls_job_destructor);
/*
* Framework global variables
*/
orte_odls_base_t orte_odls_base;
orte_odls_globals_t orte_odls_globals;
/**
* Function for finding and opening either all MCA components, or the one
* that was specifically requested via a MCA parameter.
*/
int orte_odls_base_open(void)
{
char **ranks=NULL, *tmp;
int i, rank, sock, core, rc;
orte_namelist_t *nm;
bool xterm_hold;
/* Debugging / verbose output. Always have stream open, with
verbose set by the mca open system... */
orte_odls_globals.output = opal_output_open(NULL);
mca_base_param_reg_int_name("odls", "base_sigkill_timeout",
"Time to wait for a process to die after issuing a kill signal to it",
false, false, 1, &orte_odls_globals.timeout_before_sigkill);
/* initialize ODLS globals */
OBJ_CONSTRUCT(&orte_odls_globals.mutex, opal_mutex_t);
OBJ_CONSTRUCT(&orte_odls_globals.cond, opal_condition_t);
OBJ_CONSTRUCT(&orte_odls_globals.xterm_ranks, opal_list_t);
orte_odls_globals.xtermcmd = NULL;
orte_odls_globals.dmap = NULL;
orte_odls_globals.debugger = NULL;
orte_odls_globals.debugger_launched = false;
OBJ_CONSTRUCT(&orte_odls_globals.sysinfo, opal_list_t);
#if OPAL_HAVE_HWLOC
/* ensure we have the local topology */
if (NULL == opal_hwloc_topology) {
if (0 != hwloc_topology_init(&opal_hwloc_topology) ||
0 != hwloc_topology_load(opal_hwloc_topology)) {
return ORTE_ERR_NOT_SUPPORTED;
}
}
#endif
/* init globals */
OPAL_PAFFINITY_CPU_ZERO(orte_odls_globals.my_cores);
orte_odls_globals.bound = false;
orte_odls_globals.num_processors = 0;
orte_odls_globals.num_sockets = orte_default_num_sockets_per_board;
orte_odls_globals.num_cores_per_socket = orte_default_num_cores_per_socket;
OBJ_CONSTRUCT(&orte_odls_globals.sockets, opal_bitmap_t);
opal_bitmap_init(&orte_odls_globals.sockets, 16);
/* see if paffinity is supported */
if (ORTE_SUCCESS == (rc = opal_paffinity_base_get(&orte_odls_globals.my_cores))) {
/* get the number of local sockets unless we were given a number */
if (0 == orte_default_num_sockets_per_board) {
opal_paffinity_base_get_socket_info(&orte_odls_globals.num_sockets);
/* on some really old kernels or unusual systems, we may not
* see any sockets - so default to a value of 1 to avoid
* the segfault
*/
if (orte_odls_globals.num_sockets <= 0) {
orte_odls_globals.num_sockets = 1;
}
}
/* get the number of local processors */
opal_paffinity_base_get_processor_info(&orte_odls_globals.num_processors);
/* compute the base number of cores/socket, if not given */
if (0 == orte_default_num_cores_per_socket) {
orte_odls_globals.num_cores_per_socket = orte_odls_globals.num_processors / orte_odls_globals.num_sockets;
}
OPAL_OUTPUT_VERBOSE((1, orte_odls_globals.output,
"%s FOUND %d SOCKETS WITH %d CORES-PER-SOCKET",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
orte_odls_globals.num_sockets,
orte_odls_globals.num_cores_per_socket));
/* determine if we are bound */
OPAL_PAFFINITY_PROCESS_IS_BOUND(orte_odls_globals.my_cores, &orte_odls_globals.bound);
/* if we are bound, determine the number of sockets - and which ones - that are available to us */
if (orte_odls_globals.bound) {
for (i=0; i < orte_odls_globals.num_processors; i++) {
if (OPAL_PAFFINITY_CPU_ISSET(i, orte_odls_globals.my_cores)) {
opal_paffinity_base_get_map_to_socket_core(i, &sock, &core);
opal_bitmap_set_bit(&orte_odls_globals.sockets, sock);
}
}
/* determine how many sockets we have available to us */
orte_odls_globals.num_sockets = 0;
for (i=0; i < opal_bitmap_size(&orte_odls_globals.sockets); i++) {
if (opal_bitmap_is_set_bit(&orte_odls_globals.sockets, i)) {
orte_odls_globals.num_sockets++;
}
}
if (ORTE_PROC_IS_HNP && orte_report_bindings) {
opal_output(0, "System has detected external process binding to cores %04lx",
orte_odls_globals.my_cores.bitmask[0]);
}
}
} else {
OPAL_OUTPUT_VERBOSE((1, orte_odls_globals.output,
"%s AFFINITY NOT SUPPORTED: %s",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_ERROR_NAME(rc)));
}
/* check if the user requested that we display output in xterms */
if (NULL != orte_xterm) {
/* construct a list of ranks to be displayed */
xterm_hold = false;
orte_util_parse_range_options(orte_xterm, &ranks);
for (i=0; i < opal_argv_count(ranks); i++) {
if (0 == strcmp(ranks[i], "BANG")) {
xterm_hold = true;
continue;
}
nm = OBJ_NEW(orte_namelist_t);
rank = strtol(ranks[i], NULL, 10);
if (-1 == rank) {
/* wildcard */
nm->name.vpid = ORTE_VPID_WILDCARD;
} else if (rank < 0) {
/* error out on bozo case */
orte_show_help("help-odls-base.txt",
"orte-odls-base:xterm-neg-rank",
true, rank);
return ORTE_ERROR;
} else {
/* we can't check here if the rank is out of
* range as we don't yet know how many ranks
* will be in the job - we'll check later
*/
nm->name.vpid = rank;
}
opal_list_append(&orte_odls_globals.xterm_ranks, &nm->item);
}
opal_argv_free(ranks);
/* construct the xtermcmd */
orte_odls_globals.xtermcmd = NULL;
tmp = opal_find_absolute_path("xterm");
if (NULL == tmp) {
return ORTE_ERROR;
}
opal_argv_append_nosize(&orte_odls_globals.xtermcmd, tmp);
free(tmp);
opal_argv_append_nosize(&orte_odls_globals.xtermcmd, "-T");
opal_argv_append_nosize(&orte_odls_globals.xtermcmd, "save");
if (xterm_hold) {
opal_argv_append_nosize(&orte_odls_globals.xtermcmd, "-hold");
}
opal_argv_append_nosize(&orte_odls_globals.xtermcmd, "-e");
}
/* collect the system info */
if (NULL != opal_sysinfo.query) {
char *keys[] = {
OPAL_SYSINFO_CPU_TYPE,
OPAL_SYSINFO_CPU_MODEL,
OPAL_SYSINFO_NUM_CPUS,
OPAL_SYSINFO_MEM_SIZE,
NULL
};
opal_list_item_t *item;
opal_sysinfo_value_t *info;
/* get and store our local resources */
opal_sysinfo.query(keys, &orte_odls_globals.sysinfo);
/* find our cpu type and model, save it for later */
for (item = opal_list_get_first(&orte_odls_globals.sysinfo);
item != opal_list_get_end(&orte_odls_globals.sysinfo) &&
(NULL == orte_local_cpu_type || NULL == orte_local_cpu_model);
item = opal_list_get_next(item)) {
info = (opal_sysinfo_value_t*)item;
if (0 == strcmp(info->key, OPAL_SYSINFO_CPU_TYPE)) {
orte_local_cpu_type = strdup(info->data.str);
}
if (0 == strcmp(info->key, OPAL_SYSINFO_CPU_MODEL)) {
orte_local_cpu_model = strdup(info->data.str);
}
}
}
/* Open up all available components */
if (ORTE_SUCCESS !=
mca_base_components_open("odls", orte_odls_globals.output,
mca_odls_base_static_components,
&orte_odls_base.available_components, true)) {
return ORTE_ERROR;
}
/* are there components available for use ? -
* orte_odls_base.available_components is always initialized */
if(0 < opal_list_get_size(&(orte_odls_base.available_components))) {
orte_odls_base.components_available = true;
} else {
orte_odls_base.components_available = false;
}
/* All done */
return ORTE_SUCCESS;
}
#endif
| 35.44086 | 118 | 0.616808 |
9f498fc210e7c8dc9f1d551dad155f7958da54a6 | 4,910 | c | C | LIB/assign_radii_types.c | bkmgit/FlexAID | e66298e545eb863d57c1064ccd29e98a6674b225 | [
"Apache-2.0"
] | 10 | 2018-02-28T02:23:01.000Z | 2022-03-29T22:02:51.000Z | LIB/assign_radii_types.c | bkmgit/FlexAID | e66298e545eb863d57c1064ccd29e98a6674b225 | [
"Apache-2.0"
] | null | null | null | LIB/assign_radii_types.c | bkmgit/FlexAID | e66298e545eb863d57c1064ccd29e98a6674b225 | [
"Apache-2.0"
] | 9 | 2019-06-07T20:27:24.000Z | 2021-08-23T08:56:39.000Z | #include "flexaid.h"
/******************************************
Assigns radius of atoms based on the
atom types derived from SYBYL
******************************************/
void assign_radii_types(FA_Global* FA, atom* atoms, resid* residue)
{
for(int i=1; i<=FA->res_cnt; i++)
{
for(int j=residue[i].fatm[0]; j<=residue[i].latm[0]; j++)
{
switch(atoms[j].type){
case 1: // C.1
atoms[j].radius = 1.88f;
break;
case 2: // C.2
if((3 - atoms[j].bond[0]) > 0){
atoms[j].radius = 1.72f;
}else{
atoms[j].radius = 1.61f;
}
break;
case 3: // C.3
atoms[j].radius = 1.88f;
break;
case 4: // C.AR
atoms[j].radius = 1.76f;
break;
case 5: // C.CAT
atoms[j].radius = 1.88f;
break;
case 6: // N.1
atoms[j].radius = 1.64f;
break;
case 7: // N.2
atoms[j].radius = 1.64f;
break;
case 8: // N.3
atoms[j].radius = 1.64f;
break;
case 9: // N.4
atoms[j].radius = 1.64f;
break;
case 10: // N.AR
atoms[j].radius = 1.64f;
break;
case 11: // N.AM
atoms[j].radius = 1.64f;
break;
case 12: // N.PL3
atoms[j].radius = 1.64f;
break;
case 13: // O.2
atoms[j].radius = 1.42f;
break;
case 14: // O.3
atoms[j].radius = 1.46f;
break;
case 15: // O.CO2
atoms[j].radius = 1.46f;
break;
case 16: // O.AR
atoms[j].radius = 1.46f;
break;
case 17: // S.2
atoms[j].radius = 1.782f;
break;
case 18: // S.3
atoms[j].radius = 1.782f;
break;
case 19: // S.O
atoms[j].radius = 1.782f;
break;
case 20: // S.O2
atoms[j].radius = 1.782f;
break;
case 21: // S.AR
atoms[j].radius = 1.782f;
break;
case 22: // P.3
atoms[j].radius = 1.871f;
break;
case 23: // F
atoms[j].radius = 1.560f;
break;
case 24: // CL
atoms[j].radius = 1.735f;
break;
case 25: // BR
atoms[j].radius = 1.978f;
break;
case 26: // I
atoms[j].radius = 2.094f;
break;
case 27: // SE
atoms[j].radius = 1.9f;
break;
case 28: // MG
atoms[j].radius = 0.72f;
break;
case 29: // SR
atoms[j].radius = 1.18f;
break;
case 30: // CU
atoms[j].radius = 1.18f;
break;
case 31: // MN
atoms[j].radius = 0.73f;
break;
case 32: // HG
atoms[j].radius = 1.02f;
break;
case 33: // CD
atoms[j].radius = 0.95f;
break;
case 34: // NI
atoms[j].radius = 0.69f;
break;
case 35: // ZN
atoms[j].radius = 0.74f;
break;
case 36: // CA
atoms[j].radius = 1.00f;
break;
case 37: // FE
atoms[j].radius = 0.61f;
break;
case 38: // CO.OH
atoms[j].radius = 0.65f;
break;
case 39: // DUMMY
atoms[j].radius = 2.0f;
break;
case 40: // SOLVENT
break;
}
//printf("atom[%d].type=%d set to radius %.3f\n", atoms[j].number, atoms[j].type, atoms[j].radius);
}
}
}
| 34.097222 | 111 | 0.296538 |
95ae03a5d3f86c4cf103d2d55a087f43021dcc46 | 206 | h | C | Stable/EOS.framework/Headers/IgnoreHitView.h | HydraFramework/release-ios | 5707faa4909c82d1fc3d24d12d7614df0b3d7935 | [
"MIT"
] | null | null | null | Stable/EOS.framework/Headers/IgnoreHitView.h | HydraFramework/release-ios | 5707faa4909c82d1fc3d24d12d7614df0b3d7935 | [
"MIT"
] | null | null | null | Stable/EOS.framework/Headers/IgnoreHitView.h | HydraFramework/release-ios | 5707faa4909c82d1fc3d24d12d7614df0b3d7935 | [
"MIT"
] | null | null | null | //
// IgnoreHitView.h
// EOSFramework
//
// Created by Sam on 4/13/12.
// Copyright (c) 2014 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface IgnoreHitView : UIView
@end
| 14.714286 | 62 | 0.684466 |
a7da94be65d167789759a633a47ed55366d5a018 | 640 | h | C | Examples/Geoloqi/Source/Geonote.h | TrialGuides/Cumulus | d9044a7794a18bac399830e862934a9b5a41b12d | [
"BSD-3-Clause"
] | 5 | 2015-02-01T15:51:22.000Z | 2016-05-29T12:57:39.000Z | Examples/Geoloqi/Source/Geonote.h | TrialGuides/Cumulus | d9044a7794a18bac399830e862934a9b5a41b12d | [
"BSD-3-Clause"
] | 2 | 2015-06-09T15:58:11.000Z | 2016-04-25T07:17:01.000Z | Examples/Geoloqi/Source/Geonote.h | TrialGuides/Cumulus | d9044a7794a18bac399830e862934a9b5a41b12d | [
"BSD-3-Clause"
] | 2 | 2015-01-31T04:50:15.000Z | 2015-06-09T16:01:17.000Z | //
// Geonote.h
// Geoloqi
//
// Created by John Clayton on 12/11/11.
// Copyright (c) 2011 Me. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Geonote : NSManagedObject
@property (nonatomic, retain) NSNumber * radius;
@property (nonatomic, retain) NSDate * dateCreated;
@property (nonatomic, retain) NSNumber * latitude;
@property (nonatomic, retain) NSNumber * longitude;
@property (nonatomic, retain) NSString * placeId;
@property (nonatomic, retain) NSString * placeName;
@property (nonatomic, retain) NSString * text;
@property (nonatomic, retain) NSString * geonoteID;
@end
| 25.6 | 51 | 0.732813 |
67cca705d4cfd9cb3fe22a897861968790b94312 | 1,345 | h | C | src/Validator/AnyOfRequirement.h | hsidky/LNTMC | 6f1cc81476718ef19f85fd596d0815a194705a50 | [
"MIT"
] | 10 | 2016-08-16T23:32:33.000Z | 2021-07-06T09:39:58.000Z | src/Validator/AnyOfRequirement.h | hsidky/LNT-MC | 6f1cc81476718ef19f85fd596d0815a194705a50 | [
"MIT"
] | 33 | 2015-04-09T16:19:51.000Z | 2016-02-06T04:34:01.000Z | src/Validator/AnyOfRequirement.h | hsidky/LNT-MC | 6f1cc81476718ef19f85fd596d0815a194705a50 | [
"MIT"
] | 8 | 2015-02-16T18:34:46.000Z | 2021-01-11T19:37:14.000Z | #pragma once
#include "Requirement.h"
#include "RequirementLoader.h"
namespace Json
{
class AnyOfRequirement : public Requirement
{
private:
RequireList _reqs;
public:
AnyOfRequirement() : _reqs(0) {}
virtual void ClearErrors() override
{
for(auto& r : _reqs)
r->ClearErrors();
Requirement::ClearErrors();
}
virtual void ClearNotices() override
{
for(auto& r : _reqs)
r->ClearNotices();
Requirement::ClearNotices();
}
virtual void Reset() override
{
ClearErrors();
ClearNotices();
_reqs.clear();
}
virtual void Parse(Value json, const std::string& path) override
{
Reset();
RequirementLoader loader;
auto& head = json.isMember("anyOf") ? json["anyOf"] : json;
for(auto& val : head)
if(auto req = loader.LoadRequirement(val))
{
_reqs.push_back(std::move(req));
_reqs.back()->Parse(val, path);
}
}
virtual void Validate(const Value& json, const std::string& path) override
{
for(auto& r : _reqs)
{
r->Validate(json, path);
if(!r->HasErrors())
return;
}
// Collect errors.
for(auto& r : _reqs)
{
if(r->HasErrors())
for(const auto& error : r->GetErrors())
PushError(error);
if(r->HasNotices())
for(const auto& notice : r->GetNotices())
PushNotice(notice);
}
}
};
} | 17.467532 | 76 | 0.611896 |
9c106c3809829ed04c6795f3c376d60bf9766358 | 1,156 | h | C | Source/Game.h | ZaroDev/CoquitoFesquitoMinigame | 19604ca7547e7e4f3f43298b98e9da83cd26b212 | [
"MIT"
] | 1 | 2021-03-08T09:04:38.000Z | 2021-03-08T09:04:38.000Z | Source/Game.h | ZaroDev/CoquitoFesquitoMinigame | 19604ca7547e7e4f3f43298b98e9da83cd26b212 | [
"MIT"
] | null | null | null | Source/Game.h | ZaroDev/CoquitoFesquitoMinigame | 19604ca7547e7e4f3f43298b98e9da83cd26b212 | [
"MIT"
] | 2 | 2021-03-08T09:16:58.000Z | 2021-03-15T08:10:57.000Z | #pragma once
#include "SDL/include/SDL.h"
#include "SDL_image/include/SDL_image.h"
#include "SDL_mixer/include/SDL_mixer.h"
#include "Entity.h"
#include "UI.h"
#include <iostream>
#define WINDOW_WIDTH 1024
#define WINDOW_HEIGHT 768
#define MAX_KEYS 256
#define MAX_SHOTS 32
#define MAX_ENEMIES 5
class Game
{
public:
Game();
~Game();
bool Init();
void Release();
bool Input();
bool Update();
void Draw();
bool CheckCollision(SDL_Rect a, SDL_Rect b);
void RandSpawn();
void SpawnPlayer();
private:
SDL_Window* Window;
SDL_Renderer* Renderer;
SDL_Texture* PlayerIMG;
SDL_Texture* Background;
SDL_Texture* ShotIMG;
SDL_Texture* EnemyIMG;
SDL_Texture* Text;
SDL_Texture* Font;
Mix_Music* Music;
Mix_Chunk* Fx_shoot;
Mix_Chunk* Fx_kill;
Mix_Chunk* Fx_gameOver;
SDL_Rect scrRc;
SDL_Rect scrRc1;
SDL_Rect scrRc2;
SDL_Rect scrRc3;
SDL_Rect dsrRc;
SDL_Rect dsrRc1;
SDL_Rect dsrRc2;
SDL_Rect dsrRc3;
UI UI;
Entity Player, Scene, Platform, Shots[MAX_SHOTS], Enemy[MAX_ENEMIES];
bool godMode;
int idx_shot;
int idx_enemy;
enum KEY_STATE { KEY_IDLE, KEY_DOWN, KEY_REPEAT, KEY_UP };
KEY_STATE keys[MAX_KEYS];
}; | 16.055556 | 70 | 0.737024 |
d51f824ad16c2e4a8a86917820d756e44f5a4d3d | 13,796 | h | C | ionc/inc/ion_decimal.h | hyandell/ion-c | 160d2a14bf25dcb3e209cf7cd6ae726996f8b535 | [
"Apache-2.0"
] | null | null | null | ionc/inc/ion_decimal.h | hyandell/ion-c | 160d2a14bf25dcb3e209cf7cd6ae726996f8b535 | [
"Apache-2.0"
] | null | null | null | ionc/inc/ion_decimal.h | hyandell/ion-c | 160d2a14bf25dcb3e209cf7cd6ae726996f8b535 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2011-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at:
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
/**
* This module provides routines for working with arbitrary-precision decimal numbers in accordance with the decimal
* data model defined in the Ion Specification.
*
* For computational APIs, the output parameter (usually the first) is considered to be an uninitialized value (i.e.
* no effort is made to free its associated memory before overwriting it) UNLESS it is the same reference as one of
* the operands. If it is the same reference as one of the operands, the operation will be performed in-place if
* possible. If not possible, its memory will be freed (if necessary) and replaced with newly allocated memory to hold
* the result. This means that it is important not to reuse ION_DECIMAL instances as output parameters for non-in-place
* operations without freeing them using `ion_decimal_free` first. Doing so could result in a memory leak.
*
* APIs without documentation within this file are shims to counterparts within the decNumber library. These
* counterparts are named dec[Number|Quad]<X>, where X is the camelCased function name without the `ion_decimal_`
* prefix. Detailed documentation for those APIs can be found within the decNumber library.
*
* To avoid memory leaks, `ion_decimal_free` should be called on all ION_DECIMALs before they go out of scope AND before
* they are overwritten by non-in-place operations.
*/
#ifndef ION_DECIMAL_H_
#define ION_DECIMAL_H_
#include "ion_types.h"
#include "ion_platform_config.h"
#ifndef DECNUMDIGITS
#error DECNUMDIGITS must be defined to be >= DECQUAD_Pmax
#elif DECNUMDIGITS < DECQUAD_Pmax
#error DECNUMDIGITS must be defined to be >= DECQUAD_Pmax
#endif
/**
* Provides the byte size required to hold the string representation of the given decimal.
*/
#define ION_DECIMAL_STRLEN(ion_decimal) \
((size_t)(((ion_decimal)->type == ION_DECIMAL_TYPE_QUAD) \
? DECQUAD_String \
: (((ion_decimal)->type == ION_DECIMAL_TYPE_UNKNOWN) \
? -1 \
: ((ion_decimal)->value.num_value->digits + 14) /* +14 is specified by decNumberToString. */ \
) \
))
#ifdef __cplusplus
extern "C" {
#endif
/*
* Internal structure definitions. The internals should NOT be depended upon (or cared about) by the end user.
*/
/**
* Determines which value of the _ion_decimal's `value` field is active.
*/
typedef enum {
ION_DECIMAL_TYPE_UNKNOWN = 0,
/**
* The _ion_decimal holds a decQuad.
*/
ION_DECIMAL_TYPE_QUAD = 1,
/**
* The _ion_decimal holds an unowned decNumber.
*/
ION_DECIMAL_TYPE_NUMBER = 2,
/**
* The _ion_decimal holds a decNumber whose memory is managed by an owner.
*/
ION_DECIMAL_TYPE_NUMBER_OWNED = 3,
} ION_DECIMAL_TYPE;
struct _ion_decimal {
ION_DECIMAL_TYPE type;
union {
decQuad quad_value;
decNumber *num_value;
} value;
};
/* Memory management */
/**
* Zeroes the given ION_DECIMAL in-place. NOTE: this has better performance than memset in certain environments.
*
* @param value - the value to zero.
* @return IERR_OK (no errors are possible).
*/
ION_API_EXPORT iERR ion_decimal_zero(ION_DECIMAL *value);
/**
* If necessary, copies the given decimal's internal data so that owner of that data may safely go out of scope. This is
* useful, for example, when it is necessary to keep the value in scope after the reader that produced it is closed.
* Values produced through calls to `ion_decimal_*` APIs (with the possible exception of `ion_decimal_from_number`) do
* NOT need to be claimed.
*
* @param value - The value to claim.
*/
ION_API_EXPORT iERR ion_decimal_claim(ION_DECIMAL *value);
/**
* Frees any memory that was allocated when constructing this value. This should be called to clean up all ION_DECIMALs.
*
* @param value - The value to free.
*/
ION_API_EXPORT iERR ion_decimal_free(ION_DECIMAL *value);
/* Conversions */
/**
* Converts the given ION_DECIMAL to a string. `ION_DECIMAL_STRLEN` may be used to determine the amount of space
* required to hold the string representation.
*
* @return IERR_OK (no errors are possible).
*/
ION_API_EXPORT iERR ion_decimal_to_string(const ION_DECIMAL *value, char *p_string);
/**
* Converts the given string to its ION_DECIMAL representation.
*
* @param value - a non-null pointer to the resulting decimal.
* @param str - a null-terminated string representing a decimal. Exponents (if any) may be indicated using either 'd'
* or 'e'.
* @param context - the context to use for the conversion. If the decimal lies outside of the context's limits, an error
* is raised.
* @return IERR_NUMERIC_OVERFLOW if the decimal lies outside of the context's limits, otherwise IERR_OK.
*/
ION_API_EXPORT iERR ion_decimal_from_string(ION_DECIMAL *value, const char *str, decContext *context);
/**
* Represents the given uint32 as an ION_DECIMAL.
*
* @return IERR_OK (no errors are possible).
*/
ION_API_EXPORT iERR ion_decimal_from_uint32(ION_DECIMAL *value, uint32_t num);
/**
* Represents the given int32 as an ION_DECIMAL.
*
* @return IERR_OK (no errors are possible).
*/
ION_API_EXPORT iERR ion_decimal_from_int32(ION_DECIMAL *value, int32_t num);
/**
* Represents the given decQuad as an ION_DECIMAL. The caller IS NOT required to keep the given decQuad in scope for the
* lifetime of the resulting ION_DECIMAL.
*
* @return IERR_OK (no errors are possible).
*/
ION_API_EXPORT iERR ion_decimal_from_quad(ION_DECIMAL *value, decQuad *quad);
/**
* Represents the given decNumber as an ION_DECIMAL. This function does not allocate or copy any memory, so the caller
* IS required to keep the given decNumber in scope for the lifetime of the resulting ION_DECIMAL. If desired, the
* caller can alleviate this requirement by calling `ion_decimal_claim` on the resulting ION_DECIMAL (note that this
* forces a copy). It is the caller's responsibility to eventually free any dynamically allocated memory used by the
* given decNumber (calling `ion_decimal_free` will not free this memory).
*
* @return IERR_OK (no errors are possible).
*/
ION_API_EXPORT iERR ion_decimal_from_number(ION_DECIMAL *value, decNumber *number);
/**
* Converts the given ION_INT to its ION_DECIMAL representation.
*/
ION_API_EXPORT iERR ion_decimal_from_ion_int(ION_DECIMAL *value, decContext *context, ION_INT *p_int);
/**
* Converts the given ION_DECIMAL to its ION_INT representation. If the given ION_DECIMAL is not an integer,
* IERR_INVALID_ARG will be returned; rounding will never occur. If rounding is desired, use
* `ion_decimal_to_integral_exact` or `ion_decimal_to_integral_value` first.
*/
ION_API_EXPORT iERR ion_decimal_to_ion_int(const ION_DECIMAL *value, decContext *context, ION_INT *p_int);
ION_API_EXPORT iERR ion_decimal_to_int32(const ION_DECIMAL *value, decContext *context, int32_t *p_int);
ION_API_EXPORT iERR ion_decimal_to_uint32(const ION_DECIMAL *value, decContext *context, uint32_t *p_int);
/* Operator APIs (computational) */
ION_API_EXPORT iERR ion_decimal_fma(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, const ION_DECIMAL *fhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_add(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_and(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_divide(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_divide_integer(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_max(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_max_mag(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_min(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_min_mag(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_multiply(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_or(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_quantize(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_remainder(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_remainder_near(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_rotate(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_scaleb(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_shift(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_subtract(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_xor(ION_DECIMAL *value, const ION_DECIMAL *lhs, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_abs(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_invert(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_logb(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_minus(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_plus(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_reduce(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_to_integral_exact(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
ION_API_EXPORT iERR ion_decimal_to_integral_value(ION_DECIMAL *value, const ION_DECIMAL *rhs, decContext *context);
/* Utility APIs (non-computational) */
ION_API_EXPORT uint32_t ion_decimal_digits(const ION_DECIMAL *value);
ION_API_EXPORT int32_t ion_decimal_get_exponent(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_radix(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_same_quantum(const ION_DECIMAL *lhs, const ION_DECIMAL *rhs);
ION_API_EXPORT uint32_t ion_decimal_is_integer(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_is_subnormal(const ION_DECIMAL *value, decContext *context);
ION_API_EXPORT uint32_t ion_decimal_is_normal(const ION_DECIMAL *value, decContext *context);
ION_API_EXPORT uint32_t ion_decimal_is_finite(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_is_infinite(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_is_nan(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_is_negative(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_is_zero(const ION_DECIMAL *value);
ION_API_EXPORT uint32_t ion_decimal_is_canonical(const ION_DECIMAL *value);
/* Comparisons */
/**
* Compares ION_DECIMALs for ordering and equivalence under the Ion data model. A negative result indicates that `left`
* is less than `right`. A positive result indicates that `left` is greater than `right`. A result of zero indicates
* that `left` and `right` are equivalent under the Ion data model. Non-equivalent values are ordered according to the
* IEEE 754 total ordering.
*/
ION_API_EXPORT iERR ion_decimal_compare(const ION_DECIMAL *left, const ION_DECIMAL *right, decContext *context, int32_t *result);
/**
* Compares decQuads for equivalence under the Ion data model. That is, the sign, coefficient, and exponent must be
* equivalent for the normalized values (even for zero).
*
* @deprecated - use of decQuads directly is deprecated. ION_DECIMAL should be used. See `ion_decimal_equals`.
*/
ION_API_EXPORT iERR ion_decimal_equals_quad(const decQuad *left, const decQuad *right, decContext *context, BOOL *is_equal);
/**
* Compares ION_DECIMALs for equivalence under the Ion data model. That is, the sign, coefficient, and exponent must be
* equivalent for the normalized values (even for zero).
*/
ION_API_EXPORT iERR ion_decimal_equals(const ION_DECIMAL *left, const ION_DECIMAL *right, decContext *context, BOOL *is_equal);
/* Copies */
ION_API_EXPORT iERR ion_decimal_canonical(ION_DECIMAL *value, const ION_DECIMAL *rhs);
ION_API_EXPORT iERR ion_decimal_copy(ION_DECIMAL *value, const ION_DECIMAL *rhs);
ION_API_EXPORT iERR ion_decimal_copy_abs(ION_DECIMAL *value, const ION_DECIMAL *rhs);
ION_API_EXPORT iERR ion_decimal_copy_negate(ION_DECIMAL *value, const ION_DECIMAL *rhs);
ION_API_EXPORT iERR ion_decimal_copy_sign(ION_DECIMAL *value, const ION_DECIMAL *rhs, const ION_DECIMAL *lhs, decContext *context);
#ifdef __cplusplus
}
#endif
#endif /* ION_DECIMAL_H_ */
| 49.096085 | 149 | 0.781096 |
845d57aed3f70c86e658ecb8a5b9f4ef044b4bc0 | 2,254 | h | C | implementations/ugene/src/corelibs/U2View/src/ov_msa/find_pattern/FindPatternMsaTask.h | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/corelibs/U2View/src/ov_msa/find_pattern/FindPatternMsaTask.h | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/corelibs/U2View/src/ov_msa/find_pattern/FindPatternMsaTask.h | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* 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.
*/
#ifndef _U2_FIND_PATTERN_MSA_TASK_H_
#define _U2_FIND_PATTERN_MSA_TASK_H_
#include <U2Core/U2Region.h>
#include <U2View/FindPatternTask.h>
namespace U2 {
class MultipleSequenceAlignmentObject;
class FindPatternListTask;
struct U2VIEW_EXPORT FindPatternMsaSettings {
FindPatternMsaSettings();
MultipleSequenceAlignmentObject *msaObj;
QList<NamePattern> patterns;
bool removeOverlaps;
int matchValue;
FindAlgorithmSettings findSettings;
};
struct U2VIEW_EXPORT FindPatternInMsaResult {
public:
FindPatternInMsaResult(qint64 rowId, const QList<U2Region> ®ions);
/** Unique row id in the multiple alignment object. */
qint64 rowId;
/** List of matched regions with gaps. */
QList<U2Region> regions;
};
class U2VIEW_EXPORT FindPatternMsaTask : public Task {
Q_OBJECT
public:
FindPatternMsaTask(const FindPatternMsaSettings &settings);
void prepare() override;
QList<Task *> onSubTaskFinished(Task *subTask) override;
/** Returns list of per-row results. */
const QList<FindPatternInMsaResult> &getResults() const;
private:
void getResultFromTask();
void createSearchTaskForCurrentSequence();
FindPatternMsaSettings settings;
int currentSequenceIndex;
FindPatternListTask *searchInSingleSequenceTask;
int totalResultsCounter;
QList<FindPatternInMsaResult> results;
};
} // namespace U2
#endif
| 27.82716 | 73 | 0.751109 |
84e4ee14d61da2c7b8c121ef310d8db65002b8f7 | 335 | h | C | include/ncurses_display.h | 19Timotei97/LinuxSystemMonitor | 19f387e4a0a462db2b76cae47dac4482b672013f | [
"MIT"
] | null | null | null | include/ncurses_display.h | 19Timotei97/LinuxSystemMonitor | 19f387e4a0a462db2b76cae47dac4482b672013f | [
"MIT"
] | null | null | null | include/ncurses_display.h | 19Timotei97/LinuxSystemMonitor | 19f387e4a0a462db2b76cae47dac4482b672013f | [
"MIT"
] | null | null | null | #ifndef NCURSES_DISPLAY_H
#define NCURSES_DISPLAY_H
#include <curses.h>
#include "process.h"
#include "system.h"
namespace NCursesDisplay
{
void Display (System&, int = 10);
void DisplaySystem (System&, WINDOW*);
void DisplayProcesses (std::vector<Process>&, WINDOW*, int);
std::string ProgressBar (float);
};
#endif | 16.75 | 62 | 0.710448 |
7efb091052dd58d20c8f2cc967480d4f97b926e7 | 1,096 | c | C | uc.c | AngheloAlf/libgfxd | 6d8a00835f30cb6847ad126357149ad1f29c63aa | [
"MIT"
] | 26 | 2020-12-29T23:21:05.000Z | 2022-03-23T01:26:02.000Z | uc.c | AngheloAlf/libgfxd | 6d8a00835f30cb6847ad126357149ad1f29c63aa | [
"MIT"
] | 90 | 2020-12-29T18:19:37.000Z | 2022-03-21T19:44:15.000Z | uc.c | AngheloAlf/libgfxd | 6d8a00835f30cb6847ad126357149ad1f29c63aa | [
"MIT"
] | 26 | 2020-12-29T18:18:38.000Z | 2022-03-10T09:13:46.000Z | #include <inttypes.h>
#include <string.h>
#include <stdint.h>
#include "gbi.h"
#include "gfxd.h"
#include "priv.h"
#include "uc_argfn.c"
#include "uc_argtbl.c"
#include "uc_macrofn.c"
#include "uc_macrotbl.c"
UCFUNC int disas(gfxd_macro_t *m, uint32_t hi, uint32_t lo)
{
int opcode = (hi >> 24) & 0xFF;
for (int i = 0; i < sizeof(macro_tbl) / sizeof(macro_tbl[0]); i++)
{
const gfxd_macro_type_t *t = ¯o_tbl[i];
if (t->disas_fn != NULL && t->opcode == opcode)
return t->disas_fn(m, hi, lo);
}
return d_Invalid(m, hi, lo);
}
UCFUNC int combine(gfxd_macro_t *m, int num)
{
int opcode = macro_tbl[m->id].opcode;
for (int i = 0; i < sizeof(macro_tbl) / sizeof(macro_tbl[0]); i++)
{
const gfxd_macro_type_t *t = ¯o_tbl[i];
if (t->combine_fn != NULL
&& t->opcode == opcode
&& (t->ext == 0 || config.emit_ext_macro != 0))
{
if (t->combine_fn(m, num) == 0)
return 0;
}
}
return -1;
}
static const struct gfxd_ucode uc =
{
.disas_fn = disas,
.combine_fn = combine,
.arg_tbl = arg_tbl,
.macro_tbl = macro_tbl,
};
const gfxd_ucode_t uc_name = &uc;
| 19.927273 | 67 | 0.635036 |
a369e46ab878310ef0ab8cf399ca4994a73fa098 | 707 | h | C | realSenseHeadTracker/src/ofApp.h | olekristensen/oresund | acfd604bda68e7fec0d07e14530eee546e497386 | [
"MIT"
] | 1 | 2018-09-04T11:41:38.000Z | 2018-09-04T11:41:38.000Z | realSenseHeadTracker/src/ofApp.h | olekristensen/oresund | acfd604bda68e7fec0d07e14530eee546e497386 | [
"MIT"
] | null | null | null | realSenseHeadTracker/src/ofApp.h | olekristensen/oresund | acfd604bda68e7fec0d07e14530eee546e497386 | [
"MIT"
] | 1 | 2021-04-18T05:41:35.000Z | 2021-04-18T05:41:35.000Z | #pragma once
#include "ofMain.h"
#include <librealsense2/rs.hpp>
#include "tracker.hpp"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void loadBagFile(string path);
rs2::pipeline pipe;
rs2::device device;
rs2::pipeline_profile selection;
rs2::colorizer color_map;
rs2::frame colored_depth;
rs2::frame colored_filtered;
rs2_intrinsics intrinsics;
rs2::decimation_filter dec_filter;
rs2::spatial_filter spat_filter;
rs2::temporal_filter temp_filter;
rs2::points points;
rs2::pointcloud pc;
ofVboMesh mesh;
ofEasyCam cam;
ofNode origin;
MeshTracker tracker;
};
| 19.108108 | 38 | 0.663366 |
2835eb69ffc149ad8b2059999674e54fba57e078 | 80 | h | C | t3/lib/hello.h | suzp1984/CMake-tutorial | ce349498808cca32aa07ee32d6af00e2bcbf5584 | [
"Apache-2.0"
] | null | null | null | t3/lib/hello.h | suzp1984/CMake-tutorial | ce349498808cca32aa07ee32d6af00e2bcbf5584 | [
"Apache-2.0"
] | null | null | null | t3/lib/hello.h | suzp1984/CMake-tutorial | ce349498808cca32aa07ee32d6af00e2bcbf5584 | [
"Apache-2.0"
] | null | null | null | #ifndef HELLO_H
#define HELLO_H
#include <stdio.h>
void helloFunc();
#endif
| 8 | 18 | 0.7125 |
9352f13d733d8fc0707564c06c75f3f49a455cb6 | 4,428 | c | C | examples/InlineHook.c | fengjixuchui/zyan-hook-engine | 774bd266dd461921120a54dc95670effd99d99ff | [
"MIT"
] | 112 | 2015-05-20T00:09:20.000Z | 2022-03-14T21:17:12.000Z | examples/InlineHook.c | fengjixuchui/zyan-hook-engine | 774bd266dd461921120a54dc95670effd99d99ff | [
"MIT"
] | 5 | 2017-02-18T21:40:17.000Z | 2020-05-14T04:39:08.000Z | examples/InlineHook.c | fengjixuchui/zyan-hook-engine | 774bd266dd461921120a54dc95670effd99d99ff | [
"MIT"
] | 22 | 2016-03-29T17:02:17.000Z | 2022-02-21T07:05:18.000Z | /***************************************************************************************************
Zyan Hook Library (Zyrex)
Original Author : Florian Bernd
* 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.
***************************************************************************************************/
/**
* @file
* @brief Demonstrates the inline-hook.
*/
#include <Zycore/Defines.h>
#include <Zyrex/Zyrex.h>
#include <Zyrex/Internal/InlineHook.h>
#include <Zyrex/Internal/Trampoline.h>
#include <stdio.h>
#include "Zyrex/Transaction.h"
#include <stdint.h>
#include <Windows.h>
/* ============================================================================================== */
/* Entry point */
/* ============================================================================================== */
typedef DWORD (__stdcall functype)(void* param);
static functype* volatile original = NULL;
DWORD __stdcall xxx2(void* param)
{
ZYAN_UNUSED(param);
puts("hello from original\n");
int v = 0;
for (int i = 0; i < 3; ++i)
{
v++;
}
return 0x1337;
}
DWORD __stdcall callback(void* param)
{
ZYAN_UNUSED(param);
puts("hello from callback\n");
return (*original)(NULL) + 1;
}
typedef BOOL (WINAPI FuncCopyFileW)(_In_ LPCWSTR lpExistingFileName, _In_ LPCWSTR lpNewFileName,
_In_ BOOL bFailIfExists);
static FuncCopyFileW* volatile CopyFileWOriginal = ZYAN_NULL;
BOOL WINAPI CopyFileWCallback(_In_ LPCWSTR lpExistingFileName, _In_ LPCWSTR lpNewFileName,
_In_ BOOL bFailIfExists)
{
ZYAN_UNUSED(lpExistingFileName);
ZYAN_UNUSED(lpNewFileName);
ZYAN_UNUSED(bFailIfExists);
puts("CopyFileW callback");
const BOOL result = CopyFileWOriginal(lpExistingFileName, lpNewFileName, bFailIfExists);
const DWORD error = GetLastError();
ZYAN_UNUSED(error);
return result;
}
int main()
{
ZyrexInitialize();
ZyrexTransactionBegin();
ZyrexInstallInlineHook((void*)&xxx2, (const void*)&callback, (ZyanConstVoidPointer*)&original);
/*ZyrexInstallInlineHook((void*)&CopyFileW, (const void*)&CopyFileWCallback,
(ZyanConstVoidPointer*)&CopyFileWOriginal);*/
ZyrexTransactionCommit();
printf("%x\n", (unsigned int)xxx2(0));
ZyrexTransactionBegin();
ZyrexRemoveInlineHook((ZyanConstVoidPointer*)&original);
ZyrexTransactionCommit();
printf("%x\n", (unsigned int)xxx2(0));
//ZyanU8 buffer[] =
//{ // E1, E2
// /*0xEB, 0xFE, */0x75, 0x02, 0xeb, 0xfb, 0x67, 0xE3, 0xf8, 0x48, 0x8B, 0x05, 0xF5, 0xFF, 0xFF, 0xFF, 0x90, 0x90, 0x90, 0xC3
//};
//void* const buf = VirtualAlloc(NULL, sizeof(buffer), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
//memcpy(buf, buffer, sizeof(buffer));
//functype* const xxx = (functype*)buf;
//ZyrexTrampolineChunk* trampoline;
//const ZyanStatus status =
// ZyrexTrampolineCreate((const void*)xxx, (const void*)&callback, 5, &trampoline);
//if (ZYAN_SUCCESS(status))
//{
// original = (functype*)&trampoline->code_buffer;
// printf("%.8X", ((functype*)original)(NULL));
// ZyrexTrampolineFree(trampoline);
//}
return 0;
}
/* ============================================================================================== */
| 32.086957 | 133 | 0.602529 |
d1b2a4dd29f034486cc4808ce89714247f900e61 | 1,406 | h | C | include/app/service/AccountApi.h | agiledragon/transfer-money | 7656bf8803afe6545b1461e493e1b1995fe6d1e2 | [
"MIT"
] | 11 | 2019-06-20T11:56:35.000Z | 2021-05-26T16:03:50.000Z | include/app/service/AccountApi.h | agiledragon/transfer-money | 7656bf8803afe6545b1461e493e1b1995fe6d1e2 | [
"MIT"
] | null | null | null | include/app/service/AccountApi.h | agiledragon/transfer-money | 7656bf8803afe6545b1461e493e1b1995fe6d1e2 | [
"MIT"
] | 4 | 2019-08-25T12:35:34.000Z | 2022-03-26T20:06:06.000Z | #ifndef H3609D1A0_41F0_4D0B_9133_7849016D0332
#define H3609D1A0_41F0_4D0B_9133_7849016D0332
#include <pub/base/Types.h>
#include <domain/service/AccountService.h>
#include <domain/service/WithdrawMoneyService.h>
#include <domain/service/TransferMoneyToLocalService.h>
#include <domain/service/TransferMoneyToRemoteService.h>
#include <domain/service/TransferMoneyFromRemoteService.h>
#include <domain/service/TransferMoneyService.h>
#include <string>
struct AccountApi
{
AccountApi();
std::string createAccount(const std::string& phoneNumber, U32 initAmount);
void destroyAccount(const std::string& accountId);
void withdrawMoney(const std::string& accountId, U32 amount);
U32 getAmount(const std::string& accountId);
void transferMoneyToLocal(const std::string& fromId, const std::string& toId, U32 amount);
void transferMoneyToRemote(const std::string& fromId, const std::string& toId, U32 amount);
void transferMoneyFromRemote(const std::string& fromId, const std::string& toId, U32 amount);
private:
std::string generateAccountId(const std::string& phoneNumber);
private:
AccountService accountService;
WithdrawMoneyService withdrawMoneyService;
TransferMoneyToLocalService transferMoneyToLocalService;
TransferMoneyToRemoteService transferMoneyToRemoteService;
TransferMoneyFromRemoteService transferMoneyFromRemoteService;
TransferMoneyService transferMoneyService;
};
#endif
| 34.292683 | 94 | 0.825036 |
9e06ffe5b9f43b710d2f528a31af2eec5803f28a | 1,759 | h | C | cpp/libjoynr/include/joynr/QosArbitrationStrategyFunction.h | naeramarth7/joynr | 3c378d3447cf83678d26ef0def44a29fe1270193 | [
"Apache-2.0"
] | null | null | null | cpp/libjoynr/include/joynr/QosArbitrationStrategyFunction.h | naeramarth7/joynr | 3c378d3447cf83678d26ef0def44a29fe1270193 | [
"Apache-2.0"
] | null | null | null | cpp/libjoynr/include/joynr/QosArbitrationStrategyFunction.h | naeramarth7/joynr | 3c378d3447cf83678d26ef0def44a29fe1270193 | [
"Apache-2.0"
] | null | null | null |
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#ifndef QOSARBITRATIONSTRATEGYFUNCTION_H
#define QOSARBITRATIONSTRATEGYFUNCTION_H
#include <map>
#include <string>
#include <vector>
#include "joynr/ArbitrationStrategyFunction.h"
#include "joynr/Logger.h"
#include "joynr/PrivateCopyAssign.h"
namespace joynr
{
namespace types
{
class DiscoveryEntryWithMetaInfo;
class CustomParameter;
} // namespace types
/*
* The QoS Arbitration Strategy Function arbitrates according to the QoS of the provider.
* It arbitrates to the provider with the highest priority.
*/
class QosArbitrationStrategyFunction : public ArbitrationStrategyFunction
{
public:
~QosArbitrationStrategyFunction() final = default;
QosArbitrationStrategyFunction() = default;
types::DiscoveryEntryWithMetaInfo select(
const std::map<std::string, types::CustomParameter> customParameters,
const std::vector<types::DiscoveryEntryWithMetaInfo>& discoveryEntries) const final;
private:
DISALLOW_COPY_AND_ASSIGN(QosArbitrationStrategyFunction);
ADD_LOGGER(QosArbitrationStrategyFunction)
};
} // namespace joynr
#endif // QOSARBITRATIONSTRATEGYFUNCTION_H
| 28.836066 | 96 | 0.75668 |
9aadcd541f918acf5553d4472a3d1dc4038eab4c | 468 | c | C | sin/version8.c | MoriGM/RandomCStuff | 66a9e6d94fc11ab446defd6dd86e0ae6d10dd4d3 | [
"MIT"
] | null | null | null | sin/version8.c | MoriGM/RandomCStuff | 66a9e6d94fc11ab446defd6dd86e0ae6d10dd4d3 | [
"MIT"
] | null | null | null | sin/version8.c | MoriGM/RandomCStuff | 66a9e6d94fc11ab446defd6dd86e0ae6d10dd4d3 | [
"MIT"
] | null | null | null | #define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <time.h>
#define PI 3.14159265
int saw_down_pos(double s)
{
return (int) (s / 4.8);
}
int main(void)
{
while(true)
for (double d = 0;d < 360;d++)
{
int p = saw_down_pos(d);
for (int i = 0;i < p;i++)
printf(" ");
printf("0\n");
struct timespec tp;
tp.tv_nsec = (1000 * 1000 * 4);
tp.tv_sec = 0;
nanosleep(&tp, NULL);
}
return 0;
}
| 14.625 | 34 | 0.58547 |
d286b1ee7399e92dd4acec1f103147b9c30c5cb8 | 219 | h | C | gudov/gudov.h | MiaoHN/Gudov | 621b3ee253fb28a21f85e864ad13702fc524f572 | [
"MIT"
] | null | null | null | gudov/gudov.h | MiaoHN/Gudov | 621b3ee253fb28a21f85e864ad13702fc524f572 | [
"MIT"
] | null | null | null | gudov/gudov.h | MiaoHN/Gudov | 621b3ee253fb28a21f85e864ad13702fc524f572 | [
"MIT"
] | null | null | null | #ifndef __GUDOV_GUDOV_H__
#define __GUDOV_GUDOV_H__
#include "config.h"
#include "fiber.h"
#include "log.h"
#include "macro.h"
#include "singleton.h"
#include "thread.h"
#include "util.h"
#endif // __GUDOV_GUDOV_H__
| 16.846154 | 28 | 0.739726 |
d65d03aac717da87c3961a1b5b0bf25a472daf41 | 5,713 | h | C | Projects/SerialPort_Config/Inc/Uart.h | prasadghole/stm32cpp | 02ceab7630f9ae245224854480eff0ddf7925e60 | [
"MIT"
] | null | null | null | Projects/SerialPort_Config/Inc/Uart.h | prasadghole/stm32cpp | 02ceab7630f9ae245224854480eff0ddf7925e60 | [
"MIT"
] | null | null | null | Projects/SerialPort_Config/Inc/Uart.h | prasadghole/stm32cpp | 02ceab7630f9ae245224854480eff0ddf7925e60 | [
"MIT"
] | null | null | null | /*
* Uart.h
* Author: 20006401
*/
#ifndef INC_UART_H_
#define INC_UART_H_
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "stm32f7xx_ll_bus.h"
#include "stm32f7xx_ll_rcc.h"
#include "stm32f7xx_ll_system.h"
#include "stm32f7xx_ll_utils.h"
#include "stm32f7xx_ll_cortex.h"
#include "stm32f7xx_ll_gpio.h"
#include "stm32f7xx_ll_exti.h"
#include "stm32f7xx_ll_usart.h"
#include "stm32f7xx_ll_pwr.h"
namespace stm32f767 {
enum UsartInstance {
UART_1 = 0,
UART_3 = 1
};
class UsartSettings{
public:
UsartSettings()
{
this->m_baudrate = 115200;
this->m_bits = 8;
this->m_parity = 0;
this->m_stopbit = 1;
this->m_flowcontrol = 0;
}
UsartSettings(uint32_t baudrate, uint32_t bits, uint32_t parity, uint32_t stopbit, uint32_t flowcontrol):
m_baudrate(baudrate), m_bits(bits),m_parity(parity),m_stopbit(stopbit),m_flowcontrol(flowcontrol)
{}
uint32_t m_baudrate;
uint32_t m_bits;
uint32_t m_parity;
uint32_t m_stopbit;
uint32_t m_flowcontrol;
};
class UsartConfig {
public:
UsartConfig(USART_TypeDef * instance, uint32_t bus,uint32_t usartclock, uint32_t gpioclock,GPIO_TypeDef * txport , uint32_t txpin,GPIO_TypeDef * rxport, uint32_t rxpin,uint32_t clockdiv) :
m_instance(instance),
m_bus(bus),
m_usartclock(usartclock),
m_gpioclock(gpioclock),
m_txport(txport),
m_txpin(txpin),
m_rxport(rxport),
m_rxpin(rxpin),
m_clockdiv(clockdiv)
{}
USART_TypeDef * m_instance;
uint32_t m_bus;
uint32_t m_usartclock;
uint32_t m_gpioclock;
GPIO_TypeDef * m_txport;
uint32_t m_txpin;
GPIO_TypeDef * m_rxport;
uint32_t m_rxpin;
uint32_t m_clockdiv;
};
class Usart {
public:
Usart() = default;
Usart(UsartInstance instance, UsartSettings settings);
bool Initialize();
bool Transmit(uint8_t * buffer);
private:
UsartConfig m_config;
UsartSettings m_settings;
bool Init(USART_TypeDef * instance, uint32_t baudrate,uint32_t bits,uint32_t parity, uint32_t stopbit,uint32_t flowcontrol);
};
/* Define used to enable Virtual Com Port use :
USE_VCP_CONNECTION == 0
USART1 instance is used. (TX on PA.09, RX on PA.10)
(requires wiring USART1 TX/Rx Pins to PC connection (could be achieved thanks to a USB to UART adapter)
USE_VCP_CONNECTION == 1
USART3 instance is used. (TX on PD.08, RX on PD.09)
(please ensure that USART communication between the target MCU and ST-LINK MCU is properly enabled
on HW board in order to support Virtual Com Port)
*/
#define USE_VCP_CONNECTION 1
/* Private definitions covering GPIO clock and USART pins
depending on selected USART instance. */
#if (USE_VCP_CONNECTION == 0)
/* USART1 instance is used. (TX on PA.09, RX on PA.10)
(requires wiring USART1 TX/Rx Pins to USB to UART adapter) */
#define USARTx_INSTANCE USART1
#define USARTx_CLK_ENABLE() LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_USART1)
#define USARTx_CLK_SOURCE() LL_RCC_SetUSARTClockSource(LL_RCC_USART1_CLKSOURCE_PCLK2)
#define USARTx_GPIO_CLK_ENABLE() LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA) /* Enable the peripheral clock of GPIOA */
#define USARTx_TX_PIN LL_GPIO_PIN_9
#define USARTx_TX_GPIO_PORT GPIOA
#define USARTx_SET_TX_GPIO_AF() LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_9, LL_GPIO_AF_7)
#define USARTx_RX_PIN LL_GPIO_PIN_10
#define USARTx_RX_GPIO_PORT GPIOA
#define USARTx_SET_RX_GPIO_AF() LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_10, LL_GPIO_AF_7)
#define APB_Div 2
#else
/* USART3 instance is used. (TX on PD.08, RX on PD.09)
(please ensure that USART communication between the target MCU and ST-LINK MCU is properly enabled
on HW board in order to support Virtual Com Port) */
#define USARTx_INSTANCE USART3
#define USARTx_CLK_ENABLE() LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART3)
#define USARTx_CLK_SOURCE() LL_RCC_SetUSARTClockSource(LL_RCC_USART3_CLKSOURCE_PCLK1)
#define USARTx_GPIO_CLK_ENABLE() LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOD) /* Enable the peripheral clock of GPIOD */
#define USARTx_TX_PIN LL_GPIO_PIN_8
#define USARTx_TX_GPIO_PORT GPIOD
#define USARTx_SET_TX_GPIO_AF() LL_GPIO_SetAFPin_8_15(GPIOD, LL_GPIO_PIN_8, LL_GPIO_AF_7)
#define USARTx_RX_PIN LL_GPIO_PIN_9
#define USARTx_RX_GPIO_PORT GPIOD
#define USARTx_SET_RX_GPIO_AF() LL_GPIO_SetAFPin_8_15(GPIOD, LL_GPIO_PIN_9, LL_GPIO_AF_7)
#define APB_Div 4
#endif /* (USE_VCP_CONNECTION == 0) */
#define USER_BUTTON_PIN LL_GPIO_PIN_13
#define USER_BUTTON_GPIO_PORT GPIOC
#define USER_BUTTON_GPIO_CLK_ENABLE() LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOC)
#define USER_BUTTON_EXTI_LINE LL_EXTI_LINE_13
#define USER_BUTTON_EXTI_IRQn EXTI15_10_IRQn
#define USER_BUTTON_EXTI_LINE_ENABLE() LL_EXTI_EnableIT_0_31(USER_BUTTON_EXTI_LINE)
#define USER_BUTTON_EXTI_FALLING_TRIG_ENABLE() LL_EXTI_EnableFallingTrig_0_31(USER_BUTTON_EXTI_LINE)
#define USER_BUTTON_SYSCFG_SET_EXTI() do { \
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SYSCFG); \
LL_SYSCFG_SetEXTISource(LL_SYSCFG_EXTI_PORTC, LL_SYSCFG_EXTI_LINE13); \
} while(0)
#define USER_BUTTON_IRQHANDLER EXTI15_10_IRQHandler
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* INC_UART_H_ */
| 34.415663 | 190 | 0.707159 |
a991a59fb6a6c343ece2bc832a5aec97ea9126c2 | 2,887 | h | C | src/net/quic/quic_flags.h | lunshengning/lsn | 1ac7395cd22467800cae2aeb364d87ebe83cb1a7 | [
"BSD-3-Clause"
] | null | null | null | src/net/quic/quic_flags.h | lunshengning/lsn | 1ac7395cd22467800cae2aeb364d87ebe83cb1a7 | [
"BSD-3-Clause"
] | null | null | null | src/net/quic/quic_flags.h | lunshengning/lsn | 1ac7395cd22467800cae2aeb364d87ebe83cb1a7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_QUIC_QUIC_FLAGS_H_
#define NET_QUIC_QUIC_FLAGS_H_
#include <stdint.h>
#include "net/base/net_export.h"
NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_time_loss_detection;
NET_EXPORT_PRIVATE extern bool FLAGS_use_early_return_when_verifying_chlo;
NET_EXPORT_PRIVATE extern bool FLAGS_enable_quic_fec;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_bbr_congestion_control;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_allow_bbr;
NET_EXPORT_PRIVATE extern int64_t FLAGS_quic_time_wait_list_seconds;
NET_EXPORT_PRIVATE extern int64_t FLAGS_quic_time_wait_list_max_connections;
NET_EXPORT_PRIVATE extern bool FLAGS_enable_quic_stateless_reject_support;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_always_log_bugs_for_tests;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_auto_tune_receive_window;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_enable_multipath;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_require_handshake_confirmation;
NET_EXPORT_PRIVATE extern bool FLAGS_shift_quic_cubic_epoch_when_app_limited;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_measure_headers_hol_blocking_time;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_disable_pacing;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_new_idle_timeout;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_stream_sequencer_buffer;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_respect_send_alarm2;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_batch_writes;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_block_unencrypted_writes;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_never_write_unencrypted_data;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_no_unencrypted_fec;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_require_fix;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_supports_trailers;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_supports_push_promise;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_distinguish_incoming_outgoing_streams;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_validate_stk_without_scid;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_rfc7539;
NET_EXPORT_PRIVATE extern bool FLAGS_require_strike_register_or_server_nonce;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_log_loss_event;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_include_path_id_in_iv;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_cede_correctly;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_different_max_num_open_streams;
NET_EXPORT_PRIVATE extern bool
FLAGS_quic_crypto_server_config_default_has_chacha20;
NET_EXPORT_PRIVATE extern bool FLAGS_check_peer_address_change_after_decryption;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_log_received_parameters;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_new_tcp_sender;
NET_EXPORT_PRIVATE extern bool FLAGS_quic_save_initial_subkey_secret;
#endif // NET_QUIC_QUIC_FLAGS_H_
| 54.471698 | 80 | 0.907863 |
45e90fb2710f406ec0002e85580ef896cd78f1d6 | 1,563 | h | C | images/player6.h | jpfli/Pomifactory | ee736a97bcbb5f16625aedae492c267e4911378c | [
"MIT"
] | 2 | 2020-06-16T18:14:53.000Z | 2020-10-07T10:42:28.000Z | images/player6.h | jpfli/Pomifactory | ee736a97bcbb5f16625aedae492c267e4911378c | [
"MIT"
] | null | null | null | images/player6.h | jpfli/Pomifactory | ee736a97bcbb5f16625aedae492c267e4911378c | [
"MIT"
] | null | null | null | // Automatically generated file, do not edit.
#pragma once
const uint8_t player6[] = {
24, 24,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x3c,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x00,0xcc,0x3c,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc3,0xcc,0x33,0x33,0xc0,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc3,0xcc,0x3c,0x33,0xc0,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc3,0x33,0x33,0x33,0xc0,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc3,0x33,0x33,0x33,0xc0,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc3,0x33,0x33,0x33,0xc0,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc3,0x33,0x33,0x33,0xc0,
0x00,0x00,0x00,0xcc,0x00,0x00,0x00,0xc3,0x33,0x33,0x3c,0x00,
0x00,0x00,0x0c,0x33,0xc0,0x00,0x0c,0x33,0x3c,0xcc,0xc0,0x00,
0x00,0x00,0xc3,0x33,0x3c,0xc0,0x0c,0x33,0x3c,0x3c,0x00,0x00,
0x00,0x00,0xc3,0x33,0x33,0x3c,0xc3,0x33,0x3c,0x3c,0x00,0x00,
0x00,0x0c,0x33,0x3c,0x33,0x33,0x33,0x33,0x3c,0x3c,0x00,0x00,
0x00,0xcc,0x33,0xc0,0xc3,0x33,0x33,0x33,0xcc,0x3c,0xc0,0x00,
0x0c,0x33,0x33,0xc0,0xc3,0x33,0x33,0x33,0xcc,0x33,0x3c,0x00,
0x0c,0x33,0x33,0xc0,0xc3,0x33,0x33,0x3c,0x0c,0x33,0x3c,0x00
};
| 48.84375 | 60 | 0.78055 |
04ebef573cee5766b3b77e49918eaab416a40c14 | 29,185 | c | C | src/portapi.c | k-tsj/Gauche | 8bbb9d1e80433ca2e42f6e531d71a48dc4c5964a | [
"BSD-3-Clause"
] | null | null | null | src/portapi.c | k-tsj/Gauche | 8bbb9d1e80433ca2e42f6e531d71a48dc4c5964a | [
"BSD-3-Clause"
] | null | null | null | src/portapi.c | k-tsj/Gauche | 8bbb9d1e80433ca2e42f6e531d71a48dc4c5964a | [
"BSD-3-Clause"
] | null | null | null | /*
* portapi.c - port common API
*
* Copyright (c) 2000-2013 Shiro Kawai <shiro@acm.org>
*
* 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 authors nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This file is included _twice_ by port.c to define safe- and unsafe-
* variant of port common APIs. It is to minimize the overhead of
* locking operations.
*
* The macro SHORTCUT allows 'safe' version to bypass lock/unlock
* stuff by calling 'unsafe' version when the port is already locked by
* the calling thread.
*/
/* [scratch and ungottern buffer]
* It is always possible to mix binary and character i/o for Gauche's
* ports. To support peek operations in Scheme and 'unget' operations
* in C, we need to buffer at most one character or its equivalent
* byte sequence. The 'ungotten' and 'scratch' fields are used for
* character and binary buffering, respectively.
* (This level of buffering is common to all input port types, and
* distinct from the buffering of 'buffered' (file) port type.)
*
* 'Ungotten' field keeps SCM_CHAR_INVALID if there's no buffered
* character. Otherwise, its value is the buffered character.
* The number of bytes in the 'scratch' array is kept in 'scrcnt'
* field. If 'scrcnt' field is not zero, there's data in the
* 'scratch' array.
*
* In no cases there should be data in both ungotten and scratch
* field. The consistency is taken care of the routines defined here;
* no other routine should touch these buffering field.
*/
#ifdef SAFE_PORT_OP
#define VMDECL ScmVM *vm = Scm_VM()
#define LOCK(p) PORT_LOCK(p, vm)
#define UNLOCK(p) PORT_UNLOCK(p)
#define SAFE_CALL(p, exp) PORT_SAFE_CALL(p, exp)
#define SHORTCUT(p, unsafe) \
do { if (PORT_LOCKED(p, vm)) { unsafe; }} while (0)
#else
#define VMDECL /*none*/
#define LOCK(p) /*none*/
#define UNLOCK(p) /*none*/
#define SAFE_CALL(p, exp) (exp)
#define SHORTCUT(p, unsafe) /* none */
#endif
/* Convenience macro */
#ifndef CLOSE_CHECK
#define CLOSE_CHECK(port) \
do { \
if (SCM_PORT_CLOSED_P(port)) { \
UNLOCK(p); \
Scm_PortError((port), SCM_PORT_ERROR_CLOSED, \
"I/O attempted on closed port: %S", (port)); \
} \
} while (0)
#endif /* CLOSE_CHECK */
/*=================================================================
* Putb
*/
#ifdef SAFE_PORT_OP
void Scm_Putb(ScmByte b, ScmPort *p)
#else
void Scm_PutbUnsafe(ScmByte b, ScmPort *p)
#endif
{
VMDECL;
SHORTCUT(p, Scm_PutbUnsafe(b, p); return);
LOCK(p);
CLOSE_CHECK(p);
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
if (p->src.buf.current >= p->src.buf.end) {
SAFE_CALL(p, bufport_flush(p, (int)(p->src.buf.current - p->src.buf.buffer), FALSE));
}
SCM_ASSERT(p->src.buf.current < p->src.buf.end);
*p->src.buf.current++ = b;
if (p->src.buf.mode == SCM_PORT_BUFFER_NONE) {
SAFE_CALL(p, bufport_flush(p, 1, FALSE));
}
UNLOCK(p);
break;
case SCM_PORT_OSTR:
SCM_DSTRING_PUTB(&p->src.ostr, b);
UNLOCK(p);
break;
case SCM_PORT_PROC:
SAFE_CALL(p, p->src.vt.Putb(b, p));
UNLOCK(p);
break;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_OUTPUT,
"bad port type for output: %S", p);
}
}
/*=================================================================
* Putc
*/
#ifdef SAFE_PORT_OP
void Scm_Putc(ScmChar c, ScmPort *p)
#else
void Scm_PutcUnsafe(ScmChar c, ScmPort *p)
#endif
{
int nb;
VMDECL;
SHORTCUT(p, Scm_PutcUnsafe(c, p); return);
LOCK(p);
CLOSE_CHECK(p);
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
nb = SCM_CHAR_NBYTES(c);
if (p->src.buf.current+nb > p->src.buf.end) {
SAFE_CALL(p, bufport_flush(p, (int)(p->src.buf.current - p->src.buf.buffer), FALSE));
}
SCM_ASSERT(p->src.buf.current+nb <= p->src.buf.end);
SCM_CHAR_PUT(p->src.buf.current, c);
p->src.buf.current += nb;
if (p->src.buf.mode == SCM_PORT_BUFFER_LINE) {
if (c == '\n') {
SAFE_CALL(p, bufport_flush(p, nb, FALSE));
}
} else if (p->src.buf.mode == SCM_PORT_BUFFER_NONE) {
SAFE_CALL(p, bufport_flush(p, nb, FALSE));
}
UNLOCK(p);
break;
case SCM_PORT_OSTR:
SCM_DSTRING_PUTC(&p->src.ostr, c);
UNLOCK(p);
break;
case SCM_PORT_PROC:
SAFE_CALL(p, p->src.vt.Putc(c, p));
UNLOCK(p);
break;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_OUTPUT,
"bad port type for output: %S", p);
}
}
/*=================================================================
* Puts
*/
#ifdef SAFE_PORT_OP
void Scm_Puts(ScmString *s, ScmPort *p)
#else
void Scm_PutsUnsafe(ScmString *s, ScmPort *p)
#endif
{
VMDECL;
SHORTCUT(p, Scm_PutsUnsafe(s, p); return);
LOCK(p);
CLOSE_CHECK(p);
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE: {
u_int size;
const char *ss = Scm_GetStringContent(s, &size, NULL, NULL);
SAFE_CALL(p, bufport_write(p, ss, size));
if (p->src.buf.mode == SCM_PORT_BUFFER_LINE) {
const char *cp = p->src.buf.current;
while (cp-- > p->src.buf.buffer) {
if (*cp == '\n') {
SAFE_CALL(p, bufport_flush(p, (int)(cp - p->src.buf.current), FALSE));
break;
}
}
} else if (p->src.buf.mode == SCM_PORT_BUFFER_NONE) {
SAFE_CALL(p, bufport_flush(p, 0, TRUE));
}
UNLOCK(p);
break;
}
case SCM_PORT_OSTR:
Scm_DStringAdd(&p->src.ostr, s);
UNLOCK(p);
break;
case SCM_PORT_PROC:
SAFE_CALL(p, p->src.vt.Puts(s, p));
UNLOCK(p);
break;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_OUTPUT,
"bad port type for output: %S", p);
}
}
/*=================================================================
* Putz
*/
#ifdef SAFE_PORT_OP
void Scm_Putz(const char *s, int siz, ScmPort *p)
#else
void Scm_PutzUnsafe(const char *s, int siz, ScmPort *p)
#endif
{
VMDECL;
SHORTCUT(p, Scm_PutzUnsafe(s, siz, p); return);
LOCK(p);
CLOSE_CHECK(p);
if (siz < 0) siz = (int)strlen(s);
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
SAFE_CALL(p, bufport_write(p, s, siz));
if (p->src.buf.mode == SCM_PORT_BUFFER_LINE) {
const char *cp = p->src.buf.current;
while (cp-- > p->src.buf.buffer) {
if (*cp == '\n') {
SAFE_CALL(p, bufport_flush(p, (int)(cp - p->src.buf.current), FALSE));
break;
}
}
} else if (p->src.buf.mode == SCM_PORT_BUFFER_NONE) {
SAFE_CALL(p, bufport_flush(p, 0, TRUE));
}
UNLOCK(p);
break;
case SCM_PORT_OSTR:
Scm_DStringPutz(&p->src.ostr, s, siz);
UNLOCK(p);
break;
case SCM_PORT_PROC:
SAFE_CALL(p, p->src.vt.Putz(s, siz, p));
UNLOCK(p);
break;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_OUTPUT,
"bad port type for output: %S", p);
}
}
/*=================================================================
* Flush
*/
#ifdef SAFE_PORT_OP
void Scm_Flush(ScmPort *p)
#else
void Scm_FlushUnsafe(ScmPort *p)
#endif
{
VMDECL;
SHORTCUT(p, Scm_FlushUnsafe(p); return);
LOCK(p);
CLOSE_CHECK(p);
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
SAFE_CALL(p, bufport_flush(p, 0, TRUE));
UNLOCK(p);
break;
case SCM_PORT_OSTR:
UNLOCK(p);
break;
case SCM_PORT_PROC:
SAFE_CALL(p, p->src.vt.Flush(p));
UNLOCK(p);
break;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_OUTPUT,
"bad port type for output: %S", p);
}
}
/*=================================================================
* Ungetc & PeekChar
*/
#ifdef SAFE_PORT_OP
void Scm_Ungetc(ScmChar c, ScmPort *p)
#else
void Scm_UngetcUnsafe(ScmChar c, ScmPort *p)
#endif
{
VMDECL;
SHORTCUT(p, Scm_UngetcUnsafe(c, p); return);
LOCK(p);
if (p->ungotten != SCM_CHAR_INVALID
|| p->scrcnt != 0) {
Scm_PortError(p, SCM_PORT_ERROR_INPUT,
"pushback buffer overflow on port %S", p);
}
p->ungotten = c;
UNLOCK(p);
}
#ifdef SAFE_PORT_OP
ScmChar Scm_Peekc(ScmPort *p)
#else
ScmChar Scm_PeekcUnsafe(ScmPort *p)
#endif
{
ScmChar ch;
VMDECL;
SHORTCUT(p, return Scm_PeekcUnsafe(p));
LOCK(p);
if ((ch = p->ungotten) == SCM_CHAR_INVALID) {
ch = Scm_GetcUnsafe(p);
p->ungotten = ch;
}
UNLOCK(p);
return ch;
}
/*=================================================================
* Ungetb & PeekByte
*/
#ifdef SAFE_PORT_OP
void Scm_Ungetb(int b, ScmPort *p)
#else
void Scm_UngetbUnsafe(int b, ScmPort *p)
#endif
{
VMDECL;
SHORTCUT(p, Scm_UngetbUnsafe(b, p); return);
LOCK(p);
if (p->ungotten != SCM_CHAR_INVALID
|| p->scrcnt >= SCM_CHAR_MAX_BYTES) {
Scm_PortError(p, SCM_PORT_ERROR_INPUT,
"pushback buffer overflow on port %S", p);
}
p->scratch[p->scrcnt++] = b;
UNLOCK(p);
}
#ifdef SAFE_PORT_OP
int Scm_Peekb(ScmPort *p)
#else
int Scm_PeekbUnsafe(ScmPort *p)
#endif
{
int b;
VMDECL;
SHORTCUT(p, return Scm_PeekbUnsafe(p));
LOCK(p);
if (p->scrcnt > 0) {
b = (unsigned char)p->scratch[0];
} else {
SCM_GETB(b, p);
if (b >= 0) {
if (p->scrcnt > 0) {
/* unshift scratch buffer */
int i;
SCM_ASSERT(p->scrcnt < SCM_CHAR_MAX_BYTES);
for (i=p->scrcnt; i>0; i--) {
p->scratch[i] = p->scratch[i-1];
}
p->scratch[0] = b;
p->scrcnt++;
} else {
p->scratch[0] = b;
p->scrcnt = 1;
}
}
}
UNLOCK(p);
return b;
}
/*=================================================================
* Getb
*/
#ifndef SHIFT_SCRATCH /* we need to define this only once */
#define SHIFT_SCRATCH
/* shift scratch buffer content */
static inline void shift_scratch(ScmPort *p, int off)
{
u_int i;
for (i=0; i<p->scrcnt; i++) {
p->scratch[i] = p->scratch[i+off];
}
}
/* handle the case that there's remaining data in the scratch buffer */
static int getb_scratch(ScmPort *p)
{
int b = (unsigned char)p->scratch[0];
p->scrcnt--;
shift_scratch(p, 1);
return b;
}
/* handle the case that there's an ungotten char */
static int getb_ungotten(ScmPort *p)
{
SCM_CHAR_PUT(p->scratch, p->ungotten);
p->scrcnt = SCM_CHAR_NBYTES(p->ungotten);
p->ungotten = SCM_CHAR_INVALID;
return getb_scratch(p);
}
#endif /*SHIFT_SCRATCH*/
/* Getb body */
#ifdef SAFE_PORT_OP
int Scm_Getb(ScmPort *p)
#else
int Scm_GetbUnsafe(ScmPort *p)
#endif
{
int b = 0, r = 0;
VMDECL;
SHORTCUT(p, return Scm_GetbUnsafe(p));
LOCK(p);
CLOSE_CHECK(p);
/* check if there's "pushed back" stuff */
if (p->scrcnt) {
b = getb_scratch(p);
} else if (p->ungotten != SCM_CHAR_INVALID) {
b = getb_ungotten(p);
} else {
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
if (p->src.buf.current >= p->src.buf.end) {
SAFE_CALL(p, r = bufport_fill(p, 1, FALSE));
if (r == 0) {
UNLOCK(p);
return EOF;
}
}
b = (unsigned char)*p->src.buf.current++;
break;
case SCM_PORT_ISTR:
if (p->src.istr.current >= p->src.istr.end) b = EOF;
else b = (unsigned char)*p->src.istr.current++;
break;
case SCM_PORT_PROC:
SAFE_CALL(p, b = p->src.vt.Getb(p));
break;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_INPUT,
"bad port type for input: %S", p);
}
p->bytes++;
}
UNLOCK(p);
return b;
}
/*=================================================================
* Getc
*/
/* handle the case that there's data in scratch area */
#ifdef SAFE_PORT_OP
#define GETC_SCRATCH getc_scratch
static int getc_scratch(ScmPort *p)
#else
#define GETC_SCRATCH getc_scratch_unsafe
static int getc_scratch_unsafe(ScmPort *p)
#endif
{
char tbuf[SCM_CHAR_MAX_BYTES];
int nb = SCM_CHAR_NFOLLOWS(p->scratch[0]), ch, i, curr = p->scrcnt;
int r = 0;
memcpy(tbuf, p->scratch, curr);
p->scrcnt = 0;
for (i=curr; i<=nb; i++) {
SAFE_CALL(p, r = Scm_Getb(p));
if (r == EOF) {
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_INPUT,
"encountered EOF in middle of a multibyte character from port %S", p);
}
tbuf[i] = (char)r;
}
SCM_CHAR_GET(tbuf, ch);
return ch;
}
/* Getc body */
#ifdef SAFE_PORT_OP
int Scm_Getc(ScmPort *p)
#else
int Scm_GetcUnsafe(ScmPort *p)
#endif
{
int first, nb, c = 0, r = 0;
VMDECL;
SHORTCUT(p, return Scm_GetcUnsafe(p));
LOCK(p);
CLOSE_CHECK(p);
if (p->scrcnt > 0) {
r = GETC_SCRATCH(p);
UNLOCK(p);
return r;
}
if (p->ungotten != SCM_CHAR_INVALID) {
c = p->ungotten;
p->ungotten = SCM_CHAR_INVALID;
UNLOCK(p);
return c;
}
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
if (p->src.buf.current >= p->src.buf.end) {
SAFE_CALL(p, r = bufport_fill(p, 1, FALSE));
if (r == 0) {
UNLOCK(p);
return EOF;
}
}
first = (unsigned char)*p->src.buf.current++;
nb = SCM_CHAR_NFOLLOWS(first);
p->bytes++;
if (nb > 0) {
if (p->src.buf.current + nb > p->src.buf.end) {
/* The buffer doesn't have enough bytes to consist a char.
move the incomplete char to the scratch buffer and try
to fetch the rest of the char. */
int rest, filled = 0;
p->scrcnt = (unsigned char)(p->src.buf.end - p->src.buf.current + 1);
memcpy(p->scratch, p->src.buf.current-1, p->scrcnt);
p->src.buf.current = p->src.buf.end;
rest = nb + 1 - p->scrcnt;
for (;;) {
SAFE_CALL(p, filled = bufport_fill(p, rest, FALSE));
if (filled <= 0) {
/* TODO: make this behavior customizable */
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_INPUT,
"encountered EOF in middle of a multibyte character from port %S", p);
}
if (filled >= rest) {
memcpy(p->scratch+p->scrcnt, p->src.buf.current, rest);
p->scrcnt += rest;
p->src.buf.current += rest;
break;
} else {
memcpy(p->scratch+p->scrcnt, p->src.buf.current, filled);
p->scrcnt += filled;
p->src.buf.current = p->src.buf.end;
rest -= filled;
}
}
SCM_CHAR_GET(p->scratch, c);
p->scrcnt = 0;
} else {
SCM_CHAR_GET(p->src.buf.current-1, c);
p->src.buf.current += nb;
}
p->bytes += nb;
} else {
c = first;
if (c == '\n') p->line++;
}
UNLOCK(p);
return c;
case SCM_PORT_ISTR:
if (p->src.istr.current >= p->src.istr.end) {
UNLOCK(p);
return EOF;
}
first = (unsigned char)*p->src.istr.current++;
nb = SCM_CHAR_NFOLLOWS(first);
p->bytes++;
if (nb > 0) {
if (p->src.istr.current + nb > p->src.istr.end) {
/* TODO: make this behavior customizable */
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_INPUT,
"encountered EOF in middle of a multibyte character from port %S", p);
}
SCM_CHAR_GET(p->src.istr.current-1, c);
p->src.istr.current += nb;
p->bytes += nb;
} else {
c = first;
if (c == '\n') p->line++;
}
UNLOCK(p);
return c;
case SCM_PORT_PROC:
SAFE_CALL(p, c = p->src.vt.Getc(p));
if (c == '\n') p->line++;
UNLOCK(p);
return c;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_INPUT, "bad port type for input: %S", p);
}
return 0;/*dummy*/
}
#undef GETC_SCRATCH
/*=================================================================
* Getz - block read.
* If the buffering mode is BUFFER_FULL, this reads BUFLEN bytes
* unless it reaches EOF. Otherwise, this reads less than BUFLEN
* if the data is not immediately available.
*/
#ifdef SAFE_PORT_OP
#define GETZ_SCRATCH getz_scratch
static int getz_scratch(char *buf, int buflen, ScmPort *p)
#else
#define GETZ_SCRATCH getz_scratch_unsafe
static int getz_scratch_unsafe(char *buf, int buflen, ScmPort *p)
#endif
{
int i, n = 0;
if (p->scrcnt >= (u_int)buflen) {
memcpy(buf, p->scratch, buflen);
p->scrcnt -= buflen;
shift_scratch(p, buflen);
return buflen;
} else {
memcpy(buf, p->scratch, p->scrcnt);
i = p->scrcnt;
p->scrcnt = 0;
SAFE_CALL(p, n = Scm_Getz(buf+i, buflen-i, p));
return i + n;
}
}
#ifndef GETZ_ISTR /* common part */
#define GETZ_ISTR getz_istr
static int getz_istr(ScmPort *p, char *buf, int buflen)
{
int siz;
if (p->src.istr.current + buflen >= p->src.istr.end) {
if (p->src.istr.current >= p->src.istr.end) return EOF;
siz = (int)(p->src.istr.end - p->src.istr.current);
memcpy(buf, p->src.istr.current, siz);
p->src.istr.current = p->src.istr.end;
return siz;
} else {
memcpy(buf, p->src.istr.current, buflen);
p->src.istr.current += buflen;
return buflen;
}
}
#endif /*!GETZ_ISTR*/
#ifdef SAFE_PORT_OP
int Scm_Getz(char *buf, int buflen, ScmPort *p)
#else
int Scm_GetzUnsafe(char *buf, int buflen, ScmPort *p)
#endif
{
int siz = 0, r = 0;
VMDECL;
SHORTCUT(p, return Scm_GetzUnsafe(buf, buflen, p));
LOCK(p);
CLOSE_CHECK(p);
if (p->scrcnt) {
r = GETZ_SCRATCH(buf, buflen, p);
UNLOCK(p);
return r;
}
if (p->ungotten != SCM_CHAR_INVALID) {
p->scrcnt = SCM_CHAR_NBYTES(p->ungotten);
SCM_CHAR_PUT(p->scratch, p->ungotten);
p->ungotten = SCM_CHAR_INVALID;
r = GETZ_SCRATCH(buf, buflen, p);
UNLOCK(p);
return r;
}
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
SAFE_CALL(p, siz = bufport_read(p, buf, buflen));
p->bytes += siz;
UNLOCK(p);
if (siz == 0) return EOF;
else return siz;
case SCM_PORT_ISTR:
r = GETZ_ISTR(p, buf, buflen);
p->bytes += r;
UNLOCK(p);
return r;
case SCM_PORT_PROC:
SAFE_CALL(p, r = p->src.vt.Getz(buf, buflen, p));
p->bytes += r;
UNLOCK(p);
return r;
default:
UNLOCK(p);
Scm_PortError(p, SCM_PORT_ERROR_INPUT, "bad port type for input: %S", p);
}
return -1; /* dummy */
}
#undef GETZ_SCRATCH
/*=================================================================
* ReadLine
* Reads up to EOL or EOF.
*/
/* Auxiliary procedures */
/* NB: it may be further optimized by scanning the contents of buffer
when the port is a buffered port or an input string, which allows
us to avoid mb->wc->mb conversion. See port.c, v 1.69 for some
attempt to do so. The problem there is that if I have to take
into account the cases of the ungotten char and the scratch buffer,
code becomes ugly. There might be some better approach. */
#ifndef READLINE_AUX
#define READLINE_AUX
/* Assumes the port is locked, and the caller takes care of unlocking
even if an error is signalled within this body */
/* NB: this routine reads bytes, not chars. It allows to readline
from a port in unknown character encoding (e.g. reading the first
line of xml doc to find out charset parameter). */
ScmObj readline_body(ScmPort *p)
{
int b1 = 0, b2 = 0;
ScmDString ds;
Scm_DStringInit(&ds);
b1 = Scm_GetbUnsafe(p);
if (b1 == EOF) return SCM_EOF;
for (;;) {
if (b1 == EOF) return Scm_DStringGet(&ds, 0);
if (b1 == '\n') break;
if (b1 == '\r') {
b2 = Scm_GetbUnsafe(p);
if (b2 == EOF || b2 == '\n') break;
Scm_UngetbUnsafe(b2, p);
break;
}
SCM_DSTRING_PUTB(&ds, b1);
b1 = Scm_GetbUnsafe(p);
}
p->line++;
return Scm_DStringGet(&ds, 0);
}
#endif /* READLINE_AUX */
#ifdef SAFE_PORT_OP
ScmObj Scm_ReadLine(ScmPort *p)
#else
ScmObj Scm_ReadLineUnsafe(ScmPort *p)
#endif
{
ScmObj r = SCM_UNDEFINED;
VMDECL;
SHORTCUT(p, return Scm_ReadLineUnsafe(p));
LOCK(p);
SAFE_CALL(p, r = readline_body(p));
UNLOCK(p);
return r;
}
/*=================================================================
* ByteReady
*/
#ifdef SAFE_PORT_OP
int Scm_ByteReady(ScmPort *p)
#else
int Scm_ByteReadyUnsafe(ScmPort *p)
#endif
{
int r = 0;
VMDECL;
SHORTCUT(p, return Scm_ByteReadyUnsafe(p));
if (!SCM_IPORTP(p)) Scm_Error("input port required, but got %S", p);
LOCK(p);
if (p->ungotten != SCM_CHAR_INVALID
|| p->scrcnt > 0) {
r = TRUE;
} else {
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
if (p->src.buf.current < p->src.buf.end) r = TRUE;
else if (p->src.buf.ready == NULL) r = TRUE;
else {
SAFE_CALL(p, r = (p->src.buf.ready(p) != SCM_FD_WOULDBLOCK));
}
break;
case SCM_PORT_PROC:
SAFE_CALL(p, r = p->src.vt.Ready(p, FALSE));
break;
default:
r = TRUE;
}
}
UNLOCK(p);
return r;
}
/*=================================================================
* CharReady
*/
#ifdef SAFE_PORT_OP
int Scm_CharReady(ScmPort *p)
#else
int Scm_CharReadyUnsafe(ScmPort *p)
#endif
{
int r = 0;
VMDECL;
SHORTCUT(p, return Scm_CharReadyUnsafe(p));
if (!SCM_IPORTP(p)) Scm_Error("input port required, but got %S", p);
LOCK(p);
if (p->ungotten != SCM_CHAR_INVALID) r = TRUE;
else {
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
if (p->src.buf.current < p->src.buf.end) r = TRUE;
else if (p->src.buf.ready == NULL) r = TRUE;
else {
SAFE_CALL(p, r = (p->src.buf.ready(p) != SCM_FD_WOULDBLOCK));
}
break;
case SCM_PORT_PROC:
SAFE_CALL(p, r = p->src.vt.Ready(p, TRUE));
break;
default:
r = TRUE;
}
}
UNLOCK(p);
return r;
}
/*=================================================================
* PortSeek
*/
#ifndef SEEK_ISTR /* common part */
#define SEEK_ISTR seek_istr
static off_t seek_istr(ScmPort *p, off_t o, int whence, int nomove)
{
off_t r;
if (nomove) {
r = (off_t)(p->src.istr.current - p->src.istr.start);
} else {
long z = (long)o;
if (whence == SEEK_CUR) {
z += (long)(p->src.istr.current - p->src.istr.start);
} else if (whence == SEEK_END) {
z += (long)(p->src.istr.end - p->src.istr.start);
}
if (z < 0 || z > (long)(p->src.istr.end - p->src.istr.start)) {
r = (off_t)-1;
} else {
p->src.istr.current = p->src.istr.start + z;
r = (off_t)(p->src.istr.current - p->src.istr.start);
}
p->ungotten = SCM_CHAR_INVALID;
}
return r;
}
#endif /*SEEK_ISTR*/
#ifdef SAFE_PORT_OP
ScmObj Scm_PortSeek(ScmPort *p, ScmObj off, int whence)
#else
ScmObj Scm_PortSeekUnsafe(ScmPort *p, ScmObj off, int whence)
#endif
{
off_t r = (off_t)-1, o = Scm_IntegerToOffset(off);
int nomove = (whence == SEEK_CUR && o == 0);
VMDECL;
SHORTCUT(p, return Scm_PortSeekUnsafe(p, off, whence));
if (SCM_PORT_CLOSED_P(p)) {
Scm_PortError(p, SCM_PORT_ERROR_CLOSED,
"attempt to seek on closed port: %S", p);
}
LOCK(p);
switch (SCM_PORT_TYPE(p)) {
case SCM_PORT_FILE:
/* NB: we might be able to skip calling seeker if we keep the
# of bytes read or write so far, but such count may be off
when the port has been experienced an error condition. */
/* NB: the following doesn't work if we have bidirectional port.
In such case we need to keep whether the last call of buffer
handling routine was input or output. */
if (!p->src.buf.seeker) break;
if (nomove) {
SAFE_CALL(p, r = p->src.buf.seeker(p, 0, SEEK_CUR));
if (SCM_PORT_DIR(p)&SCM_PORT_INPUT) {
r -= (off_t)(p->src.buf.end - p->src.buf.current);
} else {
r += (off_t)(p->src.buf.current - p->src.buf.buffer);
}
} else {
/* NB: possible optimization: the specified position is within
the current buffer, we can avoid calling seeker. */
if (SCM_PORT_DIR(p)&SCM_PORT_INPUT) {
char *c = p->src.buf.current; /* save current ptr */
if (whence == SEEK_CUR) {
o -= (off_t)(p->src.buf.end - c);
}
p->src.buf.current = p->src.buf.end; /* invalidate buffer */
SAFE_CALL(p, r = p->src.buf.seeker(p, o, whence));
if (r == (off_t)-1) {
/* This may happend if seeker somehow gave up */
p->src.buf.current = c;
}
} else {
SAFE_CALL(p, bufport_flush(p, 0, TRUE));
SAFE_CALL(p, r = p->src.buf.seeker(p, o, whence));
}
/* Invalidate ungotten char */
p->ungotten = SCM_CHAR_INVALID;
}
break;
case SCM_PORT_ISTR:
r = SEEK_ISTR(p, o, whence, nomove);
break;
case SCM_PORT_OSTR:
if (nomove) {
r = (off_t)Scm_DStringSize(&(p->src.ostr));
} else {
/* Not supported yet */
r = (off_t)-1;
}
break;
case SCM_PORT_PROC:
if (p->src.vt.Seek) {
SAFE_CALL(p, r = p->src.vt.Seek(p, o, whence));
}
break;
}
UNLOCK(p);
if (r == (off_t)-1) return SCM_FALSE;
else return Scm_OffsetToInteger(r);
}
#undef VMDECL
#undef LOCK
#undef UNLOCK
#undef SAFE_CALL
#undef SHORTCUT
#undef CLOSE_CHECK
| 29.539474 | 108 | 0.528799 |
1074290702ae455e3d7c080e21421f3951ba29c5 | 1,224 | h | C | sources/drivers/misc/mediatek/gpu/mt6735/mali/drivers/gpu/arm/midgard/mali_kbase_hw.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 2 | 2018-03-09T23:59:27.000Z | 2018-04-01T07:58:39.000Z | sources/drivers/misc/mediatek/gpu/mt6735/mali/drivers/gpu/arm/midgard/mali_kbase_hw.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | null | null | null | sources/drivers/misc/mediatek/gpu/mt6735/mali/drivers/gpu/arm/midgard/mali_kbase_hw.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 3 | 2017-06-24T20:23:09.000Z | 2018-03-25T04:30:11.000Z | /*
*
* (C) COPYRIGHT ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation, and any use by you of this program is subject to the terms
* of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained
* from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
/**
* @file
* Run-time work-arounds helpers
*/
#ifndef _KBASE_HW_H_
#define _KBASE_HW_H_
#include "mali_kbase_defs.h"
/**
* @brief Tell whether a work-around should be enabled
*/
#define kbase_hw_has_issue(kbdev, issue)\
test_bit(issue, &(kbdev)->hw_issues_mask[0])
/**
* @brief Tell whether a feature is supported
*/
#define kbase_hw_has_feature(kbdev, feature)\
test_bit(feature, &(kbdev)->hw_features_mask[0])
/**
* @brief Set the HW issues mask depending on the GPU ID
*/
mali_error kbase_hw_set_issues_mask(struct kbase_device *kbdev);
/**
* @brief Set the features mask depending on the GPU ID
*/
void kbase_hw_set_features_mask(struct kbase_device *kbdev);
#endif /* _KBASE_HW_H_ */
| 23.09434 | 79 | 0.721405 |
313aeac218d82e1e46257e72aee3baeba96a305e | 505 | h | C | YFCommonTools/Categories/UIKit/UIButton/UIButtonCategoryHeader.h | BigShow1949/YFCommonTools | 4d524e15e1d6d3736eb5874e621164fa8126161b | [
"MIT"
] | 2 | 2018-10-26T14:12:36.000Z | 2020-10-21T01:59:12.000Z | YFCommonTools/Categories/UIKit/UIButton/UIButtonCategoryHeader.h | BigShow1949/YFCommonTools | 4d524e15e1d6d3736eb5874e621164fa8126161b | [
"MIT"
] | null | null | null | YFCommonTools/Categories/UIKit/UIButton/UIButtonCategoryHeader.h | BigShow1949/YFCommonTools | 4d524e15e1d6d3736eb5874e621164fa8126161b | [
"MIT"
] | 2 | 2018-09-20T01:57:49.000Z | 2021-07-14T07:42:43.000Z | //
// UIButtonCategoryHeader.h
// YFToolsDemo
//
// Created by big show on 2019/3/27.
// Copyright © 2019年 BigShow. All rights reserved.
//
#ifndef UIButtonCategoryHeader_h
#define UIButtonCategoryHeader_h
#import "UIButton+BackgroundColor_yf.h"
#import "UIButton+Block_yf.h"
#import "UIButton+CountDown_yf.h"
#import "UIButton+Indicator_yf.h"
#import "UIButton+MiddleAligning_yf.h"
#import "UIButton+Submitting_yf.h"
#import "UIButton+TouchAreaInsets_yf.h"
#endif /* UIButtonCategoryHeader_h */
| 21.956522 | 51 | 0.770297 |
bdbe50086b4cf7200b264ffbf03784dccbe8c11e | 2,280 | h | C | Engine/Modules/Core/Include/Platform/Windows/PostWindowsApi.h | wanghaiwei/VisReal | e60158e65bae2ee838e73e5009d68c26da84ae74 | [
"MIT"
] | 1 | 2020-11-24T09:28:20.000Z | 2020-11-24T09:28:20.000Z | Engine/Modules/Core/Include/Platform/Windows/PostWindowsApi.h | wanghaiwei/VisReal | e60158e65bae2ee838e73e5009d68c26da84ae74 | [
"MIT"
] | null | null | null | Engine/Modules/Core/Include/Platform/Windows/PostWindowsApi.h | wanghaiwei/VisReal | e60158e65bae2ee838e73e5009d68c26da84ae74 | [
"MIT"
] | null | null | null | /**
* Created by rayfalling on 2020/11/26.
*
* Use Epic version to make <Windows.h> include correctly
* */
// Hide Windows-only types (same as HideWindowsPlatformTypes.h)
#undef INT
#undef UINT
#undef DWORD
#undef FLOAT
// Undo any Windows defines.
#undef uint8
#undef uint16
#undef uint32
#undef int32
#undef float
#undef CDECL
#undef PF_MAX
#undef PlaySound
#undef DrawText
#undef CaptureStackBackTrace
#undef MemoryBarrier
#undef DeleteFile
#undef MoveFile
#undef CopyFile
#undef CreateDirectory
#undef GetCurrentTime
#undef SendMessage
#undef LoadString
#undef UpdateResource
#undef FindWindow
#undef GetObject
#undef GetEnvironmentVariable
#undef CreateFont
#undef CreateDesktop
#undef GetMessage
#undef PostMessage
#undef GetCommandLine
#undef GetProp
#undef SetPort
#undef SetProp
#undef GetFileAttributes
#undef ReportEvent
#undef GetClassName
#undef GetClassInfo
#undef Yield
#undef IMediaEventSink
#undef GetTempFileName
// Undefine all the atomics. AllowWindowsPlatformAtomics/HideWindowsPlatformAtomics temporarily defining these macros.
#if PLATFORM_WINDOWS || PLATFORM_HOLOLENS
#undef InterlockedIncrement
#undef InterlockedDecrement
#undef InterlockedAdd
#undef InterlockedExchange
#undef InterlockedExchangeAdd
#undef InterlockedCompareExchange
#undef InterlockedCompareExchangePointer
#undef InterlockedExchange64
#undef InterlockedExchangeAdd64
#undef InterlockedCompareExchange64
#undef InterlockedIncrement64
#undef InterlockedDecrement64
#undef InterlockedAnd
#undef InterlockedOr
#undef InterlockedXor
#endif
// Restore any previously defined macros
#pragma pop_macro("MAX_uint8")
#pragma pop_macro("MAX_uint16")
#pragma pop_macro("MAX_uint32")
#pragma pop_macro("MAX_int32")
#pragma pop_macro("TEXT")
#pragma pop_macro("TRUE")
#pragma pop_macro("FALSE")
// Restore the warning that the pack size is changed in this header.
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
// Redefine CDECL to our version of the #define. <AJS> Is this really necessary?
#define CDECL __cdecl /* Standard C function */
// Make sure version is high enough for API to be defined. For CRITICAL_SECTION
#if !defined(_XTL_) && (_WIN32_WINNT < 0x0403)
#error SetCriticalSectionSpinCount requires _WIN32_WINNT >= 0x0403
#endif
| 24.516129 | 118 | 0.80307 |
0890cd4d997b7852f75fa7ed2d3b5ec0982cee63 | 48,600 | h | C | IGC/Compiler/MetaDataApi/SpirMetaDataApi.h | bader/intel-graphics-compiler | 04f51dc2f3d5047f334da5cb5eebe568480622f5 | [
"MIT"
] | null | null | null | IGC/Compiler/MetaDataApi/SpirMetaDataApi.h | bader/intel-graphics-compiler | 04f51dc2f3d5047f334da5cb5eebe568480622f5 | [
"MIT"
] | null | null | null | IGC/Compiler/MetaDataApi/SpirMetaDataApi.h | bader/intel-graphics-compiler | 04f51dc2f3d5047f334da5cb5eebe568480622f5 | [
"MIT"
] | null | null | null | /*========================== begin_copyright_notice ============================
Copyright (c) 2014-2021 Intel Corporation
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.
============================= end_copyright_notice ===========================*/
#pragma once
#include "MetaDataApiUtils.h"
namespace IGC {
namespace SPIRMD
{
//typedefs and forward declarations
class VectorTypeHintMetaData;
typedef MetaObjectHandle<VectorTypeHintMetaData> VectorTypeHintMetaDataHandle;
class VersionMetaData;
typedef MetaObjectHandle<VersionMetaData> VersionMetaDataHandle;
class WorkGroupDimensionsMetaData;
typedef MetaObjectHandle<WorkGroupDimensionsMetaData> WorkGroupDimensionsMetaDataHandle;
class SubGroupDimensionsMetaData;
typedef MetaObjectHandle<SubGroupDimensionsMetaData> SubGroupDimensionsMetaDataHandle;
class WorkgroupWalkOrderMetaData;
typedef MetaObjectHandle<WorkgroupWalkOrderMetaData> WorkgroupWalkOrderMetaDataHandle;
class KernelMetaData;
typedef MetaObjectHandle<KernelMetaData> KernelMetaDataHandle;
typedef MetaDataList<VersionMetaDataHandle> OpenCLVersionsMetaDataList;
typedef MetaObjectHandle<OpenCLVersionsMetaDataList> OpenCLVersionsMetaDataListHandle;
typedef MetaDataList<VersionMetaDataHandle> SpirVersionsMetaDataList;
typedef MetaObjectHandle<SpirVersionsMetaDataList> SpirVersionsMetaDataListHandle;
typedef MetaDataList<std::string> InnerUsedKhrExtensionsMetaDataList;
typedef MetaObjectHandle<InnerUsedKhrExtensionsMetaDataList> InnerUsedKhrExtensionsMetaDataListHandle;
typedef MetaDataList<InnerUsedKhrExtensionsMetaDataListHandle> UsedKhrExtensionsMetaDataList;
typedef MetaObjectHandle<UsedKhrExtensionsMetaDataList> UsedKhrExtensionsMetaDataListHandle;
typedef MetaDataList<std::string> InnerUsedOptionalCoreFeaturesMetaDataList;
typedef MetaObjectHandle<InnerUsedOptionalCoreFeaturesMetaDataList> InnerUsedOptionalCoreFeaturesMetaDataListHandle;
typedef MetaDataList<InnerUsedOptionalCoreFeaturesMetaDataListHandle> UsedOptionalCoreFeaturesMetaDataList;
typedef MetaObjectHandle<UsedOptionalCoreFeaturesMetaDataList> UsedOptionalCoreFeaturesMetaDataListHandle;
typedef MetaDataList<int32_t> FloatingPointContractionsMetaDataList;
typedef MetaObjectHandle<FloatingPointContractionsMetaDataList> FloatingPointContractionsMetaDataListHandle;
typedef MetaDataList<KernelMetaDataHandle> KernelsMetaDataList;
typedef MetaObjectHandle<KernelsMetaDataList> KernelsMetaDataListHandle;
typedef MetaDataList<std::string> InnerCompilerOptionsMetaDataList;
typedef MetaObjectHandle<InnerCompilerOptionsMetaDataList> InnerCompilerOptionsMetaDataListHandle;
typedef MetaDataList<InnerCompilerOptionsMetaDataListHandle> CompilerOptionsMetaDataList;
typedef MetaObjectHandle<CompilerOptionsMetaDataList> CompilerOptionsMetaDataListHandle;
typedef MetaDataList<std::string> InnerCompilerExternalOptionsMetaDataList;
typedef MetaObjectHandle<InnerCompilerExternalOptionsMetaDataList> InnerCompilerExternalOptionsMetaDataListHandle;
typedef MetaDataList<InnerCompilerExternalOptionsMetaDataListHandle> CompilerExternalOptionsMetaDataList;
typedef MetaObjectHandle<CompilerExternalOptionsMetaDataList> CompilerExternalOptionsMetaDataListHandle;
typedef MetaDataList<int32_t> ArgAddressSpacesMetaDataList;
typedef MetaObjectHandle<ArgAddressSpacesMetaDataList> ArgAddressSpacesMetaDataListHandle;
typedef MetaDataList<std::string> ArgAccessQualifiersMetaDataList;
typedef MetaObjectHandle<ArgAccessQualifiersMetaDataList> ArgAccessQualifiersMetaDataListHandle;
typedef MetaDataList<std::string> ArgTypesMetaDataList;
typedef MetaObjectHandle<ArgTypesMetaDataList> ArgTypesMetaDataListHandle;
typedef MetaDataList<std::string> ArgBaseTypesMetaDataList;
typedef MetaObjectHandle<ArgBaseTypesMetaDataList> ArgBaseTypesMetaDataListHandle;
typedef MetaDataList<std::string> ArgTypeQualifiersMetaDataList;
typedef MetaObjectHandle<ArgTypeQualifiersMetaDataList> ArgTypeQualifiersMetaDataListHandle;
typedef MetaDataList<std::string> ArgNamesMetaDataList;
typedef MetaObjectHandle<ArgNamesMetaDataList> ArgNamesMetaDataListHandle;
///
// Read/Write the VectorTypeHint structure from/to LLVM metadata
//
class VectorTypeHintMetaData :public IMetaDataObject
{
public:
typedef VectorTypeHintMetaData _Myt;
typedef IMetaDataObject _Mybase;
// typedefs for data member types
typedef MetaDataValue<llvm::UndefValue>::value_type VecTypeType;
typedef MetaDataValue<bool>::value_type SignType;
public:
///
// Factory method - creates the VectorTypeHintMetaData from the given metadata node
//
static _Myt* get(const llvm::MDNode* pNode, bool hasId = false)
{
return new _Myt(pNode, hasId);
}
///
// Factory method - create the default empty VectorTypeHintMetaData object
static _Myt* get()
{
return new _Myt();
}
///
// Factory method - create the default empty named VectorTypeHintMetaData object
static _Myt* get(const char* name)
{
return new _Myt(name);
}
///
// Ctor - loads the VectorTypeHintMetaData from the given metadata node
//
VectorTypeHintMetaData(const llvm::MDNode* pNode, bool hasId);
///
// Default Ctor - creates the empty, not named VectorTypeHintMetaData object
//
VectorTypeHintMetaData();
///
// Ctor - creates the empty, named VectorTypeHintMetaData object
//
VectorTypeHintMetaData(const char* name);
/// VecType related methods
VecTypeType getVecType() const
{
return m_VecType.get();
}
bool isVecTypeHasValue() const
{
return m_VecType.hasValue();
}
/// Sign related methods
SignType getSign() const
{
return m_Sign.get();
}
bool isSignHasValue() const
{
return m_Sign.hasValue();
}
///
// Returns true if any of the VectorTypeHintMetaData`s members has changed
bool dirty() const;
///
// Returns true if the structure was loaded from the metadata or was changed
bool hasValue() const;
///
// Discards the changes done to the VectorTypeHintMetaData instance
void discardChanges();
///
// Generates the new MDNode hierarchy for the given structure
llvm::Metadata* generateNode(llvm::LLVMContext& context) const;
///
// Saves the structure changes to the given MDNode
void save(llvm::LLVMContext& context, llvm::MDNode* pNode) const;
private:
///
// Returns true if the given MDNode could be saved to without replacement
bool compatibleWith(const llvm::MDNode* pNode) const
{
return false;
}
private:
typedef MetaDataIterator<llvm::MDNode> NodeIterator;
llvm::Metadata* getVecTypeNode(const llvm::MDNode* pParentNode) const;
llvm::Metadata* getSignNode(const llvm::MDNode* pParentNode) const;
private:
// data members
MetaDataValue<llvm::UndefValue> m_VecType;
MetaDataValue<bool> m_Sign;
// parent node
const llvm::MDNode* m_pNode;
};
///
// Read/Write the Version structure from/to LLVM metadata
//
class VersionMetaData :public IMetaDataObject
{
public:
typedef VersionMetaData _Myt;
typedef IMetaDataObject _Mybase;
// typedefs for data member types
typedef MetaDataValue<int32_t>::value_type MajorType;
typedef MetaDataValue<int32_t>::value_type MinorType;
public:
///
// Factory method - creates the VersionMetaData from the given metadata node
//
static _Myt* get(const llvm::MDNode* pNode, bool hasId = false)
{
return new _Myt(pNode, hasId);
}
///
// Factory method - create the default empty VersionMetaData object
static _Myt* get()
{
return new _Myt();
}
///
// Factory method - create the default empty named VersionMetaData object
static _Myt* get(const char* name)
{
return new _Myt(name);
}
///
// Ctor - loads the VersionMetaData from the given metadata node
//
VersionMetaData(const llvm::MDNode* pNode, bool hasId);
///
// Default Ctor - creates the empty, not named VersionMetaData object
//
VersionMetaData();
///
// Ctor - creates the empty, named VersionMetaData object
//
VersionMetaData(const char* name);
/// Major related methods
MajorType getMajor() const
{
return m_Major.get();
}
bool isMajorHasValue() const
{
return m_Major.hasValue();
}
/// Minor related methods
MinorType getMinor() const
{
return m_Minor.get();
}
bool isMinorHasValue() const
{
return m_Minor.hasValue();
}
///
// Returns true if any of the VersionMetaData`s members has changed
bool dirty() const;
///
// Returns true if the structure was loaded from the metadata or was changed
bool hasValue() const;
///
// Discards the changes done to the VersionMetaData instance
void discardChanges();
///
// Generates the new MDNode hierarchy for the given structure
llvm::Metadata* generateNode(llvm::LLVMContext& context) const;
///
// Saves the structure changes to the given MDNode
void save(llvm::LLVMContext& context, llvm::MDNode* pNode) const;
private:
///
// Returns true if the given MDNode could be saved to without replacement
bool compatibleWith(const llvm::MDNode* pNode) const
{
return false;
}
private:
typedef MetaDataIterator<llvm::MDNode> NodeIterator;
llvm::Metadata* getMajorNode(const llvm::MDNode* pParentNode) const;
llvm::Metadata* getMinorNode(const llvm::MDNode* pParentNode) const;
private:
// data members
MetaDataValue<int32_t> m_Major;
MetaDataValue<int32_t> m_Minor;
// parent node
const llvm::MDNode* m_pNode;
};
///
// Read/Write the WorkGroupDimensions structure from/to LLVM metadata
//
class WorkGroupDimensionsMetaData :public IMetaDataObject
{
public:
typedef WorkGroupDimensionsMetaData _Myt;
typedef IMetaDataObject _Mybase;
// typedefs for data member types
typedef MetaDataValue<int32_t>::value_type XDimType;
typedef MetaDataValue<int32_t>::value_type YDimType;
typedef MetaDataValue<int32_t>::value_type ZDimType;
public:
///
// Factory method - creates the WorkGroupDimensionsMetaData from the given metadata node
//
static _Myt* get(const llvm::MDNode* pNode, bool hasId = false)
{
return new _Myt(pNode, hasId);
}
///
// Factory method - create the default empty WorkGroupDimensionsMetaData object
static _Myt* get()
{
return new _Myt();
}
///
// Factory method - create the default empty named WorkGroupDimensionsMetaData object
static _Myt* get(const char* name)
{
return new _Myt(name);
}
///
// Ctor - loads the WorkGroupDimensionsMetaData from the given metadata node
//
WorkGroupDimensionsMetaData(const llvm::MDNode* pNode, bool hasId);
///
// Default Ctor - creates the empty, not named WorkGroupDimensionsMetaData object
//
WorkGroupDimensionsMetaData();
///
// Ctor - creates the empty, named WorkGroupDimensionsMetaData object
//
WorkGroupDimensionsMetaData(const char* name);
/// XDim related methods
XDimType getXDim() const
{
return m_XDim.get();
}
bool isXDimHasValue() const
{
return m_XDim.hasValue();
}
/// YDim related methods
YDimType getYDim() const
{
return m_YDim.get();
}
bool isYDimHasValue() const
{
return m_YDim.hasValue();
}
/// ZDim related methods
ZDimType getZDim() const
{
return m_ZDim.get();
}
bool isZDimHasValue() const
{
return m_ZDim.hasValue();
}
///
// Returns true if any of the WorkGroupDimensionsMetaData`s members has changed
bool dirty() const;
///
// Returns true if the structure was loaded from the metadata or was changed
bool hasValue() const;
///
// Discards the changes done to the WorkGroupDimensionsMetaData instance
void discardChanges();
///
// Generates the new MDNode hierarchy for the given structure
llvm::Metadata* generateNode(llvm::LLVMContext& context) const;
///
// Saves the structure changes to the given MDNode
void save(llvm::LLVMContext& context, llvm::MDNode* pNode) const;
private:
///
// Returns true if the given MDNode could be saved to without replacement
bool compatibleWith(const llvm::MDNode* pNode) const
{
return false;
}
private:
typedef MetaDataIterator<llvm::MDNode> NodeIterator;
llvm::Metadata* getXDimNode(const llvm::MDNode* pParentNode) const;
llvm::Metadata* getYDimNode(const llvm::MDNode* pParentNode) const;
llvm::Metadata* getZDimNode(const llvm::MDNode* pParentNode) const;
private:
// data members
MetaDataValue<int32_t> m_XDim;
MetaDataValue<int32_t> m_YDim;
MetaDataValue<int32_t> m_ZDim;
// parent node
const llvm::MDNode* m_pNode;
};
///
// Read/Write the SubGroupDimensions structure from/to LLVM metadata
//
class SubGroupDimensionsMetaData :public IMetaDataObject
{
public:
typedef SubGroupDimensionsMetaData _Myt;
typedef IMetaDataObject _Mybase;
// typedefs for data member types
typedef MetaDataValue<int32_t>::value_type SIMD_SizeType;
public:
///
// Factory method - creates the SubGroupDimensionsMetaData from the given metadata node
//
static _Myt* get(const llvm::MDNode* pNode, bool hasId = false)
{
return new _Myt(pNode, hasId);
}
///
// Factory method - create the default empty SubGroupDimensionsMetaData object
static _Myt* get()
{
return new _Myt();
}
///
// Factory method - create the default empty named SubGroupDimensionsMetaData object
static _Myt* get(const char* name)
{
return new _Myt(name);
}
///
// Ctor - loads the SubGroupDimensionsMetaData from the given metadata node
//
SubGroupDimensionsMetaData(const llvm::MDNode* pNode, bool hasId);
///
// Default Ctor - creates the empty, not named SubGroupDimensionsMetaData object
//
SubGroupDimensionsMetaData();
///
// Ctor - creates the empty, named SubGroupDimensionsMetaData object
//
SubGroupDimensionsMetaData(const char* name);
/// SIMD_Size related methods
SIMD_SizeType getSIMD_Size() const
{
return m_SIMD_Size.get();
}
bool isSIMD_SizeHasValue() const
{
return m_SIMD_Size.hasValue();
}
///
// Returns true if any of the SubGroupDimensionsMetaData`s members has changed
bool dirty() const;
///
// Returns true if the structure was loaded from the metadata or was changed
bool hasValue() const;
///
// Discards the changes done to the SubGroupDimensionsMetaData instance
void discardChanges();
///
// Generates the new MDNode hierarchy for the given structure
llvm::Metadata* generateNode(llvm::LLVMContext& context) const;
///
// Saves the structure changes to the given MDNode
void save(llvm::LLVMContext& context, llvm::MDNode* pNode) const;
private:
///
// Returns true if the given MDNode could be saved to without replacement
bool compatibleWith(const llvm::MDNode* pNode) const
{
return false;
}
private:
typedef MetaDataIterator<llvm::MDNode> NodeIterator;
llvm::Metadata* getSIMD_SizeNode(const llvm::MDNode* pParentNode) const;
private:
// data members
MetaDataValue<int32_t> m_SIMD_Size;
// parent node
const llvm::MDNode* m_pNode;
};
///
// Read/Write the WorkgroupWalkOrder structure from/to LLVM metadata
//
class WorkgroupWalkOrderMetaData :public IMetaDataObject
{
public:
typedef WorkgroupWalkOrderMetaData _Myt;
typedef IMetaDataObject _Mybase;
// typedefs for data member types
typedef MetaDataValue<int32_t>::value_type WalkOrderDimType;
public:
///
// Factory method - creates the SubGroupSizeMetaData from the given metadata node
//
static _Myt* get(const llvm::MDNode* pNode, bool hasId = false)
{
return new _Myt(pNode, hasId);
}
///
// Factory method - create the default empty SubGroupSizeMetaData object
static _Myt* get()
{
return new _Myt();
}
///
// Factory method - create the default empty named SubGroupSizeMetaData object
static _Myt* get(const char* name)
{
return new _Myt(name);
}
///
// Ctor - loads the SubGroupSizeMetaData from the given metadata node
//
WorkgroupWalkOrderMetaData(const llvm::MDNode* pNode, bool hasId);
///
// Default Ctor - creates the empty, not named SubGroupSizeMetaData object
//
WorkgroupWalkOrderMetaData();
///
// Ctor - creates the empty, named SubGroupSizeMetaData object
//
WorkgroupWalkOrderMetaData(const char* name);
/// workgroup walk order related methods
WalkOrderDimType getDim0() const
{
return m_Dim0.get();
}
WalkOrderDimType getDim1() const
{
return m_Dim1.get();
}
WalkOrderDimType getDim2() const
{
return m_Dim2.get();
}
///
// Returns true if any of the SubGroupSizeMetaData`s members has changed
bool dirty() const;
///
// Returns true if the structure was loaded from the metadata or was changed
bool hasValue() const;
///
// Discards the changes done to the SubGroupSizeMetaData instance
void discardChanges();
///
// Generates the new MDNode hierarchy for the given structure
llvm::Metadata* generateNode(llvm::LLVMContext& context) const;
///
// Saves the structure changes to the given MDNode
void save(llvm::LLVMContext& context, llvm::MDNode* pNode) const;
private:
///
// Returns true if the given MDNode could be saved to without replacement
bool compatibleWith(const llvm::MDNode* pNode) const
{
return false;
}
private:
typedef MetaDataIterator<llvm::MDNode> NodeIterator;
llvm::Metadata* getDim0Node(const llvm::MDNode* pParentNode) const;
llvm::Metadata* getDim1Node(const llvm::MDNode* pParentNode) const;
llvm::Metadata* getDim2Node(const llvm::MDNode* pParentNode) const;
private:
// data members
MetaDataValue<int32_t> m_Dim0;
MetaDataValue<int32_t> m_Dim1;
MetaDataValue<int32_t> m_Dim2;
// parent node
const llvm::MDNode* m_pNode;
};
///
// Read/Write the Kernel structure from/to LLVM metadata
//
class KernelMetaData :public IMetaDataObject
{
public:
typedef KernelMetaData _Myt;
typedef IMetaDataObject _Mybase;
// typedefs for data member types
typedef MetaDataValue<llvm::Function>::value_type FunctionType;
typedef MetaDataList<int32_t> ArgAddressSpacesList;
typedef MetaDataList<std::string> ArgAccessQualifiersList;
typedef MetaDataList<std::string> ArgTypesList;
typedef MetaDataList<std::string> ArgBaseTypesList;
typedef MetaDataList<std::string> ArgTypeQualifiersList;
typedef MetaDataList<std::string> ArgNamesList;
public:
///
// Factory method - creates the KernelMetaData from the given metadata node
//
static _Myt* get(const llvm::MDNode* pNode, bool hasId = false)
{
return new _Myt(pNode, hasId);
}
///
// Factory method - create the default empty KernelMetaData object
static _Myt* get()
{
return new _Myt();
}
///
// Factory method - create the default empty named KernelMetaData object
static _Myt* get(const char* name)
{
return new _Myt(name);
}
///
// Ctor - loads the KernelMetaData from the given metadata node
//
KernelMetaData(const llvm::MDNode* pNode, bool hasId);
///
// Default Ctor - creates the empty, not named KernelMetaData object
//
KernelMetaData();
///
// Ctor - creates the empty, named KernelMetaData object
//
KernelMetaData(const char* name);
/// Function related methods
FunctionType getFunction() const
{
return m_Function.get();
}
bool isFunctionHasValue() const
{
return m_Function.hasValue();
}
/// WorkGroupSizeHint related methods
const WorkGroupDimensionsMetaDataHandle getWorkGroupSizeHint()
{
return m_WorkGroupSizeHint;
}
/// RequiredWorkGroupSize related methods
const WorkGroupDimensionsMetaDataHandle getRequiredWorkGroupSize()
{
return m_RequiredWorkGroupSize;
}
/// RequiredSubGroupSize related methods
const SubGroupDimensionsMetaDataHandle getRequiredSubGroupSize()
{
return m_RequiredSubGroupSize;
}
/// WorkgroupWalkOrder related methods
const WorkgroupWalkOrderMetaDataHandle getWorkgroupWalkOrder()
{
return m_WorkgroupWalkOrder;
}
/// VectorTypeHint related methods
const VectorTypeHintMetaDataHandle getVectorTypeHint()
{
return m_VectorTypeHint;
}
/// ArgAddressSpaces related methods
ArgAddressSpacesList::const_iterator begin_ArgAddressSpaces() const
{
return m_ArgAddressSpaces.begin();
}
ArgAddressSpacesList::const_iterator end_ArgAddressSpaces() const
{
return m_ArgAddressSpaces.end();
}
size_t size_ArgAddressSpaces() const
{
return m_ArgAddressSpaces.size();
}
bool empty_ArgAddressSpaces() const
{
return m_ArgAddressSpaces.empty();
}
bool isArgAddressSpacesHasValue() const
{
return m_ArgAddressSpaces.hasValue();
}
const ArgAddressSpacesList::item_type getArgAddressSpacesItem(size_t index) const
{
return m_ArgAddressSpaces.getItem(index);
}
/// ArgAccessQualifiers related methods
ArgAccessQualifiersList::const_iterator begin_ArgAccessQualifiers() const
{
return m_ArgAccessQualifiers.begin();
}
ArgAccessQualifiersList::const_iterator end_ArgAccessQualifiers() const
{
return m_ArgAccessQualifiers.end();
}
size_t size_ArgAccessQualifiers() const
{
return m_ArgAccessQualifiers.size();
}
bool empty_ArgAccessQualifiers() const
{
return m_ArgAccessQualifiers.empty();
}
bool isArgAccessQualifiersHasValue() const
{
return m_ArgAccessQualifiers.hasValue();
}
const ArgAccessQualifiersList::item_type getArgAccessQualifiersItem(size_t index) const
{
return m_ArgAccessQualifiers.getItem(index);
}
/// ArgTypes related methods
ArgTypesList::const_iterator begin_ArgTypes() const
{
return m_ArgTypes.begin();
}
ArgTypesList::const_iterator end_ArgTypes() const
{
return m_ArgTypes.end();
}
size_t size_ArgTypes() const
{
return m_ArgTypes.size();
}
bool empty_ArgTypes() const
{
return m_ArgTypes.empty();
}
bool isArgTypesHasValue() const
{
return m_ArgTypes.hasValue();
}
const ArgTypesList::item_type getArgTypesItem(size_t index) const
{
return m_ArgTypes.getItem(index);
}
/// ArgBaseTypes related methods
ArgBaseTypesList::const_iterator begin_ArgBaseTypes() const
{
return m_ArgBaseTypes.begin();
}
ArgBaseTypesList::const_iterator end_ArgBaseTypes() const
{
return m_ArgBaseTypes.end();
}
size_t size_ArgBaseTypes() const
{
return m_ArgBaseTypes.size();
}
bool empty_ArgBaseTypes() const
{
return m_ArgBaseTypes.empty();
}
bool isArgBaseTypesHasValue() const
{
return m_ArgBaseTypes.hasValue();
}
const ArgBaseTypesList::item_type getArgBaseTypesItem(size_t index) const
{
return m_ArgBaseTypes.getItem(index);
}
/// ArgTypeQualifiers related methods
ArgTypeQualifiersList::const_iterator begin_ArgTypeQualifiers() const
{
return m_ArgTypeQualifiers.begin();
}
ArgTypeQualifiersList::const_iterator end_ArgTypeQualifiers() const
{
return m_ArgTypeQualifiers.end();
}
size_t size_ArgTypeQualifiers() const
{
return m_ArgTypeQualifiers.size();
}
bool empty_ArgTypeQualifiers() const
{
return m_ArgTypeQualifiers.empty();
}
bool isArgTypeQualifiersHasValue() const
{
return m_ArgTypeQualifiers.hasValue();
}
const ArgTypeQualifiersList::item_type getArgTypeQualifiersItem(size_t index) const
{
return m_ArgTypeQualifiers.getItem(index);
}
/// ArgNames related methods
ArgNamesList::const_iterator begin_ArgNames() const
{
return m_ArgNames.begin();
}
ArgNamesList::const_iterator end_ArgNames() const
{
return m_ArgNames.end();
}
size_t size_ArgNames() const
{
return m_ArgNames.size();
}
bool empty_ArgNames() const
{
return m_ArgNames.empty();
}
bool isArgNamesHasValue() const
{
return m_ArgNames.hasValue();
}
const ArgNamesList::item_type getArgNamesItem(size_t index) const
{
return m_ArgNames.getItem(index);
}
///
// Returns true if any of the KernelMetaData`s members has changed
bool dirty() const;
///
// Returns true if the structure was loaded from the metadata or was changed
bool hasValue() const;
///
// Discards the changes done to the KernelMetaData instance
void discardChanges();
///
// Generates the new MDNode hierarchy for the given structure
llvm::Metadata* generateNode(llvm::LLVMContext& context) const;
///
// Saves the structure changes to the given MDNode
void save(llvm::LLVMContext& context, llvm::MDNode* pNode) const;
private:
///
// Returns true if the given MDNode could be saved to without replacement
bool compatibleWith(const llvm::MDNode* pNode) const
{
return false;
}
private:
typedef MetaDataIterator<llvm::MDNode> NodeIterator;
llvm::Metadata* getFunctionNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getWorkGroupSizeHintNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getRequiredWorkGroupSizeNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getRequiredSubGroupSizeNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getWorkgroupWalkOrderNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getVectorTypeHintNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getArgAddressSpacesNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getArgAccessQualifiersNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getArgTypesNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getArgBaseTypesNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getArgTypeQualifiersNode(const llvm::MDNode* pParentNode) const;
llvm::MDNode* getArgNamesNode(const llvm::MDNode* pParentNode) const;
private:
// data members
MetaDataValue<llvm::Function> m_Function;
WorkGroupDimensionsMetaDataHandle m_WorkGroupSizeHint;
WorkGroupDimensionsMetaDataHandle m_RequiredWorkGroupSize;
SubGroupDimensionsMetaDataHandle m_RequiredSubGroupSize;
WorkgroupWalkOrderMetaDataHandle m_WorkgroupWalkOrder;
VectorTypeHintMetaDataHandle m_VectorTypeHint;
MetaDataList<int32_t> m_ArgAddressSpaces;
MetaDataList<std::string> m_ArgAccessQualifiers;
MetaDataList<std::string> m_ArgTypes;
MetaDataList<std::string> m_ArgBaseTypes;
MetaDataList<std::string> m_ArgTypeQualifiers;
MetaDataList<std::string> m_ArgNames;
// parent node
const llvm::MDNode* m_pNode;
};
class SpirMetaDataUtils
{
public:
// typedefs for the data members types
typedef NamedMDNodeList<KernelMetaDataHandle> KernelsList;
typedef NamedMDNodeList<InnerCompilerOptionsMetaDataListHandle> CompilerOptionsList;
typedef NamedMDNodeList<InnerCompilerExternalOptionsMetaDataListHandle> CompilerExternalOptionsList;
typedef NamedMDNodeList<int32_t> FloatingPointContractionsList;
typedef NamedMDNodeList<InnerUsedOptionalCoreFeaturesMetaDataListHandle> UsedOptionalCoreFeaturesList;
typedef NamedMDNodeList<InnerUsedKhrExtensionsMetaDataListHandle> UsedKhrExtensionsList;
typedef NamedMDNodeList<VersionMetaDataHandle> SpirVersionsList;
typedef NamedMDNodeList<VersionMetaDataHandle> OpenCLVersionsList;
public:
// If using this constructor, setting the llvm module by the setModule
// function is needed for correct operation.
SpirMetaDataUtils() {}
SpirMetaDataUtils(llvm::Module* pModule) :
m_Kernels(pModule->getNamedMetadata("opencl.kernels")),
m_CompilerOptions(pModule->getNamedMetadata("opencl.compiler.options")),
m_CompilerExternalOptions(pModule->getNamedMetadata("opencl.compiler.ext.options")),
m_FloatingPointContractions(pModule->getNamedMetadata("opencl.enable.FP_CONTRACT")),
m_UsedOptionalCoreFeatures(pModule->getNamedMetadata("opencl.used.optional.core.features")),
m_UsedKhrExtensions(pModule->getNamedMetadata("opencl.used.extensions")),
m_SpirVersions(pModule->getNamedMetadata("opencl.spir.version")),
m_OpenCLVersions(pModule->getNamedMetadata("opencl.ocl.version")),
m_pModule(pModule)
{
}
void setModule(llvm::Module* pModule) {
m_Kernels = pModule->getNamedMetadata("opencl.kernels");
m_CompilerOptions = pModule->getNamedMetadata("opencl.compiler.options");
m_CompilerExternalOptions = pModule->getNamedMetadata("opencl.compiler.ext.options");
m_FloatingPointContractions = pModule->getNamedMetadata("opencl.enable.FP_CONTRACT");
m_UsedOptionalCoreFeatures = pModule->getNamedMetadata("opencl.used.optional.core.features");
m_UsedKhrExtensions = pModule->getNamedMetadata("opencl.used.extensions");
m_SpirVersions = pModule->getNamedMetadata("opencl.spir.version");
m_OpenCLVersions = pModule->getNamedMetadata("opencl.ocl.version");
m_pModule = pModule;
}
~SpirMetaDataUtils() {}
/// Kernels related methods
KernelsList::const_iterator begin_Kernels() const
{
return m_Kernels.begin();
}
KernelsList::const_iterator end_Kernels() const
{
return m_Kernels.end();
}
size_t size_Kernels() const
{
return m_Kernels.size();
}
bool empty_Kernels() const
{
return m_Kernels.empty();
}
bool isKernelsHasValue() const
{
return m_Kernels.hasValue();
}
const KernelsList::item_type getKernelsItem(size_t index) const
{
return m_Kernels.getItem(index);
}
/// CompilerOptions related methods
CompilerOptionsList::const_iterator begin_CompilerOptions() const
{
return m_CompilerOptions.begin();
}
CompilerOptionsList::const_iterator end_CompilerOptions() const
{
return m_CompilerOptions.end();
}
size_t size_CompilerOptions() const
{
return m_CompilerOptions.size();
}
bool empty_CompilerOptions() const
{
return m_CompilerOptions.empty();
}
bool isCompilerOptionsHasValue() const
{
return m_CompilerOptions.hasValue();
}
const CompilerOptionsList::item_type getCompilerOptionsItem(size_t index) const
{
return m_CompilerOptions.getItem(index);
}
/// CompilerExternalOptions related methods
CompilerExternalOptionsList::const_iterator begin_CompilerExternalOptions() const
{
return m_CompilerExternalOptions.begin();
}
CompilerExternalOptionsList::const_iterator end_CompilerExternalOptions() const
{
return m_CompilerExternalOptions.end();
}
size_t size_CompilerExternalOptions() const
{
return m_CompilerExternalOptions.size();
}
bool empty_CompilerExternalOptions() const
{
return m_CompilerExternalOptions.empty();
}
bool isCompilerExternalOptionsHasValue() const
{
return m_CompilerExternalOptions.hasValue();
}
const CompilerExternalOptionsList::item_type getCompilerExternalOptionsItem(size_t index) const
{
return m_CompilerExternalOptions.getItem(index);
}
/// FloatingPointContractions related methods
FloatingPointContractionsList::const_iterator begin_FloatingPointContractions() const
{
return m_FloatingPointContractions.begin();
}
FloatingPointContractionsList::const_iterator end_FloatingPointContractions() const
{
return m_FloatingPointContractions.end();
}
size_t size_FloatingPointContractions() const
{
return m_FloatingPointContractions.size();
}
bool empty_FloatingPointContractions() const
{
return m_FloatingPointContractions.empty();
}
bool isFloatingPointContractionsHasValue() const
{
return m_FloatingPointContractions.hasValue();
}
const FloatingPointContractionsList::item_type getFloatingPointContractionsItem(size_t index) const
{
return m_FloatingPointContractions.getItem(index);
}
/// UsedOptionalCoreFeatures related methods
UsedOptionalCoreFeaturesList::const_iterator begin_UsedOptionalCoreFeatures() const
{
return m_UsedOptionalCoreFeatures.begin();
}
UsedOptionalCoreFeaturesList::const_iterator end_UsedOptionalCoreFeatures() const
{
return m_UsedOptionalCoreFeatures.end();
}
size_t size_UsedOptionalCoreFeatures() const
{
return m_UsedOptionalCoreFeatures.size();
}
bool empty_UsedOptionalCoreFeatures() const
{
return m_UsedOptionalCoreFeatures.empty();
}
bool isUsedOptionalCoreFeaturesHasValue() const
{
return m_UsedOptionalCoreFeatures.hasValue();
}
const UsedOptionalCoreFeaturesList::item_type getUsedOptionalCoreFeaturesItem(size_t index) const
{
return m_UsedOptionalCoreFeatures.getItem(index);
}
/// UsedKhrExtensions related methods
UsedKhrExtensionsList::const_iterator begin_UsedKhrExtensions() const
{
return m_UsedKhrExtensions.begin();
}
UsedKhrExtensionsList::const_iterator end_UsedKhrExtensions() const
{
return m_UsedKhrExtensions.end();
}
size_t size_UsedKhrExtensions() const
{
return m_UsedKhrExtensions.size();
}
bool empty_UsedKhrExtensions() const
{
return m_UsedKhrExtensions.empty();
}
bool isUsedKhrExtensionsHasValue() const
{
return m_UsedKhrExtensions.hasValue();
}
const UsedKhrExtensionsList::item_type getUsedKhrExtensionsItem(size_t index) const
{
return m_UsedKhrExtensions.getItem(index);
}
/// SpirVersions related methods
SpirVersionsList::const_iterator begin_SpirVersions() const
{
return m_SpirVersions.begin();
}
SpirVersionsList::const_iterator end_SpirVersions() const
{
return m_SpirVersions.end();
}
size_t size_SpirVersions() const
{
return m_SpirVersions.size();
}
bool empty_SpirVersions() const
{
return m_SpirVersions.empty();
}
bool isSpirVersionsHasValue() const
{
return m_SpirVersions.hasValue();
}
const SpirVersionsList::item_type getSpirVersionsItem(size_t index) const
{
return m_SpirVersions.getItem(index);
}
/// OpenCLVersions related methods
OpenCLVersionsList::const_iterator begin_OpenCLVersions() const
{
return m_OpenCLVersions.begin();
}
OpenCLVersionsList::const_iterator end_OpenCLVersions() const
{
return m_OpenCLVersions.end();
}
size_t size_OpenCLVersions() const
{
return m_OpenCLVersions.size();
}
bool empty_OpenCLVersions() const
{
return m_OpenCLVersions.empty();
}
bool isOpenCLVersionsHasValue() const
{
return m_OpenCLVersions.hasValue();
}
const OpenCLVersionsList::item_type getOpenCLVersionsItem(size_t index) const
{
return m_OpenCLVersions.getItem(index);
}
void deleteMetadata()
{
llvm::NamedMDNode* KernelsNode = m_pModule->getNamedMetadata("opencl.kernels");
if (KernelsNode)
{
m_pModule->eraseNamedMetadata(KernelsNode);
}
llvm::NamedMDNode* CompilerOptionsNode = m_pModule->getNamedMetadata("opencl.compiler.options");
if (CompilerOptionsNode)
{
m_pModule->eraseNamedMetadata(CompilerOptionsNode);
}
llvm::NamedMDNode* CompilerExternalOptionsNode = m_pModule->getNamedMetadata("opencl.compiler.ext.options");
if (CompilerExternalOptionsNode)
{
m_pModule->eraseNamedMetadata(CompilerExternalOptionsNode);
}
llvm::NamedMDNode* FloatingPointContractionsNode = m_pModule->getNamedMetadata("opencl.enable.FP_CONTRACT");
if (FloatingPointContractionsNode)
{
m_pModule->eraseNamedMetadata(FloatingPointContractionsNode);
}
llvm::NamedMDNode* UsedOptionalCoreFeaturesNode = m_pModule->getNamedMetadata("opencl.used.optional.core.features");
if (UsedOptionalCoreFeaturesNode)
{
m_pModule->eraseNamedMetadata(UsedOptionalCoreFeaturesNode);
}
llvm::NamedMDNode* UsedKhrExtensionsNode = m_pModule->getNamedMetadata("opencl.used.extensions");
if (UsedKhrExtensionsNode)
{
m_pModule->eraseNamedMetadata(UsedKhrExtensionsNode);
}
llvm::NamedMDNode* SpirVersionsNode = m_pModule->getNamedMetadata("opencl.spir.version");
if (SpirVersionsNode)
{
m_pModule->eraseNamedMetadata(SpirVersionsNode);
}
llvm::NamedMDNode* OpenCLVersionsNode = m_pModule->getNamedMetadata("opencl.ocl.version");
if (OpenCLVersionsNode)
{
m_pModule->eraseNamedMetadata(OpenCLVersionsNode);
}
}
private:
// data members
NamedMDNodeList<KernelMetaDataHandle> m_Kernels;
NamedMDNodeList<InnerCompilerOptionsMetaDataListHandle> m_CompilerOptions;
NamedMDNodeList<InnerCompilerExternalOptionsMetaDataListHandle> m_CompilerExternalOptions;
NamedMDNodeList<int32_t> m_FloatingPointContractions;
NamedMDNodeList<InnerUsedOptionalCoreFeaturesMetaDataListHandle> m_UsedOptionalCoreFeatures;
NamedMDNodeList<InnerUsedKhrExtensionsMetaDataListHandle> m_UsedKhrExtensions;
NamedMDNodeList<VersionMetaDataHandle> m_SpirVersions;
NamedMDNodeList<VersionMetaDataHandle> m_OpenCLVersions;
llvm::Module* m_pModule;
};
}
} //namespace
| 33.726579 | 132 | 0.581235 |
83a30d381ef8de4cc2cc8f8b5fb683ec3b2abe64 | 700 | h | C | Plugins/HammerMapEditor/Source/HammerMapEditor/Public/HammerMapEditorEdMode.h | travmygit/UnrealHammer | 707df28f0039877e3cab329648bfd7a741f358ad | [
"MIT"
] | 1 | 2021-10-20T11:23:22.000Z | 2021-10-20T11:23:22.000Z | Plugins/HammerMapEditor/Source/HammerMapEditor/Public/HammerMapEditorEdMode.h | travmygit/UnrealHammer | 707df28f0039877e3cab329648bfd7a741f358ad | [
"MIT"
] | null | null | null | Plugins/HammerMapEditor/Source/HammerMapEditor/Public/HammerMapEditorEdMode.h | travmygit/UnrealHammer | 707df28f0039877e3cab329648bfd7a741f358ad | [
"MIT"
] | 1 | 2022-03-18T04:13:12.000Z | 2022-03-18T04:13:12.000Z | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "EdMode.h"
class FHammerMapEditorEdMode : public FEdMode
{
public:
const static FEditorModeID EM_HammerMapEditorEdModeId;
public:
FHammerMapEditorEdMode();
virtual ~FHammerMapEditorEdMode();
// FEdMode interface
virtual void Enter() override;
virtual void Exit() override;
//virtual void Tick(FEditorViewportClient* ViewportClient, float DeltaTime) override;
//virtual void Render(const FSceneView* View, FViewport* Viewport, FPrimitiveDrawInterface* PDI) override;
//virtual void ActorSelectionChangeNotify() override;
bool UsesToolkits() const override;
// End of FEdMode interface
};
| 28 | 107 | 0.787143 |
2604f60d2f7fc34ec72e74a417ab1e0bd9155e54 | 2,127 | h | C | Pods/Headers/TapkuLibrary/TKAppDelegate.h | nguyenhuy/GithubStats | 6bdef9a482c931d4aadc1693f345a64598fcc6e5 | [
"MIT"
] | 1 | 2020-11-13T01:37:16.000Z | 2020-11-13T01:37:16.000Z | Pods/Headers/TapkuLibrary/TKAppDelegate.h | nguyenhuy/GithubStats | 6bdef9a482c931d4aadc1693f345a64598fcc6e5 | [
"MIT"
] | null | null | null | Pods/Headers/TapkuLibrary/TKAppDelegate.h | nguyenhuy/GithubStats | 6bdef9a482c931d4aadc1693f345a64598fcc6e5 | [
"MIT"
] | null | null | null | //
// TKAppDelegate.h
// Created by Devin Ross on 1/31/11.
//
/*
tapku.com || http://github.com/devinross/tapkulibrary
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class TKWindow;
/** This class allocates a TKWindow instance and provides a convience method for application launching. */
@interface TKAppDelegate : NSObject <UIApplicationDelegate>
// For subclassing, default implentation does nothing.
// These methods are called upon open & closing respectively regardless.
// Good for placing instructions needed regardless of multi-tasking
/** This is a convience method for placing any functionality that might be called upon initial launch of the application and any subsequent relaunch from a background state. Default implementation does nothing.
@param application The application instance.
*/
- (void) applicationDidStartup:(UIApplication *)application;
///----------------------------
/// @name Properties
///----------------------------
/** Returns the application main window. */
@property (nonatomic,strong) UIWindow *window;
@end
| 36.050847 | 210 | 0.754114 |
23092b074d24ec056de86841befc116267f08fb3 | 384 | h | C | FoodMemory/FoodMemory/Classes/Scenes/Personal/View/LCPPicker.h | LeeSons/FoodMemory | bf158b7a1d753695b370a232bb3ef56e7ca6a521 | [
"MIT"
] | null | null | null | FoodMemory/FoodMemory/Classes/Scenes/Personal/View/LCPPicker.h | LeeSons/FoodMemory | bf158b7a1d753695b370a232bb3ef56e7ca6a521 | [
"MIT"
] | null | null | null | FoodMemory/FoodMemory/Classes/Scenes/Personal/View/LCPPicker.h | LeeSons/FoodMemory | bf158b7a1d753695b370a232bb3ef56e7ca6a521 | [
"MIT"
] | null | null | null | //
// LCPPicker.h
// FoodMemory
//
// Created by morplcp on 15/12/10.
// Copyright © 2015年 morplcp. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void (^CytyBlock)(NSString *city);
@interface LCPPicker : UIView
@property(nonatomic, copy)CytyBlock selectCity;
// 字典初始化
- (instancetype)initWithDictionary:(NSArray *)cityArray;
// 显示
- (void)show;
- (void)close;
@end
| 16.695652 | 56 | 0.697917 |
23c33aa94f1b51d4bf8ae4aaa2a70dd666e51800 | 1,606 | h | C | mingw.throw.h | Cwc-Test/mingw-std-threads | a1e9bf1fed333dc04ec281f8044c7c02fbf43627 | [
"BSD-2-Clause"
] | 1 | 2019-07-14T19:44:54.000Z | 2019-07-14T19:44:54.000Z | mingw.throw.h | Cwc-Test/mingw-std-threads | a1e9bf1fed333dc04ec281f8044c7c02fbf43627 | [
"BSD-2-Clause"
] | null | null | null | mingw.throw.h | Cwc-Test/mingw-std-threads | a1e9bf1fed333dc04ec281f8044c7c02fbf43627 | [
"BSD-2-Clause"
] | null | null | null | /**
* @file mingw.throw.h
* @brief throw helper to enable -fno-exceptions
* (c) 2013-2016 by Mega Limited, Auckland, New Zealand
* @author Maeiky
*
* @copyright Simplified (2-clause) BSD License.
* You should have received a copy of the license along with this
* program.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* @note
* This file may become part of the mingw-w64 runtime package. If/when this happens,
* the appropriate license will be added, i.e. this code will become dual-licensed,
* and the current BSD 2-clause license will stay.
*/
#ifndef MINGW_THROW_H_
#define MINGW_THROW_H_
#if !defined(__cplusplus) || (__cplusplus < 201103L)
#error A C++11 compiler is required!
#endif
#if (defined(__cpp_exceptions) && (__cpp_exceptions >= 199711L)) || \
defined(__EXCEPTIONS) || (!defined(__clang__) && !defined(__GNUC__))
#define MINGW_STDTHREAD_NO_EXCEPTIONS 0
#else
#define MINGW_STDTHREAD_NO_EXCEPTIONS 1
#endif
// Disabling exceptions is very much non-standard behavior. Though C++20 may
// add a feature-test macro, earlier versions do not provide such a mechanism.
// Instead, appropriate compiler-specific macros must be checked.
namespace mingw_stdthread
{
#if MINGW_STDTHREAD_NO_EXCEPTIONS
template<class T, class ... Args>
inline void throw_error (Args&&...)
{
std::abort();
}
#else
template<class T, class ... Args>
inline void throw_error (Args&&... args)
{
throw T(std::forward<Args>(args)...);
}
#endif
}
#endif // MINGW_THROW_H_
| 28.678571 | 83 | 0.742217 |
8af7013b17fbdc20918c0fa5e1b541cedc96ff6e | 5,446 | h | C | Modules/VideoIO/OpenCV/include/itkOpenCVVideoIO.h | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | 1 | 2015-10-12T00:14:09.000Z | 2015-10-12T00:14:09.000Z | Modules/VideoIO/OpenCV/include/itkOpenCVVideoIO.h | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | Modules/VideoIO/OpenCV/include/itkOpenCVVideoIO.h | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 __itkOpenCVVideoIO_h
#define __itkOpenCVVideoIO_h
// Define support for OpenCVVideo
#ifndef ITK_VIDEO_USE_OPENCV
#define ITK_VIDEO_USE_OPENCV
#endif
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include "itkVideoIOBase.h"
#include "cv.h"
#include "highgui.h"
namespace itk
{
/** \class OpenCVVideoIO
*
* \brief VideoIO object for reading and writing videos using OpenCV
*
* \ingroup Video-IO-OpenCV
*/
class ITK_EXPORT OpenCVVideoIO:public VideoIOBase
{
public:
/** Standard class typedefs. */
typedef OpenCVVideoIO Self;
typedef VideoIOBase Superclass;
typedef SmartPointer< Self > Pointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(OpenCVVideoIO, Superclass);
/** Close the reader and writer and reset members */
virtual void FinishReadingOrWriting();
/*-------- This part of the interface deals with reading data. ------ */
/** Set to reading from file */
virtual void SetReadFromFile();
/** Set to reading from a camera */
virtual void SetReadFromCamera();
/** Determine the file type. Returns true if this ImageIO can read the
* file specified. */
virtual bool CanReadFile(const char *);
/** Return whether or not the VideoIO can read from a camera */
virtual bool CanReadCamera( unsigned long cameraID );
/** Set the spacing and dimension information for the set filename. */
virtual void ReadImageInformation();
/** Reads the data from disk into the memory buffer provided. */
virtual void Read(void *buffer);
/** Set the next frame that should be read. Return true if you operation
* succesful */
virtual bool SetNextFrameToRead(unsigned long frameNumber);
/** Accessor functions for video specific information */
virtual double GetPositionInMSec();
virtual double GetRatio();
virtual unsigned long GetFrameTotal();
virtual double GetFpS();
virtual unsigned long GetCurrentFrame();
virtual unsigned int GetIFrameInterval();
virtual unsigned long GetLastIFrame();
/** Get/Set the camera index */
virtual void SetCameraIndex(int idx);
virtual int GetCameraIndex();
/** Override Accessors to pass default values since OpenCV doesn't handle
* this type of meta data. */
virtual double GetSpacing(unsigned int i) const
{ return 1.0; }
virtual double GetOrigin(unsigned int i) const
{ return 0.0; }
virtual std::vector< double > GetDirection(unsigned int i) const
{ return this->GetDefaultDirection(i); }
/*-------- This part of the interfaces deals with writing data. ----- */
/** Determine the file type. Returns true if this ImageIO can write the
* file specified. */
virtual bool CanWriteFile(const char *);
/** Writes the spacing and dimentions of the image.
* Assumes SetFileName has been called with a valid file name. */
virtual void WriteImageInformation();
/** Writes the data to disk from the memory buffer provided. Make sure
* that the IORegion has been set properly. */
virtual void Write(const void *buffer);
/** Set Writer Parameters */
virtual void SetWriterParameters(double fps, std::vector<SizeValueType> dim, const char* fourCC,
unsigned int nChannels, IOComponentType componentType);
/** Try to open a video
* Return true on success, false otherwise.
*/
//virtual bool Open(const char* filename);
/** Try to close a video
* Return true if in case of a success, false for a faillure
* Intended to be overloaded by subclasses */
//virtual bool Close(const char* filename);
/** Return the state of the video (opened or not) **/
//virtual bool IsWriterOpen();
protected:
OpenCVVideoIO();
~OpenCVVideoIO();
void PrintSelf(std::ostream & os, Indent indent) const;
/** Update the local members from the internal capture */
void UpdateReaderProperties();
/** Reset member variables to empty state closed */
void ResetMembers();
/** Open the reader iff the writer is not open */
void OpenReader();
/** Open the writer iff the reader is not open */
void OpenWriter();
private:
OpenCVVideoIO(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
/** Member Variables */
IplImage* m_CVImage;
IplImage* m_TempImage;
CvCapture* m_Capture;
CvVideoWriter* m_Writer;
int m_FourCC;
/** device index for reading from a camera (may move to base class) */
int m_CameraIndex;
};
} // end namespace itk
#endif // __itkOpenCVVideoIO_h
| 30.255556 | 98 | 0.679949 |
1e4659f5af48f653d666f04ce93477c8adaded25 | 15,722 | c | C | vendors/nuvoton/boards/numaker_iot_m487_wifi/ports/pkcs11/iot_pkcs11_pal.c | nateglims/amazon-freertos | 5cc32eb29d935f124101a3584c6d29aa1f5d687d | [
"MIT"
] | 1 | 2019-09-06T21:13:28.000Z | 2019-09-06T21:13:28.000Z | vendors/nuvoton/boards/numaker_iot_m487_wifi/ports/pkcs11/iot_pkcs11_pal.c | nateglims/amazon-freertos | 5cc32eb29d935f124101a3584c6d29aa1f5d687d | [
"MIT"
] | 1 | 2020-05-12T20:39:30.000Z | 2020-07-08T14:15:23.000Z | vendors/nuvoton/boards/numaker_iot_m487_wifi/ports/pkcs11/iot_pkcs11_pal.c | nateglims/amazon-freertos | 5cc32eb29d935f124101a3584c6d29aa1f5d687d | [
"MIT"
] | 9 | 2020-07-31T08:18:18.000Z | 2020-09-07T06:37:13.000Z | /*
* FreeRTOS PKCS #11 PAL for Numaker_PFM_M487 V1.0.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file aws_pkcs11_pal.c
* @brief FreeRTOS device specific helper functions for
* PKCS#11 implementation based on mbedTLS. This
* file deviates from the FreeRTOS style standard for some function names and
* data types in order to maintain compliance with the PKCS#11 standard.
*/
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "FreeRTOSIPConfig.h"
#include "task.h"
#include "iot_pkcs11.h"
#include "iot_pkcs11_config.h"
/* C runtime includes. */
#include <stdio.h>
#include <string.h>
/* flash driver includes. */
#include "NuMicro.h"
//#define pkcs11FILE_NAME_PUBLISHER_CERTIFICATE "FreeRTOS_Publisher_Certificate.dat"
//#define pkcs11FILE_NAME_PUBLISHER_KEY "FreeRTOS_Publisher_Key.dat"
#define pkcs11palFILE_NAME_CLIENT_CERTIFICATE "FreeRTOS_P11_Certificate.dat"
#define pkcs11palFILE_NAME_KEY "FreeRTOS_P11_Key.dat"
#define pkcs11palFILE_CODE_SIGN_PUBLIC_KEY "FreeRTOS_P11_CodeSignKey.dat"
#define pkcs11OBJECT_CERTIFICATE_MAX_SIZE 2048
#define pkcs11OBJECT_FLASH_CERT_PRESENT ( 0x1A2B3C4DUL )
enum eObjectHandles
{
eInvalidHandle = 0, /* From PKCS #11 spec: 0 is never a valid object handle.*/
eAwsDevicePrivateKey = 1,
eAwsDevicePublicKey,
eAwsDeviceCertificate,
eAwsCodeSigningKey
};
/**
* @brief Structure for certificates/key storage.
*/
typedef struct
{
CK_ULONG ulDeviceCertificateMark;
CK_ULONG ulCertificateSize;
CK_CHAR cCertificateData[ pkcs11OBJECT_CERTIFICATE_MAX_SIZE ];
} P11CertData_t;
typedef struct
{
uint32_t DeviceCertificate;
uint32_t DeviceKey;
// uint32_t PublisherCertificate;
// uint32_t PublisherKey;
uint32_t CodeSignKey;
uint32_t ReserveKey;
} P11KeyConfig_t;
/**
* @brief Certificates/key storage in flash.
*/
#define NVT_STORE_BASE ( 0x7B000UL ) /* local storage start address in APROM */
/* Set last 4 pages for certification storage, FMC_FLASH_PAGE_SIZE=4KB */
static P11KeyConfig_t P11KeyConfig ={ NVT_STORE_BASE,
NVT_STORE_BASE + FMC_FLASH_PAGE_SIZE,
NVT_STORE_BASE + FMC_FLASH_PAGE_SIZE*2,
NVT_STORE_BASE + FMC_FLASH_PAGE_SIZE*3};
static P11CertData_t P11CertDataSave;
/*-----------------------------------------------------------*/
static CK_RV prvFLASH_update(uint32_t u32StartAddr, uint8_t * pucData, uint32_t ulDataSize)
{
uint32_t u32Addr; /* flash address */
uint32_t u32data; /* flash data */
uint32_t *pDataSrc; /* flash data */
uint32_t u32EndAddr = (u32StartAddr + sizeof(P11CertData_t));
uint32_t u32Pattern = 0xFFFFFFFF;
FMC_Erase(u32StartAddr);
/* Verify if each data word from flash u32StartAddr to u32EndAddr be 0xFFFFFFFF. */
for (u32Addr = u32StartAddr; u32Addr < u32EndAddr; u32Addr += 4)
{
u32data = FMC_Read(u32Addr); /* Read a flash word from address u32Addr. */
if (u32data != u32Pattern ) /* Verify if data matched. */
{
printf("\nFMC_Read data verify failed at address 0x%x, read=0x%x, expect=0x%x\n", u32Addr, u32data, u32Pattern);
return -1; /* data verify failed */
}
}
memcpy( P11CertDataSave.cCertificateData, pucData, ulDataSize );
P11CertDataSave.ulDeviceCertificateMark = pkcs11OBJECT_FLASH_CERT_PRESENT;
P11CertDataSave.ulCertificateSize = ulDataSize;
pDataSrc = (uint32_t *) &P11CertDataSave;
/* Fill flash range from u32StartAddr to u32EndAddr with data word u32Pattern. */
for (u32Addr = u32StartAddr; u32Addr < u32EndAddr; u32Addr += 4)
{
FMC_Write(u32Addr, *pDataSrc); /* Program flash */
pDataSrc++;
}
return ulDataSize;
}
/* Converts a label to its respective filename and handle. */
static void prvLabelToFilenameHandle( uint8_t * pcLabel,
char ** pcFileName,
CK_OBJECT_HANDLE_PTR pHandle )
{
if( pcLabel != NULL )
{
/* Translate from the PKCS#11 label to local storage file name. */
if( 0 == memcmp( pcLabel,
&pkcs11configLABEL_DEVICE_CERTIFICATE_FOR_TLS,
sizeof( pkcs11configLABEL_DEVICE_CERTIFICATE_FOR_TLS ) ) )
{
*pcFileName = pkcs11palFILE_NAME_CLIENT_CERTIFICATE;
*pHandle = eAwsDeviceCertificate;
}
else if( 0 == memcmp( pcLabel,
&pkcs11configLABEL_DEVICE_PRIVATE_KEY_FOR_TLS,
sizeof( pkcs11configLABEL_DEVICE_PRIVATE_KEY_FOR_TLS ) ) )
{
*pcFileName = pkcs11palFILE_NAME_KEY;
*pHandle = eAwsDevicePrivateKey;
}
else if( 0 == memcmp( pcLabel,
&pkcs11configLABEL_DEVICE_PUBLIC_KEY_FOR_TLS,
sizeof( pkcs11configLABEL_DEVICE_PUBLIC_KEY_FOR_TLS ) ) )
{
*pcFileName = pkcs11palFILE_NAME_KEY;
*pHandle = eAwsDevicePublicKey;
}
else if( 0 == memcmp( pcLabel,
&pkcs11configLABEL_CODE_VERIFICATION_KEY,
sizeof( pkcs11configLABEL_CODE_VERIFICATION_KEY ) ) )
{
*pcFileName = pkcs11palFILE_CODE_SIGN_PUBLIC_KEY;
*pHandle = eAwsCodeSigningKey;
}
else
{
*pcFileName = NULL;
*pHandle = eInvalidHandle;
}
}
}
/**
* @brief Writes a file to local storage.
*
* Port-specific file write for crytographic information.
*
* @param[in] pcFileName The name of the file to be written to.
* @param[in] pucData Data buffer to be written to file
* @param[in] pulDataSize Size (in bytes) of file data.
*
* @return pdTRUE if data was saved successfully to file,
* pdFALSE otherwise.
*/
static BaseType_t prvFLASH_SaveFile( char * pcFileName,
uint8_t * pucData,
uint32_t ulDataSize )
{
CK_RV xResult = pdFALSE;
uint32_t certFlashAddr = 0;
CK_RV xBytesWritten = 0;
CK_ULONG ulFlashMark = pkcs11OBJECT_FLASH_CERT_PRESENT;
const P11CertData_t * pCertFlash;
P11CertData_t * pCertSave = 0;
/* enough room to store the certificate */
if( ulDataSize > pkcs11OBJECT_CERTIFICATE_MAX_SIZE )
{
return xResult;
}
/*
* write client certificate.
*/
SYS_UnlockReg(); /* Unlock register lock protect */
FMC_Open(); /* Enable FMC ISP function */
FMC_ENABLE_AP_UPDATE(); /* Enable APROM update. */
if( strcmp( pcFileName, pkcs11palFILE_NAME_CLIENT_CERTIFICATE ) == 0 )
{
certFlashAddr = P11KeyConfig.DeviceCertificate;
}
else if( strcmp( pcFileName, pkcs11palFILE_NAME_KEY ) == 0 )
{
certFlashAddr = P11KeyConfig.DeviceKey;
}
else if( strcmp( pcFileName, pkcs11palFILE_CODE_SIGN_PUBLIC_KEY ) == 0 )
{
certFlashAddr = P11KeyConfig.CodeSignKey;
}
else
{
certFlashAddr = NULL;
}
if( certFlashAddr != NULL )
{
xBytesWritten = prvFLASH_update( certFlashAddr, pucData, ulDataSize );
if( xBytesWritten == ulDataSize )
{
xResult = pdTRUE;
}
}
FMC_DISABLE_AP_UPDATE(); /* Disable APROM update. */
SYS_LockReg(); /* Lock protected registers */
return xResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Reads a file from local storage.
*
* Port-specific file access for crytographic information.
*
* @param[in] pcFileName The name of the file to be read.
* @param[out] ppucData Pointer to buffer for file data.
* @param[out] pulDataSize Size (in bytes) of data located in file.
*
* @return pdTRUE if data was retrieved successfully from files,
* pdFALSE otherwise.
*/
static BaseType_t prvFLASH_ReadFile( char * pcFileName,
uint8_t ** ppucData,
uint32_t * pulDataSize )
{
CK_RV xResult = pdFALSE;
const P11CertData_t * pCertFlash = 0;
uint32_t certSize = 0;
uint8_t * pCertData = 0;
/*
* Read client certificate.
*/
if( strcmp( pcFileName, pkcs11palFILE_NAME_CLIENT_CERTIFICATE ) == 0 )
{
pCertFlash = (P11CertData_t *)P11KeyConfig.DeviceCertificate;
}
else if( strcmp( pcFileName, pkcs11palFILE_NAME_KEY ) == 0 )
{
pCertFlash = (P11CertData_t *)P11KeyConfig.DeviceKey;
}
else if( strcmp( pcFileName, pkcs11palFILE_CODE_SIGN_PUBLIC_KEY ) == 0 )
{
pCertFlash = (P11CertData_t *)P11KeyConfig.CodeSignKey;
}
if( ( pCertFlash !=0 ) && ( pCertFlash->ulDeviceCertificateMark == pkcs11OBJECT_FLASH_CERT_PRESENT ) )
{
pCertData = ( uint8_t * ) pCertFlash->cCertificateData;
certSize = pCertFlash->ulCertificateSize;
xResult = pdTRUE;
}
*pulDataSize = certSize;
*ppucData = pCertData;
return xResult;
}
CK_RV PKCS11_PAL_Initialize( void )
{
return CKR_OK;
}
/**
* @brief Writes a file to local storage.
*
* Port-specific file write for crytographic information.
*
* @param[in] pxLabel Label of the object to be saved.
* @param[in] pucData Data buffer to be written to file
* @param[in] ulDataSize Size (in bytes) of data to be saved.
*
* @return The file handle of the object that was stored.
*/
CK_OBJECT_HANDLE PKCS11_PAL_SaveObject( CK_ATTRIBUTE_PTR pxLabel,
CK_BYTE_PTR pucData,
CK_ULONG ulDataSize )
{
char *pcFileName = NULL;
CK_OBJECT_HANDLE xHandle = eInvalidHandle;
/* Converts a label to its respective filename and handle. */
prvLabelToFilenameHandle( pxLabel->pValue, &pcFileName, &xHandle );
/* If your project requires additional PKCS#11 objects, add them here. */
if( pcFileName != NULL )
{
if( prvFLASH_SaveFile( pcFileName, pucData, ulDataSize ) == pdFALSE )
{
xHandle = eInvalidHandle;
}
}
return xHandle;
}
/**
* @brief Translates a PKCS #11 label into an object handle.
*
* Port-specific object handle retrieval.
*
*
* @param[in] pxLabel Pointer to the label of the object
* who's handle should be found.
* @param[in] usLength The length of the label, in bytes.
*
* @return The object handle if operation was successful.
* Returns eInvalidHandle if unsuccessful.
*/
CK_OBJECT_HANDLE PKCS11_PAL_FindObject( CK_BYTE_PTR pxLabel,
CK_ULONG usLength )
{
uint8_t *pucData = NULL;
uint32_t dataSize = 0;
/* Avoid compiler warnings about unused variables. */
( void ) usLength;
CK_OBJECT_HANDLE xHandle = eInvalidHandle;
char * pcFileName = NULL;
/* Converts a label to its respective filename and handle. */
prvLabelToFilenameHandle( pxLabel,
&pcFileName,
&xHandle );
if( pcFileName != NULL )
{
/* Check if object exists/has been created before returning. */
if( pdTRUE != prvFLASH_ReadFile( pcFileName, &pucData, &dataSize) )
{
xHandle = eInvalidHandle;
}
}
return xHandle;
}
/**
* @brief Gets the value of an object in storage, by handle.
*
* Port-specific file access for cryptographic information.
*
* This call dynamically allocates the buffer which object value
* data is copied into. PKCS11_PAL_GetObjectValueCleanup()
* should be called after each use to free the dynamically allocated
* buffer.
*
* @sa PKCS11_PAL_GetObjectValueCleanup
*
* @param[in] pcFileName The name of the file to be read.
* @param[out] ppucData Pointer to buffer for file data.
* @param[out] pulDataSize Size (in bytes) of data located in file.
* @param[out] pIsPrivate Boolean indicating if value is private (CK_TRUE)
* or exportable (CK_FALSE)
*
* @return CKR_OK if operation was successful. CKR_KEY_HANDLE_INVALID if
* no such object handle was found, CKR_DEVICE_MEMORY if memory for
* buffer could not be allocated, CKR_FUNCTION_FAILED for device driver
* error.
*/
CK_RV PKCS11_PAL_GetObjectValue( CK_OBJECT_HANDLE xHandle,
CK_BYTE_PTR * ppucData,
CK_ULONG_PTR pulDataSize,
CK_BBOOL * pIsPrivate )
{
CK_RV ulReturn = CKR_OK;
char *pcFileName = NULL;
uint8_t *pucData;
if( xHandle == eAwsDeviceCertificate )
{
pcFileName = pkcs11palFILE_NAME_CLIENT_CERTIFICATE;
*pIsPrivate = CK_FALSE;
}
else if( xHandle == eAwsDevicePrivateKey )
{
pcFileName = pkcs11palFILE_NAME_KEY;
*pIsPrivate = CK_TRUE;
}
else if( xHandle == eAwsDevicePublicKey )
{
/* Public and private key are stored together in same file. */
pcFileName = pkcs11palFILE_NAME_KEY;
*pIsPrivate = CK_FALSE;
}
else if( xHandle == eAwsCodeSigningKey )
{
pcFileName = pkcs11palFILE_CODE_SIGN_PUBLIC_KEY;
*pIsPrivate = CK_FALSE;
}
else
{
ulReturn = CKR_KEY_HANDLE_INVALID;
}
if( pcFileName != NULL )
{
/* Check if object exists/has been created before returning. */
if( pdTRUE != prvFLASH_ReadFile( pcFileName, ppucData, pulDataSize) )
{
xHandle = eInvalidHandle;
}
}
return ulReturn;
}
/**
* @brief Cleanup after PKCS11_GetObjectValue().
*
* @param[in] pucData The buffer to free.
* (*ppucData from PKCS11_PAL_GetObjectValue())
* @param[in] ulDataSize The length of the buffer to free.
* (*pulDataSize from PKCS11_PAL_GetObjectValue())
*/
void PKCS11_PAL_GetObjectValueCleanup( CK_BYTE_PTR pucData,
CK_ULONG ulDataSize )
{
/* Unused parameters. */
( void ) pucData;
( void ) ulDataSize;
/* Since no buffer was allocated on heap, there is no cleanup
* to be done. */
}
| 32.891213 | 124 | 0.626638 |
9f200fa307b6229b10cd11c479cb39017ca93619 | 4,309 | c | C | src/vendor/mariadb-10.6.7/storage/mroonga/vendor/groonga/lib/ts/ts_str.c | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/mroonga/vendor/groonga/lib/ts/ts_str.c | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/mroonga/vendor/groonga/lib/ts/ts_str.c | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z | /* -*- c-basic-offset: 2 -*- */
/*
Copyright(C) 2015 Brazil
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*/
#include "ts_str.h"
#include <ctype.h>
#include <string.h>
/*-------------------------------------------------------------
* Byte.
*/
grn_ts_bool
grn_ts_byte_is_decimal(uint8_t byte)
{
return (byte >= '0') && (byte <= '9');
}
grn_ts_bool
grn_ts_byte_is_name_char(uint8_t byte)
{
/*
* Note: A table name allows '#', '@' and '-'.
* http://groonga.org/docs/reference/commands/table_create.html#name
*/
if (((byte >= '0') && (byte <= '9')) || ((byte >= 'A') && (byte <= 'Z')) ||
((byte >= 'a') && (byte <= 'z')) || (byte == '_')) {
return GRN_TRUE;
}
return GRN_FALSE;
}
/*-------------------------------------------------------------
* String.
*/
grn_ts_bool
grn_ts_str_starts_with(grn_ts_str str, grn_ts_str prefix)
{
if (str.size < prefix.size) {
return GRN_FALSE;
}
return !memcmp(str.ptr, prefix.ptr, prefix.size);
}
grn_ts_str
grn_ts_str_trim_left(grn_ts_str str)
{
size_t i;
for (i = 0; i < str.size; i++) {
if (!isspace((uint8_t)str.ptr[i])) {
break;
}
}
str.ptr += i;
str.size -= i;
return str;
}
grn_ts_str
grn_ts_str_trim_score_assignment(grn_ts_str str)
{
grn_ts_str rest;
str = grn_ts_str_trim_left(str);
if (!grn_ts_str_starts_with(str, (grn_ts_str){ "_score", 6 })) {
return str;
}
rest.ptr = str.ptr + 6;
rest.size = str.size - 6;
rest = grn_ts_str_trim_left(rest);
if (!rest.size || (rest.ptr[0] != '=') ||
((rest.size >= 2) && (rest.ptr[1] == '='))) {
return str;
}
rest.ptr++;
rest.size--;
return grn_ts_str_trim_left(rest);
}
grn_ts_bool
grn_ts_str_has_number_prefix(grn_ts_str str)
{
if (!str.size) {
return GRN_FALSE;
}
if (grn_ts_byte_is_decimal(str.ptr[0])) {
return GRN_TRUE;
}
if (str.size == 1) {
return GRN_FALSE;
}
switch (str.ptr[0]) {
case '+': case '-': {
if (grn_ts_byte_is_decimal(str.ptr[1])) {
return GRN_TRUE;
}
if (str.size == 2) {
return GRN_FALSE;
}
return (str.ptr[1] == '.') && grn_ts_byte_is_decimal(str.ptr[2]);
}
case '.': {
return grn_ts_byte_is_decimal(str.ptr[1]);
}
default: {
return GRN_FALSE;
}
}
}
grn_ts_bool
grn_ts_str_is_name_prefix(grn_ts_str str)
{
size_t i;
for (i = 0; i < str.size; i++) {
if (!grn_ts_byte_is_name_char(str.ptr[i])) {
return GRN_FALSE;
}
}
return GRN_TRUE;
}
grn_ts_bool
grn_ts_str_is_name(grn_ts_str str)
{
if (!str.size) {
return GRN_FALSE;
}
return grn_ts_str_is_name_prefix(str);
}
grn_ts_bool
grn_ts_str_is_true(grn_ts_str str)
{
return (str.size == 4) && !memcmp(str.ptr, "true", 4);
}
grn_ts_bool
grn_ts_str_is_false(grn_ts_str str)
{
return (str.size == 5) && !memcmp(str.ptr, "false", 5);
}
grn_ts_bool
grn_ts_str_is_bool(grn_ts_str str)
{
return grn_ts_str_is_true(str) || grn_ts_str_is_false(str);
}
grn_ts_bool
grn_ts_str_is_id_name(grn_ts_str str)
{
return (str.size == GRN_COLUMN_NAME_ID_LEN) &&
!memcmp(str.ptr, GRN_COLUMN_NAME_ID, GRN_COLUMN_NAME_ID_LEN);
}
grn_ts_bool
grn_ts_str_is_score_name(grn_ts_str str)
{
return (str.size == GRN_COLUMN_NAME_SCORE_LEN) &&
!memcmp(str.ptr, GRN_COLUMN_NAME_SCORE, GRN_COLUMN_NAME_SCORE_LEN);
}
grn_ts_bool
grn_ts_str_is_key_name(grn_ts_str str)
{
return (str.size == GRN_COLUMN_NAME_KEY_LEN) &&
!memcmp(str.ptr, GRN_COLUMN_NAME_KEY, GRN_COLUMN_NAME_KEY_LEN);
}
grn_ts_bool
grn_ts_str_is_value_name(grn_ts_str str)
{
return (str.size == GRN_COLUMN_NAME_VALUE_LEN) &&
!memcmp(str.ptr, GRN_COLUMN_NAME_VALUE, GRN_COLUMN_NAME_VALUE_LEN);
}
| 22.442708 | 80 | 0.64052 |
1b8e794804aef2173513e14d8f768fec3e450032 | 12,110 | h | C | parc/security/parc_Verifier.h | parc-ccnx-archive/Libparc | ea4d62db143c2d54ae51222c969fd600ffc9d28f | [
"BSD-2-Clause"
] | 4 | 2016-10-18T20:00:41.000Z | 2018-10-22T07:55:31.000Z | parc/security/parc_Verifier.h | parc-ccnx-archive/Libparc | ea4d62db143c2d54ae51222c969fd600ffc9d28f | [
"BSD-2-Clause"
] | 9 | 2016-02-03T01:10:07.000Z | 2017-09-04T13:07:55.000Z | parc/security/parc_Verifier.h | parc-ccnx-archive/Libparc | ea4d62db143c2d54ae51222c969fd600ffc9d28f | [
"BSD-2-Clause"
] | 16 | 2016-02-02T00:59:55.000Z | 2019-04-01T18:51:54.000Z | /*
* Copyright (c) 2013-2016, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL XEROX OR PARC 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.
*
* ################################################################################
* #
* # PATENT NOTICE
* #
* # This software is distributed under the BSD 2-clause License (see LICENSE
* # file). This BSD License does not make any patent claims and as such, does
* # not act as a patent grant. The purpose of this section is for each contributor
* # to define their intentions with respect to intellectual property.
* #
* # Each contributor to this source code is encouraged to state their patent
* # claims and licensing mechanisms for any contributions made. At the end of
* # this section contributors may each make their own statements. Contributor's
* # claims and grants only apply to the pieces (source code, programs, text,
* # media, etc) that they have contributed directly to this software.
* #
* # There is no guarantee that this section is complete, up to date or accurate. It
* # is up to the contributors to maintain their portion of this section and up to
* # the user of the software to verify any claims herein.
* #
* # Do not remove this header notification. The contents of this section must be
* # present in all distributions of the software. You may only modify your own
* # intellectual property statements. Please provide contact information.
*
* - Palo Alto Research Center, Inc
* This software distribution does not grant any rights to patents owned by Palo
* Alto Research Center, Inc (PARC). Rights to these patents are available via
* various mechanisms. As of January 2016 PARC has committed to FRAND licensing any
* intellectual property used by its contributions to this software. You may
* contact PARC at cipo@parc.com for more information or visit http://www.ccnx.org
*/
/**
* @file parc_Verifier.h
* @ingroup security
* @brief Structures and functions to support verification.
*
* @author Marc Mosko, Christopher A. Wood, Palo Alto Research Center (Xerox PARC)
* @copyright (c) 2013-2016, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC). All rights reserved.
*/
#ifndef libparc_parc_Verifier_h
#define libparc_parc_Verifier_h
#include <parc/algol/parc_Object.h>
#include <parc/security/parc_CryptoHasher.h>
#include <parc/security/parc_Signature.h>
#include <parc/security/parc_CryptoHashType.h>
#include <parc/security/parc_Key.h>
struct parc_verifier;
typedef struct parc_verifier PARCVerifier;
/**
* @typedef PARCVerifierInterface
* @brief The interface for `PARCVerifier`
*/
typedef struct parc_verifier_interface {
/** @see parcVerifier_GetCryptoHasher */
PARCCryptoHasher *(*GetCryptoHasher)(PARCObject *interfaceContext, PARCKeyId *keyid, PARCCryptoHashType hashType);
/** @see parcVerifier_VerifyDigest */
bool (*VerifyDigest)(PARCObject *interfaceContext, PARCKeyId *keyid, PARCCryptoHash *locallyComputedHash,
PARCCryptoSuite suite, PARCSignature *signatureToVerify);
/** @see parcVerifier_AddKey */
void (*AddKey)(PARCObject *interfaceContext, PARCKey *key);
/** @see parcVerifier_RemoveKeyId */
void (*RemoveKeyId)(PARCObject *interfaceContext, PARCKeyId *keyid);
/** @see parcVerifier_AllowedCryptoSuite */
bool (*AllowedCryptoSuite)(PARCObject *interfaceContext, PARCKeyId *keyid, PARCCryptoSuite suite);
} PARCVerifierInterface;
/**
* Create a verifier context based on a concrete implementation.
*
* @param [in] instance A concrete implementation of a `PARCVerifier`
* @param [in] interfaceContext The interface of a concrete implementation of a `PARCVerifier`
*
* @return NULL A `PARCVerifier` could not be allocated
* @return PARCSigner A new `PARCVerifier` instance derived from the specified concrete signer context.
*
* Example:
* @code
* {
* PARCVerifier *verifier = parcVerifier_Create(verifierInstance, PARCInMemoryVerifierAsVerifier);
* }
* @endcode
*/
PARCVerifier *parcVerifier_Create(PARCObject *instance, PARCVerifierInterface *interfaceContext);
/**
* Assert that an instance of `PARCVerifier` is valid.
*
* If the instance is not valid, terminate via {@link trapIllegalValue}
*
* Valid means the internal state of the type is consistent with its
* required current or future behaviour.
* This may include the validation of internal instances of types.
*
* @param [in] verifier A pointer to a PARCVerifier instance.
*
* Example
* @code
* {
* PARCVerifier *verifier = parcVerifier_Create(verifierInstance, PARCInMemoryVerifierAsVerifier);
*
* parcVerifier_AssertValid(signer);
* }
* @endcode
*/
void parcVerifier_AssertValid(const PARCVerifier *verifier);
/**
* Increase the number of references to the given `PARCVerifier` instance.
*
* A new instance is not created,
* only that the given instance's reference count is incremented.
* Discard the acquired reference by invoking `parcVerifier_Release()`.
*
* @param [in] signer A pointer to a `PARCVerifier` instance.
*
* @return NULL An error occurred.
* @return non-NULL A pointer to a PARCVerifier instance.
*
* Example:
* @code
* {
* PARCVerifier *verifier = parcVerifier_Create(verifierInstance, PARCInMemoryVerifierAsVerifier);
* PARCVerifier *handle = parcVerifier_Acquire(signer);
* // use the handle instance as needed
* }
* @endcode
*/
PARCVerifier *parcVerifier_Acquire(const PARCVerifier *verifier);
/**
* Release a previously acquired reference to the specified instance,
* decrementing the reference count for the instance.
*
* The pointer to the instance is set to NULL as a side-effect of this function.
*
* If the invocation causes the last reference to the instance to be released,
* the instance is deallocated and the instance's implementation will perform
* additional cleanup and release other privately held references.
*
* The contents of the dealloced memory used for the PARC object are undefined.
* Do not reference the object after the last release.
*
* @param [in,out] verifierPtr A pointer to a pointer to the instance to release.
*
* Example:
* @code
* {
* PARCVerifier *verifier = parcVerifier_Create(verifierInstance, PARCInMemoryVerifierAsVerifier);
*
* parcVerifier_Release(&verifier);
* }
* @endcode
*/
void parcVerifier_Release(PARCVerifier **verifierPtr);
/**
* Verify the signature against the provided digest with the specified key.
* If we do not trust the key, the signature will be rejected. In this context,
* trusting a key means that it was previously added to this verifiers "store".
*
* Returns true if the signature is accepted,false if it is rejected.
*
* @param [in] verifier A `PARCVerifier` instance.
* @param [in] keyId A `PARCKeyId` which identifies the verification key.
* @param [in] hashDigest A `PARCCryptoHash` which stores the locally computed digest.
* @param [in] suite The `PARCCryptoSuite` in which verification is performed.
* @param [in] signature The `PARCSignature` which is to be verified.
*
* @retval true If the signature is valid
* @retval false Otherwise
*
* Example:
* @code
* {
* PARCVerifier *verifier = parcVerifier_Create(verifierInstance, PARCInMemoryVerifierAsVerifier);
*
* PARCKeyId *keyId = ...
* PARCCryptoHash *hash = ...
* PARCCryptoSuite suite = PARCCryptoSuite_RSA_SHA256;
* PARCSignature *signature = ...
*
* bool valid = parcVerifier_VerifyDigestSignature(verifier, keyId, hash, suite, signature);
* if (valid) {
* // proceed
* }
* }
* @endcode
*/
bool
parcVerifier_VerifyDigestSignature(PARCVerifier *verifier, PARCKeyId *keyid, PARCCryptoHash *hashDigest,
PARCCryptoSuite suite, PARCSignature *signatureToVerify);
/**
* Check to see if the specified `PARCKeyId` is allowed with the given `PARCCryptoSuite`.
*
* A`PARCKey` identified by the given `PARCKeyId` can only be used for a particular algorithm.
*
* @param [in] verifier A `PARCVerifier` instance with a store of trusted `PARCKey` instances.
* @param [in] keyId A `PARCKeyId` referring to the key we will check against (for this verifier).
* @param [in] suite A `PARCCryptoSuite` to check against.
*
* @retval true If allowed
* @retval false Otherwise
*
* Example:
* @code
* {
* PARCVerifier *verifeir = ...
* PARCKeyId *keyId = ...
* bool isAllowed = parcVerifier_AllowedCryptoSuite(verifier, keyId, PARCCryptoSuite_RSA_SHA256);
* // act accordingly
* }
* @endcode
*/
bool parcVerifier_AllowedCryptoSuite(PARCVerifier *verifier, PARCKeyId *keyId, PARCCryptoSuite suite);
/**
* Returns a `PARCCryptoHasher` for use with the `PARCKeyId`. The caller should have already
* verified that the specified `PARCCryptoHashType` is compatible with the key ID by
* checking the AllowedCryptoSuite.
*
* @param [in] verifier A `PARCVerifier` instance with a store of trusted `PARCKey` instances.
* @param [in] keyId A `PARCKeyId` referring to the key we will check against (for this verifier).
* @param [in] suite A `PARCCryptoSuite` to check against.
*
* @retval non-NULL A `PARCCryptoHasher` instance.
* @retval NULL If the PARCCryptoHashType is not compatible with the key.
*
* Example:
* @code
* {
* PARCVerifier *verifeir = ...
* PARCKeyId *keyId = ...
* bool isAllowed = parcVerifier_AllowedCryptoSuite(verifier, keyId, PARCCryptoHashType_SHA256);
* // act accordingly
* }
* @endcode
*/
PARCCryptoHasher *parcVerifier_GetCryptoHasher(PARCVerifier *verifier, PARCKeyId *keyid, PARCCryptoHashType hashType);
/**
* Add the specified `PARCKey` to the trusted key store.
*
* @param [in] verifier A `PARCVerifier` instance with a store of trusted `PARCKey` instances.
* @param [in] key A `PARCKey` containing the new trusted key.
*
* Example:
* @code
* {
* PARCVerifier *verifeir = ...
* PARCKey *key = ...
* parcVerifier_AddKey(verifier, key);
* }
* @endcode
*/
void parcVerifier_AddKey(PARCVerifier *verifier, PARCKey *key);
/**
* Remove the key associated with the given `PARCKeyId` from the trusted key store.
*
* @param [in] verifier A `PARCVerifier` instance with a store of trusted `PARCKey` instances.
* @param [in] keyId A `PARCKeyId` referencing the `PARCKey` to remove from the keystore.
*
* Example:
* @code
* {
* PARCVerifier *verifeir = ...
* PARCKey *key = ...
* parcVerifier_AddKey(verifier, key);
*
* // Use the verifier with the key...
* ...
*
* // Now remove it because we no longer need or trust it.
* PARCKeyId *keyId = parcKey_GetKeyId(key);
* parcVerifier_RemoveKeyId(verifier, keyId);
* }
* @endcode
*/
void parcVerifier_RemoveKeyId(PARCVerifier *verifier, PARCKeyId *keyid);
#endif // libparc_parc_Verifier_h
| 38.690096 | 119 | 0.725268 |
15d1dc9fde0c6a84cfbae3572d2a2a212de24fc8 | 6,893 | c | C | src/core/stream.c | pperisin/protobluff | eaa99a8bad8e622a550e9903d2ee3e5fd2472f48 | [
"MIT"
] | null | null | null | src/core/stream.c | pperisin/protobluff | eaa99a8bad8e622a550e9903d2ee3e5fd2472f48 | [
"MIT"
] | null | null | null | src/core/stream.c | pperisin/protobluff | eaa99a8bad8e622a550e9903d2ee3e5fd2472f48 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2013-2017 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "core/buffer.h"
#include "core/common.h"
#include "core/stream.h"
#include "core/varint.h"
/* ----------------------------------------------------------------------------
* Stream read callbacks
* ------------------------------------------------------------------------- */
/*!
* Read a variable-sized integer.
*
* \param[in,out] stream Stream
* \param[in] type Type
* \param[out] value Pointer receiving value
* \return Error code
*/
static pb_error_t
read_varint(pb_stream_t *stream, pb_type_t type, void *value) {
assert(stream && value);
size_t size = pb_varint_unpack(type,
pb_buffer_data_from(stream->buffer, stream->offset),
pb_stream_left(stream), value);
return likely_(size != 0)
? pb_stream_advance(stream, size)
: PB_ERROR_VARINT;
}
/*!
* Read a fixed-sized 64-bit value.
*
* \param[in,out] stream Stream
* \param[in] type Type
* \param[out] value Pointer receiving value
* \return Error code
*/
static pb_error_t
read_64bit(pb_stream_t *stream, pb_type_t type, void *value) {
assert(stream && value);
if (unlikely_(pb_stream_advance(stream, 8)))
return PB_ERROR_OFFSET;
memcpy(value, pb_buffer_data_from(
stream->buffer, stream->offset - 8), 8);
return PB_ERROR_NONE;
}
/*!
* Read a length-prefixed value.
*
* \param[in,out] stream Stream
* \param[in] type Type
* \param[out] value Pointer receiving value
* \return Error code
*/
static pb_error_t
read_length(pb_stream_t *stream, pb_type_t type, void *value) {
assert(stream && value);
uint32_t length = 0;
size_t size = pb_varint_unpack_uint32(
pb_buffer_data_from(stream->buffer, stream->offset),
pb_stream_left(stream), &length);
if (likely_(size != 0)) {
*(pb_string_t *)value = pb_string_init(
pb_buffer_data_from(stream->buffer,
stream->offset + size), length);
return pb_stream_advance(stream, size + length);
}
return PB_ERROR_VARINT;
}
/*!
* Read a fixed-sized 32-bit value.
*
* \param[in,out] stream Stream
* \param[in] type Type
* \param[out] value Pointer receiving value
* \return Error code
*/
static pb_error_t
read_32bit(pb_stream_t *stream, pb_type_t type, void *value) {
assert(stream && value);
if (unlikely_(pb_stream_advance(stream, 4)))
return PB_ERROR_OFFSET;
memcpy(value, pb_buffer_data_from(
stream->buffer, stream->offset - 4), 4);
return PB_ERROR_NONE;
}
/* ----------------------------------------------------------------------------
* Stream skip callbacks
* ------------------------------------------------------------------------- */
/*!
* Skip a variable-sized integer.
*
* \param[in,out] stream Stream
* \return Error code
*/
static pb_error_t
skip_varint(pb_stream_t *stream) {
assert(stream);
size_t size = pb_varint_scan(
pb_buffer_data_from(stream->buffer, stream->offset),
pb_stream_left(stream));
return likely_(size != 0)
? pb_stream_advance(stream, size)
: PB_ERROR_VARINT;
}
/*!
* Skip a fixed-sized 64-bit value.
*
* \param[in,out] stream Stream
* \return Error code
*/
static pb_error_t
skip_64bit(pb_stream_t *stream) {
assert(stream);
return pb_stream_advance(stream, 8);
}
/*!
* Skip a length-prefixed value.
*
* \param[in,out] stream Stream
* \return Error code
*/
static pb_error_t
skip_length(pb_stream_t *stream) {
assert(stream);
uint32_t length = 0;
size_t size = pb_varint_unpack_uint32(
pb_buffer_data_from(stream->buffer, stream->offset),
pb_stream_left(stream), &length);
return likely_(size != 0)
? pb_stream_advance(stream, size + length)
: PB_ERROR_VARINT;
}
/*!
* Skip a fixed-sized 32-bit value.
*
* \param[in,out] stream Stream
* \return Error code
*/
static pb_error_t
skip_32bit(pb_stream_t *stream) {
assert(stream);
return pb_stream_advance(stream, 4);
}
/* ----------------------------------------------------------------------------
* Jump tables
* ------------------------------------------------------------------------- */
/*! Jump table: type ==> read method */
const pb_stream_read_f
pb_stream_read_jump[] = {
[PB_TYPE_INT32] = read_varint,
[PB_TYPE_INT64] = read_varint,
[PB_TYPE_UINT32] = read_varint,
[PB_TYPE_UINT64] = read_varint,
[PB_TYPE_SINT32] = read_varint,
[PB_TYPE_SINT64] = read_varint,
[PB_TYPE_FIXED32] = read_32bit,
[PB_TYPE_FIXED64] = read_64bit,
[PB_TYPE_SFIXED32] = read_32bit,
[PB_TYPE_SFIXED64] = read_64bit,
[PB_TYPE_BOOL] = read_varint,
[PB_TYPE_ENUM] = read_varint,
[PB_TYPE_FLOAT] = read_32bit,
[PB_TYPE_DOUBLE] = read_64bit,
[PB_TYPE_STRING] = read_length,
[PB_TYPE_BYTES] = read_length,
[PB_TYPE_MESSAGE] = read_length
};
/*! Jump table: wiretype ==> skip method */
const pb_stream_skip_f
pb_stream_skip_jump[7] = {
[PB_WIRETYPE_VARINT] = skip_varint,
[PB_WIRETYPE_64BIT] = skip_64bit,
[PB_WIRETYPE_LENGTH] = skip_length,
[PB_WIRETYPE_32BIT] = skip_32bit
};
/* ----------------------------------------------------------------------------
* Interface
* ------------------------------------------------------------------------- */
/*!
* Advance a stream by the given number of bytes.
*
* \param[in,out] stream Stream
* \param[in] advance Bytes to advance
* \return Error code
*/
extern pb_error_t
pb_stream_advance(pb_stream_t *stream, size_t advance) {
assert(stream);
if (unlikely_(pb_stream_left(stream) < advance))
return PB_ERROR_OFFSET;
stream->offset += advance;
return PB_ERROR_NONE;
}
| 29.583691 | 79 | 0.627593 |
120a96a5613055c4c23955796b8c9f8184a45617 | 1,170 | c | C | src/image.c | Theys96/GalaxySim | b208dd4562dc6628ceac0e2d40f0f7e9561a9438 | [
"BSD-3-Clause"
] | 3 | 2019-09-10T22:08:03.000Z | 2021-05-29T03:55:10.000Z | src/image.c | Theys96/GalaxySim | b208dd4562dc6628ceac0e2d40f0f7e9561a9438 | [
"BSD-3-Clause"
] | null | null | null | src/image.c | Theys96/GalaxySim | b208dd4562dc6628ceac0e2d40f0f7e9561a9438 | [
"BSD-3-Clause"
] | null | null | null | #include "image.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Image newImage(int width, int height) {
Image img;
img.width = width;
img.bytewidth = width % 8 == 0 ? width/8 : width/8 + 1;
img.height = height;
img.img = (byte**)calloc(height, sizeof(byte*));
for (int y = 0; y < height; y++) {
img.img[y] = calloc(img.bytewidth, sizeof(byte));
memset(img.img[y], 255, img.bytewidth);
}
return img;
}
void setPixel(Image img, int x, int y, int val) {
if (val) {
img.img[y][x/8] &= ~(1UL << (7-x%8));
} else {
img.img[y][x/8] |= 1UL << (7-x%8);
}
}
void saveImage(Image img, char* filename) {
FILE* pgmimg = fopen(filename, "wb");
fprintf(pgmimg, "P4\n"); // Magic bytes
fprintf(pgmimg, "%d %d\n", img.width, img.height); // Dimensions
for (int i = 0; i < img.height; i++) {
for (int j = 0; j < img.bytewidth ; j++) {
fprintf(pgmimg, "%c", img.img[i][j]);
}
}
fprintf(pgmimg, "\n");
fclose(pgmimg);
}
void freeImage(Image img) {
for (int i = 0; i < img.height; i++) {
free(img.img[i]);
}
free(img.img);
}
| 24.375 | 72 | 0.531624 |
4b39c7ec567e1c4a0184b83cae081b6ea52b9782 | 2,092 | h | C | agge/renderer_parallel.h | soyzhc/agge | bf6b2b0f76178524b6f19baeec9dfba81e251086 | [
"MIT"
] | 96 | 2015-02-02T11:18:44.000Z | 2022-01-24T13:41:13.000Z | agge/renderer_parallel.h | soyzhc/agge | bf6b2b0f76178524b6f19baeec9dfba81e251086 | [
"MIT"
] | 8 | 2018-01-13T11:44:54.000Z | 2021-04-18T17:25:47.000Z | agge/renderer_parallel.h | soyzhc/agge | bf6b2b0f76178524b6f19baeec9dfba81e251086 | [
"MIT"
] | 16 | 2017-11-19T03:08:22.000Z | 2020-09-11T08:30:35.000Z | #pragma once
#include "parallel.h"
#include "renderer.h"
namespace agge
{
class renderer_parallel : noncopyable
{
public:
explicit renderer_parallel(count_t parallelism);
~renderer_parallel();
template <typename BitmapT, typename MaskT, typename BlenderT, typename AlphaFn>
void operator ()(BitmapT &bitmap_, vector_i offset, const rect_i *window, const MaskT &mask,
const BlenderT &blender, const AlphaFn &alpha);
private:
raw_memory_object * const _scanline_caches; // Not an exception safe, but faster to place this one here...
parallel _parallel; // ... before this member, despite its constructor may throw.
const count_t _parallelism;
};
inline renderer_parallel::renderer_parallel(count_t parallelism)
: _scanline_caches(new raw_memory_object[parallelism]), _parallel(parallelism),
_parallelism(parallelism)
{ }
inline renderer_parallel::~renderer_parallel()
{ delete []_scanline_caches; }
template <typename BitmapT, typename MaskT, typename BlenderT, typename AlphaFn>
void renderer_parallel::operator ()(BitmapT &bitmap_, vector_i offset, const rect_i *window,
const MaskT &mask, const BlenderT &blender, const AlphaFn &alpha)
{
typedef renderer::adapter<BitmapT, BlenderT> rendition_adapter;
struct kernel_function : parallel::kernel_function, noncopyable
{
kernel_function(const rendition_adapter &adapter_, const renderer_parallel &renderer_, const MaskT &mask_,
const AlphaFn &alpha_)
: adapter(adapter_), renderer(renderer_), mask(mask_), alpha(alpha_)
{ }
virtual void operator ()(count_t threadid)
{
rendition_adapter ra_thread(adapter);
scanline_adapter<rendition_adapter> sl(ra_thread, renderer._scanline_caches[threadid], mask.width());
render(sl, mask, alpha, threadid, renderer._parallelism);
}
const rendition_adapter &adapter;
const renderer_parallel &renderer;
const MaskT &mask;
const AlphaFn α
};
const rendition_adapter adapter(bitmap_, offset, window, blender);
kernel_function kernel(adapter, *this, mask, alpha);
_parallel.call(kernel);
}
}
| 31.223881 | 109 | 0.75478 |
bbc7727e05b02b031d640bfb8a7925ec67e1a655 | 7,083 | h | C | src/engine/utils/include/halley/utils/utils.h | Healthire/halley | aa58e1abe22cda9e80637922721c03574779cd81 | [
"Apache-2.0"
] | null | null | null | src/engine/utils/include/halley/utils/utils.h | Healthire/halley | aa58e1abe22cda9e80637922721c03574779cd81 | [
"Apache-2.0"
] | null | null | null | src/engine/utils/include/halley/utils/utils.h | Healthire/halley | aa58e1abe22cda9e80637922721c03574779cd81 | [
"Apache-2.0"
] | null | null | null | /*****************************************************************\
__
/ /
/ / __ __
/ /______ _______ / / / / ________ __ __
/ ______ \ /_____ \ / / / / / _____ | / / / /
/ / | / _______| / / / / / / /____/ / / / / /
/ / / / / _____ / / / / / / _______/ / / / /
/ / / / / /____/ / / / / / / |______ / |______/ /
/_/ /_/ |________/ / / / / \_______/ \_______ /
/_/ /_/ / /
/ /
High Level Game Framework /_/
---------------------------------------------------------------
Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
This file is subject to the terms of halley_license.txt.
\*****************************************************************/
#pragma once
#include <algorithm>
#include <limits>
#include <list>
#include <cmath>
#include <memory>
#include <array>
#include <functional>
#include <halley/data_structures/vector.h>
#include <gsl/gsl_assert>
#ifdef _MSC_VER
#include <xmmintrin.h>
#endif
namespace Halley {
// General aliases
using Byte = unsigned char;
using Bytes = Vector<Byte>;
template <typename T>
constexpr inline T clamp(T value, T minValue, T maxValue)
{
return std::min(std::max(minValue, value), maxValue);
}
template <typename T>
constexpr inline T clamp2(T value, T minValue, T maxValue)
{
return std::max(minValue, std::min(value, maxValue));
}
template <typename T>
constexpr inline T maxAbs(T a, T b)
{
return abs(a) > abs(b) ? a : b;
}
template <typename T>
constexpr inline T minAbs(T a, T b)
{
return abs(a) < abs(b) ? a : b;
}
template <typename T>
constexpr inline bool rangeIntersection(T s1, T e1, T s2, T e2)
{
return (s1 < e2) && (s2 < e1);
}
constexpr double pi()
{
return 3.1415926535897932384626433832795;
}
// Endianness conversion
//const bool IS_BIG_ENDIAN = *((short*)"AB") == 0x4243;
constexpr bool IS_BIG_ENDIAN = false;
template <typename T>
constexpr inline T FixEndian(T t)
{
if (IS_BIG_ENDIAN) {
T temp = t;
unsigned char *v = reinterpret_cast<unsigned char*>(&temp);
for (size_t i=0; i<sizeof(T)/2; i++) {
std::swap(v[i], v[sizeof(T)-1-i]);
}
return temp;
} else {
return t;
}
}
template<>
constexpr inline char FixEndian<char>(char t) {
return t;
}
template<>
constexpr inline unsigned char FixEndian<unsigned char>(unsigned char t) {
return t;
}
// True modulo definition
template <typename T> constexpr inline T modulo (T a, T b)
{
static_assert(std::is_signed<T>::value, "Must be signed to use modulo operation");
T res = a % b;
if (res < 0) res = b+res;
return res;
}
template <typename T> constexpr inline T floatModulo (T a, T b)
{
if (b == 0) return a;
return a - b * std::floor(a/b);
}
template <> constexpr inline float modulo (float a, float b) { return floatModulo(a, b); }
template <> constexpr inline double modulo (double a, double b) { return floatModulo(a, b); }
// Float floor division (e.g. -0.5 / 2 = -1.0)
template <typename T>
constexpr inline T floorDivFloat (T a, T b)
{
return floor(a / b);
}
// Int floor division (e.g. -2 / 3 = -1)
template <typename T>
constexpr inline T floorDivInt (T a, T b)
{
T result = a / b;
if (a % b < 0) {
--result;
}
return result;
}
// Generic floor divs
constexpr inline float floorDiv (float a, float b) { return floorDivFloat(a, b); }
constexpr inline double floorDiv (double a, double b) { return floorDivFloat(a, b); }
constexpr inline long floorDiv (long a, long b) { return floorDivInt(a, b); }
constexpr inline int floorDiv (int a, int b) { return floorDivInt(a, b); }
constexpr inline short floorDiv (short a, short b) { return floorDivInt(a, b); }
constexpr inline char floorDiv (char a, char b) { return floorDivInt(a, b); }
// Interpolation
template <typename T>
constexpr inline T interpolate(T a, T b, float factor) {
return static_cast<T>(a * (1 - factor) + b * factor);
}
template <typename T>
constexpr inline T lerp(T a, T b, float factor) {
return static_cast<T>(a * (1 - factor) + b * factor);
}
// Smoothing
template <typename T>
constexpr inline T smoothCos(T a) {
return T((1-cos(a * 3.1415926535897932384626433832795))*0.5);
}
// ASR (attack-sustain-release) envelope
// Returns 0 at start of attack and end of release, 1 during sustain
// Attack and release are linear interpolations
template <typename T>
constexpr inline T asr(T x, T a, T s, T r) {
if (x < a) return x/a;
T as = a+s;
if (x < as) return 1;
return 1 - ((x-as)/r);
}
// Next power of 2
template<typename T>
constexpr static T nextPowerOf2(T val)
{
--val;
val = (val >> 1) | val;
val = (val >> 2) | val;
val = (val >> 4) | val;
val = (val >> 8) | val;
val = (val >> 16) | val;
return val+1;
}
constexpr inline int fastLog2Floor (uint32_t value) {
// From https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
constexpr int tab32[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
Expects(value > 0);
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
return tab32[uint32_t(value * 0x07C4ACDD) >> 27];
}
constexpr inline int fastLog2Floor (uint64_t value)
{
// From https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
constexpr int tab64[64] = { 63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5};
Expects(value > 0);
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
value |= value >> 32;
return tab64[uint64_t((value - (value >> 1)) * 0x07EDD5E59A4E28C2) >> 58];
}
constexpr inline int fastLog2Ceil (uint32_t value)
{
return fastLog2Floor(value - 1) + 1;
}
constexpr inline int fastLog2Ceil (uint64_t value)
{
return fastLog2Floor(value - 1) + 1;
}
// Advance a to b by up to inc
template<typename T>
constexpr static T advance(T a, T b, T inc)
{
if (a < b) return std::min(a+inc, b);
else return std::max(a-inc, b);
}
// Align address
template <typename T>
constexpr T alignUp(T val, T align)
{
return val + (align - (val % align)) % align;
}
template <typename T>
constexpr T alignDown(T val, T align)
{
return (val / align) * align;
}
// Prefetch data from memory
static inline void prefetchL1(void* p) {
#ifdef _MSC_VER
_mm_prefetch(static_cast<const char*>(p), _MM_HINT_T0);
#else
__builtin_prefetch(p);
#endif
}
static inline void prefetchL2(void* p) {
#ifdef _MSC_VER
_mm_prefetch(static_cast<const char*>(p), _MM_HINT_T1);
#else
__builtin_prefetch(p);
#endif
}
}
| 26.330855 | 287 | 0.592687 |
f4c4a73b33cec62f95794b269dc6f2d72cf8c4e0 | 197 | h | C | TicTacToe_Minimax/pch.h | lukechu10/TicTacToe-Minimax | 5b3ff4a81cef64cbd7a213db06090c830e13492e | [
"MIT"
] | 9 | 2019-02-15T05:42:23.000Z | 2021-02-23T05:00:39.000Z | TicTacToe_Minimax/pch.h | lukechu10/TicTacToe-Minimax | 5b3ff4a81cef64cbd7a213db06090c830e13492e | [
"MIT"
] | 1 | 2021-08-31T16:36:53.000Z | 2021-08-31T16:36:53.000Z | TicTacToe_Minimax/pch.h | lukechu10/TicTacToe-Minimax | 5b3ff4a81cef64cbd7a213db06090c830e13492e | [
"MIT"
] | null | null | null | #ifndef PCH_H
#define PCH_H
// TODO: add headers that you want to pre-compile here
#include <vector>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <napi.h>
#endif //PCH_H | 16.416667 | 54 | 0.725888 |
0abbbd0f690399d71d01680805baac6352e7ce4a | 6,565 | c | C | vos/tae53_changes/src/lib/tae/qparmtask.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/tae53_changes/src/lib/tae/qparmtask.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/tae53_changes/src/lib/tae/qparmtask.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | /****************************************************************************
* Copyright (c) 1993, 1994
* Century Computing, Inc.
* ALL RIGHTS RESERVED
*
* The software (programs, data bases and/or documentation) on or in
* any media can not be reproduced, disclosed, or used except under
* the terms of the TAE Plus Software License Agreement.
*
***************************************************************************/
/* TDM CHECKOUT FILE_TIME= 9-SEP-1986 14:15 DUA1:[TAEV1.OLB]QPARMTASK.C;2 */
/* TDM CHECKOUT FILE_TIME=27-JUN-1984 10:13 DUA0:[TAEV1.OLB]QPARMTASK.C;5 */
/*
* q_ functions to send a V-block using inter-task communication.
* The V-block can be built using q_functions in other source files.
*
* CHANGE LOG:
*
* 04-may-84 Move IMPORT declarations...lim
* 04-may-84 VALUE_x to xVAL ... ces
* 27-jun-84 save_string name change to q_save...palm
* change alloc_var to q_alloc...palm
* 24-aug-84 Abort process if called in batch mode...dm
* 22-jul-85 Change $runtype to tae_runtyp to aviod UNIX
* (GOULD/UTX) compilation error...dm
* 14-sep-86 Fix PR1138/1139 (x_error loop). Check application
* type and write message to stdout from q_sndp...dm
* 04-apr-88 Added string size in call to q_alloc...tpl
* 05-mar-89 new q_cmd and q_cmdwait...palm
*/
#include "taeconf.inp" /* TAE configuration (REQUIRED) */
#include "symtab.inc" /* TM symbol table */
#include "parblk.inc" /* parameter block definitions */
#include "resinc.inc" /* restricted allocation package */
#include "terminc.inc"
#include "syninc.inc"
#include "taeintproto.h"
/* Standard XQ/XR error messages and error keys: */
IMPORT TEXT pm_room[], pk_room[];
#define NOROOM {x_error((*p).mode, pm_room, pk_room, (uintptr_t) name, 0, 0); \
return (P_NOROOM); }
/*
* q_dynp. Send V-block to TM for dynamic parameters.
*/
FUNCTION CODE q_dynp
(
struct PARBLK *p, /* V-block to send */
TEXT pdfspec[], /* pdf file spec */
FUNINT mode /* M_SUBPDF or M_FULLPDF */
)
{
IMPORT TEXT tae_runtyp[]; /* INTER/BATCH/ASYNC */
TEXT *pstr;
struct VARIABLE *v;
TEXT name[6];
CODE code;
if (s_equal(tae_runtyp, "BATCH")) /* if invoked from a batch job */
{
x_error((*p).mode,
"Dynamic parameteres from TAE are not available in batch mode",
"TAE-DYNBATCH", 0, 0, 0);
}
/* The PDF file spec is set to the string value of the variable named
_PROC.
*/
s_copy ("_PROC", name);
v = p_fvar(p, name);
if (v == NULL) /* if not already there, make it*/
{
v = q_alloc(&(*p).symtab, (*p).pool, name, V_STRING, 1, 0);
if (v == NULL)
NOROOM
(*v).v_class = V_LOCAL;
}
pstr = q_save((*p).pool, pdfspec);
if (pstr == NULL)
NOROOM
SVAL(*v, 0) = pstr;
code = q_sndp(p, mode); /* send to TM */
return (code);
}
/* q_cmd. Send a command string to TM to be executed.
*
* The command may be any TCL command and the command runs
* in the context of the process PDF and it can use the
* context of the process PDF. When the command is complete
* the new process PDF context must be received via
* p_inim. You can examine the received parblk for $SFI/$SKEY
* to see if it worked ok or you may grab command output values
* from the parblk.
*
* The command may not be a synchronous process (or a procedure
* that runs a synchronous proess). You may however, submit
* procs that run asynchronously with commands like:
*
* "xyz |runtype=asyc| x=36"
*
* When p_inim completes, the proc has been started.
* If you then want to wait on termination of the async proc,
* send the command "wait-async".
*
*/
FUNCTION CODE q_cmd (TEXT* command)
{
int code;
struct PARBLK parblk;
TEXT *vv[1];
q_init (&parblk, sizeof parblk.pool, P_ABORT); /* build a parblk */
vv[0] = command;
q_string (&parblk, "_COMMAND", 1, vv, P_ADD); /* add _command */
code = q_sndp (&parblk, M_COMMAND); /* send to TM */
return (code);
}
/* q_cmdwait. Do a q_cmd and wait for completion.
*
* This is for callers who don't need the full parblk output
* of a command. The return code is the $SFI of the
* executed command.
*/
FUNCTION CODE q_cmdwait (TEXT *command)
{
int code;
struct PARBLK parblk;
struct VARIABLE *sfi;
code = q_cmd (command); /* execute command */
if (code != SUCCESS)
return (code);
p_inim (&parblk, P_BYTES, P_ABORT); /* get result */
sfi = p_find (&parblk, "$SFI"); /* completion code */
if (sfi)
return (IVAL(*sfi,0));
else
return (P_BADNAME);
}
/*
* q_out. Send output V-block to TAE monitor.
*
* TBD: How to determine P_BADNAME error code in q_out
*/
FUNCTION CODE q_out
(
struct PARBLK *p /* V-block */
)
{
CODE code;
code = q_sndp(p, M_OUTPUT); /* send to TM */
return(code);
}
/*
* q_sndp. Send V-block to parent task.
*
* TBD: q_sndp has an exit() which should be more formal (e.g., $SFI).
* NOTE: q_sndp should not call x_error to avoid infilte loop.
*/
FUNCTION CODE q_sndp
(
struct PARBLK *p, /* PARBLK to send */
FUNINT msgtype /* P_OUTPUT, P_SUBPDF, P_FULLPDF*/
)
{
IMPORT CODE applic_type; /* Application type: 'c'/FORTRAN */
CODE code;
CODE termtype, lines, cols; /* terminal info */
TEXT msgbuf[STRINGSIZ+1];
makerel(&(*p).symtab, (*p).pool); /* make pointers relative */
(*p).msgtyp = msgtype; /* set message type */
(*p).blksiz = r_top((*p).pool) - (GENPTR)p;
code = c_sndp((GENPTR)p, (*p).blksiz);
(*p).hostcode = code; /* save host error code */
if ((code != SUCCESS) && ((*p).mode == P_ABORT))
{
t_init(&lines, &cols, &termtype); /* get terminal type */
if (termtype == T_CRT) /* we have got a terminal */
{
sprintf(msgbuf,
"[TAE-NOCOMM] TAE failure communicating from application to TM. Code %d.",
code);
t_write(msgbuf, T_STDCC); /* write error msg */
}
/* Also write the msg to standard output file. (NOTE: the p_/m_msgout
* routines do the necessary checking.)
*/
sprintf(msgbuf,
"TAE failure communicating from application to TM. Code %d.", code);
if (applic_type == C_TYPE) /* application in 'c' */
m_msgout(msgbuf, "TAE-NOCOMM");
else if (applic_type == FORTRAN_TYPE)
p_msgout(msgbuf, "TAE-NOCOMM"); /* FORTN application */
else
; /* unknown type; do nothing */
procexit(code); /* exit the process */
}
makeabs(&(*p).symtab, (*p).pool); /* make pool absolute again */
return (code);
}
| 28.920705 | 79 | 0.619497 |
e426dd1ccb98b818d76412de43fe27380cbc23bb | 9,891 | c | C | games/hack/hack.trap.c | weiss/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 114 | 2015-01-18T22:55:52.000Z | 2022-02-17T10:45:02.000Z | games/hack/hack.trap.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | null | null | null | games/hack/hack.trap.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 29 | 2015-11-03T22:05:22.000Z | 2022-02-08T15:36:37.000Z | /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/* hack.trap.c - version 1.0.3 */
#include "hack.h"
extern struct monst *makemon();
char vowels[] = "aeiou";
char *traps[] = {
" bear trap",
"n arrow trap",
" dart trap",
" trapdoor",
" teleportation trap",
" pit",
" sleeping gas trap",
" piercer",
" mimic"
};
struct trap *
maketrap(x,y,typ)
register x,y,typ;
{
register struct trap *ttmp;
ttmp = newtrap();
ttmp->ttyp = typ;
ttmp->tseen = 0;
ttmp->once = 0;
ttmp->tx = x;
ttmp->ty = y;
ttmp->ntrap = ftrap;
ftrap = ttmp;
return(ttmp);
}
dotrap(trap) register struct trap *trap; {
register int ttype = trap->ttyp;
nomul(0);
if(trap->tseen && !rn2(5) && ttype != PIT)
pline("You escape a%s.", traps[ttype]);
else {
trap->tseen = 1;
switch(ttype) {
case SLP_GAS_TRAP:
pline("A cloud of gas puts you to sleep!");
nomul(-rnd(25));
break;
case BEAR_TRAP:
if(Levitation) {
pline("You float over a bear trap.");
break;
}
u.utrap = 4 + rn2(4);
u.utraptype = TT_BEARTRAP;
pline("A bear trap closes on your foot!");
break;
case PIERC:
deltrap(trap);
if(makemon(PM_PIERCER,u.ux,u.uy)) {
pline("A piercer suddenly drops from the ceiling!");
if(uarmh)
pline("Its blow glances off your helmet.");
else
(void) thitu(3,d(4,6),"falling piercer");
}
break;
case ARROW_TRAP:
pline("An arrow shoots out at you!");
if(!thitu(8,rnd(6),"arrow")){
mksobj_at(ARROW, u.ux, u.uy);
fobj->quan = 1;
}
break;
case TRAPDOOR:
if(!xdnstair) {
pline("A trap door in the ceiling opens and a rock falls on your head!");
if(uarmh) pline("Fortunately, you are wearing a helmet!");
losehp(uarmh ? 2 : d(2,10),"falling rock");
mksobj_at(ROCK, u.ux, u.uy);
fobj->quan = 1;
stackobj(fobj);
if(Invisible) newsym(u.ux, u.uy);
} else {
register int newlevel = dlevel + 1;
while(!rn2(4) && newlevel < 29)
newlevel++;
pline("A trap door opens up under you!");
if(Levitation || u.ustuck) {
pline("For some reason you don't fall in.");
break;
}
goto_level(newlevel, FALSE);
}
break;
case DART_TRAP:
pline("A little dart shoots out at you!");
if(thitu(7,rnd(3),"little dart")) {
if(!rn2(6))
poisoned("dart","poison dart");
} else {
mksobj_at(DART, u.ux, u.uy);
fobj->quan = 1;
}
break;
case TELEP_TRAP:
if(trap->once) {
deltrap(trap);
newsym(u.ux,u.uy);
vtele();
} else {
newsym(u.ux,u.uy);
tele();
}
break;
case PIT:
if(Levitation) {
pline("A pit opens up under you!");
pline("You don't fall in!");
break;
}
pline("You fall into a pit!");
u.utrap = rn1(6,2);
u.utraptype = TT_PIT;
losehp(rnd(6),"fall into a pit");
selftouch("Falling, you");
break;
default:
impossible("You hit a trap of type %u", trap->ttyp);
}
}
}
mintrap(mtmp) register struct monst *mtmp; {
register struct trap *trap = t_at(mtmp->mx, mtmp->my);
register int wasintrap = mtmp->mtrapped;
if(!trap) {
mtmp->mtrapped = 0; /* perhaps teleported? */
} else if(wasintrap) {
if(!rn2(40)) mtmp->mtrapped = 0;
} else {
register int tt = trap->ttyp;
int in_sight = cansee(mtmp->mx,mtmp->my);
extern char mlarge[];
if(mtmp->mtrapseen & (1 << tt)) {
/* he has been in such a trap - perhaps he escapes */
if(rn2(4)) return(0);
}
mtmp->mtrapseen |= (1 << tt);
switch (tt) {
case BEAR_TRAP:
if(index(mlarge, mtmp->data->mlet)) {
if(in_sight)
pline("%s is caught in a bear trap!",
Monnam(mtmp));
else
if(mtmp->data->mlet == 'o')
pline("You hear the roaring of an angry bear!");
mtmp->mtrapped = 1;
}
break;
case PIT:
/* there should be a mtmp/data -> floating */
if(!index("EywBfk'& ", mtmp->data->mlet)) { /* ab */
mtmp->mtrapped = 1;
if(in_sight)
pline("%s falls in a pit!", Monnam(mtmp));
}
break;
case SLP_GAS_TRAP:
if(!mtmp->msleep && !mtmp->mfroz) {
mtmp->msleep = 1;
if(in_sight)
pline("%s suddenly falls asleep!",
Monnam(mtmp));
}
break;
case TELEP_TRAP:
rloc(mtmp);
if(in_sight && !cansee(mtmp->mx,mtmp->my))
pline("%s suddenly disappears!",
Monnam(mtmp));
break;
case ARROW_TRAP:
if(in_sight) {
pline("%s is hit by an arrow!",
Monnam(mtmp));
}
mtmp->mhp -= 3;
break;
case DART_TRAP:
if(in_sight) {
pline("%s is hit by a dart!",
Monnam(mtmp));
}
mtmp->mhp -= 2;
/* not mondied here !! */
break;
case TRAPDOOR:
if(!xdnstair) {
mtmp->mhp -= 10;
if(in_sight)
pline("A trap door in the ceiling opens and a rock hits %s!", monnam(mtmp));
break;
}
if(mtmp->data->mlet != 'w'){
fall_down(mtmp);
if(in_sight)
pline("Suddenly, %s disappears out of sight.", monnam(mtmp));
return(2); /* no longer on this level */
}
break;
case PIERC:
break;
default:
impossible("Some monster encountered a strange trap.");
}
}
return(mtmp->mtrapped);
}
selftouch(arg) char *arg; {
if(uwep && uwep->otyp == DEAD_COCKATRICE){
pline("%s touch the dead cockatrice.", arg);
pline("You turn to stone.");
killer = objects[uwep->otyp].oc_name;
done("died");
}
}
float_up(){
if(u.utrap) {
if(u.utraptype == TT_PIT) {
u.utrap = 0;
pline("You float up, out of the pit!");
} else {
pline("You float up, only your leg is still stuck.");
}
} else
pline("You start to float in the air!");
}
float_down(){
register struct trap *trap;
pline("You float gently to the ground.");
if(trap = t_at(u.ux,u.uy))
switch(trap->ttyp) {
case PIERC:
break;
case TRAPDOOR:
if(!xdnstair || u.ustuck) break;
/* fall into next case */
default:
dotrap(trap);
}
pickup(1);
}
vtele() {
#include "def.mkroom.h"
register struct mkroom *croom;
for(croom = &rooms[0]; croom->hx >= 0; croom++)
if(croom->rtype == VAULT) {
register x,y;
x = rn2(2) ? croom->lx : croom->hx;
y = rn2(2) ? croom->ly : croom->hy;
if(teleok(x,y)) {
teleds(x,y);
return;
}
}
tele();
}
tele() {
extern coord getpos();
coord cc;
register int nux,nuy;
if(Teleport_control) {
pline("To what position do you want to be teleported?");
cc = getpos(1, "the desired position"); /* 1: force valid */
/* possible extensions: introduce a small error if
magic power is low; allow transfer to solid rock */
if(teleok(cc.x, cc.y)){
teleds(cc.x, cc.y);
return;
}
pline("Sorry ...");
}
do {
nux = rnd(COLNO-1);
nuy = rn2(ROWNO);
} while(!teleok(nux, nuy));
teleds(nux, nuy);
}
teleds(nux, nuy)
register int nux,nuy;
{
if(Punished) unplacebc();
unsee();
u.utrap = 0;
u.ustuck = 0;
u.ux = nux;
u.uy = nuy;
setsee();
if(Punished) placebc(1);
if(u.uswallow){
u.uswldtim = u.uswallow = 0;
docrt();
}
nomul(0);
if(levl[nux][nuy].typ == POOL && !Levitation)
drown();
(void) inshop();
pickup(1);
if(!Blind) read_engr_at(u.ux,u.uy);
}
teleok(x,y) register int x,y; { /* might throw him into a POOL */
return( isok(x,y) && !IS_ROCK(levl[x][y].typ) && !m_at(x,y) &&
!sobj_at(ENORMOUS_ROCK,x,y) && !t_at(x,y)
);
/* Note: gold is permitted (because of vaults) */
}
dotele() {
extern char pl_character[];
if(
#ifdef WIZARD
!wizard &&
#endif WIZARD
(!Teleportation || u.ulevel < 6 ||
(pl_character[0] != 'W' && u.ulevel < 10))) {
pline("You are not able to teleport at will.");
return(0);
}
if(u.uhunger <= 100 || u.ustr < 6) {
pline("You miss the strength for a teleport spell.");
return(1);
}
tele();
morehungry(100);
return(1);
}
placebc(attach) int attach; {
if(!uchain || !uball){
impossible("Where are your chain and ball??");
return;
}
uball->ox = uchain->ox = u.ux;
uball->oy = uchain->oy = u.uy;
if(attach){
uchain->nobj = fobj;
fobj = uchain;
if(!carried(uball)){
uball->nobj = fobj;
fobj = uball;
}
}
}
unplacebc(){
if(!carried(uball)){
freeobj(uball);
unpobj(uball);
}
freeobj(uchain);
unpobj(uchain);
}
level_tele() {
register int newlevel;
if(Teleport_control) {
char buf[BUFSZ];
do {
pline("To what level do you want to teleport? [type a number] ");
getlin(buf);
} while(!digit(buf[0]) && (buf[0] != '-' || !digit(buf[1])));
newlevel = atoi(buf);
} else {
newlevel = 5 + rn2(20); /* 5 - 24 */
if(dlevel == newlevel)
if(!xdnstair) newlevel--; else newlevel++;
}
if(newlevel >= 30) {
if(newlevel > MAXLEVEL) newlevel = MAXLEVEL;
pline("You arrive at the center of the earth ...");
pline("Unfortunately it is here that hell is located.");
if(Fire_resistance) {
pline("But the fire doesn't seem to harm you.");
} else {
pline("You burn to a crisp.");
dlevel = maxdlevel = newlevel;
killer = "visit to the hell";
done("burned");
}
}
if(newlevel < 0) {
newlevel = 0;
pline("You are now high above the clouds ...");
if(Levitation) {
pline("You float gently down to earth.");
done("escaped");
}
pline("Unfortunately, you don't know how to fly.");
pline("You fall down a few thousand feet and break your neck.");
dlevel = 0;
killer = "fall";
done("died");
}
goto_level(newlevel, FALSE); /* calls done("escaped") if newlevel==0 */
}
drown()
{
pline("You fall into a pool!");
pline("You can't swim!");
if(rn2(3) < u.uluck+2) {
/* most scrolls become unreadable */
register struct obj *obj;
for(obj = invent; obj; obj = obj->nobj)
if(obj->olet == SCROLL_SYM && rn2(12) > u.uluck)
obj->otyp = SCR_BLANK_PAPER;
/* we should perhaps merge these scrolls ? */
pline("You attempt a teleport spell."); /* utcsri!carroll */
(void) dotele();
if(levl[u.ux][u.uy].typ != POOL) return;
}
pline("You drown ...");
killer = "pool of water";
done("drowned");
}
| 22.078125 | 76 | 0.587099 |
1727772a6f19b1fbc8e5fe15c4fd691d143d0ccd | 1,618 | h | C | fnet_stack/service/link/fnet_link_config.h | lightelf76/FNET | e92b46faa098283f443e0efa57b5c0e111f43a5b | [
"Apache-2.0"
] | 93 | 2016-07-02T11:40:02.000Z | 2022-03-30T11:08:48.000Z | fnet_stack/service/link/fnet_link_config.h | lightelf76/FNET | e92b46faa098283f443e0efa57b5c0e111f43a5b | [
"Apache-2.0"
] | 7 | 2019-08-17T09:35:57.000Z | 2021-08-22T20:39:43.000Z | fnet_stack/service/link/fnet_link_config.h | lightelf76/FNET | e92b46faa098283f443e0efa57b5c0e111f43a5b | [
"Apache-2.0"
] | 34 | 2016-08-18T09:20:17.000Z | 2021-12-25T15:03:15.000Z | /**************************************************************************
*
* Copyright 2016-2018 by Andrey Butok. FNET Community.
*
***************************************************************************
*
* 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 _FNET_LINK_CONFIG_H_
#define _FNET_LINK_CONFIG_H_
/*! @addtogroup fnet_link_config */
/*! @{ */
/**************************************************************************/ /*!
* @def FNET_CFG_LINK
* @brief Link-detection service support:
* - @c 1..n = is enabled. Its value defines maximum number of
* the Link-Detection services that can be run simultaneously.
* - @b @c 0 = is disabled (Default value).
******************************************************************************/
#ifndef FNET_CFG_LINK
#define FNET_CFG_LINK (0)
#endif
/*! @} */
#ifdef FNET_CFG_LINK_MAX
#error "FNET_CFG_LINK_MAX parameter is obsolete. Use FNET_CFG_LINK."
#endif
#endif /*_FNET_LINK_CONFIG_H_ */
| 35.955556 | 80 | 0.52843 |
cb748aad7987c0c489dac00fe4afae8a64159882 | 4,058 | c | C | api/src/string_iterator.c | francois-berder/AwaLWM2M | 40f30cd4c18ace0b82f64983ac1e28537fbcaae6 | [
"BSD-3-Clause"
] | null | null | null | api/src/string_iterator.c | francois-berder/AwaLWM2M | 40f30cd4c18ace0b82f64983ac1e28537fbcaae6 | [
"BSD-3-Clause"
] | null | null | null | api/src/string_iterator.c | francois-berder/AwaLWM2M | 40f30cd4c18ace0b82f64983ac1e28537fbcaae6 | [
"BSD-3-Clause"
] | null | null | null | /************************************************************************************************************************
Copyright (c) 2016, Imagination Technologies Limited and/or its affiliated group companies.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************************************************************************************/
#include "string_iterator.h"
#include "iterator.h"
#include "memalloc.h"
#include "log.h"
struct _StringIterator
{
Iterator * Iterator;
};
StringIterator * StringIterator_New(void)
{
StringIterator * iterator = Awa_MemAlloc(sizeof (*iterator));
if (iterator != NULL)
{
memset(iterator, 0, sizeof(*iterator));
iterator->Iterator = Iterator_New();
LogNew("StringIterator", iterator);
}
else
{
LogErrorWithEnum(AwaError_OutOfMemory);
}
return iterator;
}
void StringIterator_Free(StringIterator ** iterator)
{
if ((iterator != NULL) && (*iterator != NULL))
{
// free memory managed by iterator:
Iterator_FreeValues((*iterator)->Iterator);
Iterator_Free(&(*iterator)->Iterator);
LogFree("StringIterator", *iterator);
Awa_MemSafeFree(*iterator);
*iterator = NULL;
}
}
void StringIterator_Add(StringIterator * iterator, const char * string)
{
if (iterator != NULL)
{
if (string != NULL)
{
// allocate memory, to be managed by iterator:
char * newString = strdup(string);
if (newString != NULL)
{
Iterator_Add(iterator->Iterator, newString);
}
else
{
LogErrorWithEnum(AwaError_Internal, "unable to allocate memory for string");
}
}
else
{
LogErrorWithEnum(AwaError_Internal, "string is NULL");
}
}
else
{
LogErrorWithEnum(AwaError_IteratorInvalid, "iterator is NULL");
}
}
bool StringIterator_Next(StringIterator * iterator)
{
bool result = false;
if (iterator != NULL)
{
result = Iterator_Next(iterator->Iterator);
}
else
{
LogErrorWithEnum(AwaError_IteratorInvalid, "iterator is NULL");
}
return result;
}
const char * StringIterator_Get(const StringIterator * iterator)
{
const char * string = NULL;
if (iterator != NULL)
{
string = (const char *)Iterator_Get(iterator->Iterator);
}
else
{
LogErrorWithEnum(AwaError_IteratorInvalid, "iterator is NULL");
}
return string;
}
| 34.10084 | 121 | 0.635781 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.